text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Request } from 'express'; import rimraf from 'rimraf'; import * as msRest from '@azure/ms-rest-js'; import { ExtensionContext } from '../../models/extension/extensionContext'; import { BotProjectService } from '../../services/project'; import AssetService from '../../services/asset'; import { ProjectController } from '../../controllers/project'; import { Path } from '../../utility/path'; jest.mock('@bfc/server-workers', () => ({ ServerWorker: { execute: jest.fn(), }, })); jest.mock('../../models/extension/extensionContext', () => { return { ExtensionContext: { extensions: { botTemplates: [], baseTemplates: [], publish: [], }, getUserFromRequest: jest.fn(), }, }; }); const mockSendRequest = jest.fn(); msRest.ServiceClient.prototype.sendRequest = mockSendRequest; const mockSampleBotPath = Path.join(__dirname, '../../__mocks__/asset/projects/SampleBot'); let mockRes: any; const newBot = Path.resolve(__dirname, '../../__mocks__/samplebots/newBot'); const saveAsDir = Path.resolve(__dirname, '../../__mocks__/samplebots/saveAsBot'); const useFortest = Path.resolve(__dirname, '../../__mocks__/samplebots/test'); const bot1 = Path.resolve(__dirname, '../../__mocks__/samplebots/bot1'); const location1 = { storageId: 'default', path: bot1, }; const location2 = { storageId: 'default', path: useFortest, }; beforeEach(() => { mockRes = { status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis(), send: jest.fn().mockReturnThis(), sendStatus: jest.fn().mockReturnThis(), }; mockRes.status.mockClear(); mockRes.json.mockClear(); mockRes.send.mockClear(); mockRes.sendStatus.mockClear(); }); beforeAll(async () => { ExtensionContext.extensions.botTemplates.push({ id: 'SampleBot', name: 'Sample Bot', description: 'Sample Bot', path: mockSampleBotPath, }); const currentProjectId = await BotProjectService.openProject(location1); const currentProject = await BotProjectService.getProjectById(currentProjectId); await BotProjectService.saveProjectAs(currentProject, location2); }); afterAll(() => { // remove the new bot files try { rimraf.sync(newBot); rimraf.sync(saveAsDir); rimraf.sync(useFortest); } catch (error) { throw new Error(error); } }); describe('get bot project', () => { it('should get no project', async () => { const mockReq = { params: {}, query: {}, body: {}, } as Request; await ProjectController.getProjectById(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(404); expect(mockRes.json).toHaveBeenCalledWith({ message: 'project undefined not found in cache', }); }); it('should get current project', async () => { const mockReq = { params: {}, query: {}, body: { storageId: 'default', path: Path.resolve(__dirname, '../../__mocks__/samplebots/bot1'), isRootBot: true }, } as Request; await ProjectController.openProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('get all projects', () => { it('should get all project', async () => { const mockReq = { params: {}, query: {}, body: { storageId: 'default', path: Path.resolve(__dirname, '../../__mocks__/samplebots') }, } as Request; await ProjectController.getAllProjects(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('open bot operation', () => { it('should fail to open an unexisting bot', async () => { const mockReq = { params: {}, query: {}, body: { storageId: 'default', path: 'wrong/path' }, } as Request; await ProjectController.openProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(400); expect(mockRes.json).toHaveBeenCalledWith({ message: 'file wrong/path does not exist', }); }); it('should open bot1', async () => { const mockReq = { params: {}, query: {}, body: { storageId: 'default', path: Path.resolve(__dirname, '../../__mocks__/samplebots/bot1'), isRootBot: true }, } as Request; await ProjectController.openProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('should save as bot', () => { const saveAsDir = Path.resolve(__dirname, '../../__mocks__/samplebots/'); it('saveProjectAs', async () => { const projectId = await BotProjectService.openProject(location1); const schemaUrl = 'http://json-schema.org/draft-07/schema#'; const mockReq = { params: { projectId }, query: {}, body: { storageId: 'default', location: saveAsDir, description: '', name: 'saveAsBot', schemaUrl }, } as Request; await ProjectController.saveProjectAs(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); // remove the saveas files }); }); describe('should get recent projects', () => { it('should get recent projects', async () => { const mockReq = { params: {}, query: {}, body: {}, } as Request; await ProjectController.getRecentProjects(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('create a component model conversational core bot project', () => { const newBotDir = Path.resolve(__dirname, '../../__mocks__/samplebots/'); const name = 'newConversationalCoreBot'; const mockReq = { params: {}, query: {}, body: { storageId: 'default', location: newBotDir, description: '', name: name, templateId: 'generator-conversational-core', templateVersion: '1.0.9', }, } as Request; it('should start to create a new project', async () => { BotProjectService.createProjectAsync = jest.fn(); ProjectController.createProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(202); }); }); //current opened bot is the newBot describe('dialog operation', () => { let projectId = ''; beforeEach(async () => { projectId = await BotProjectService.openProject(location2); }); it('should update dialog', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'bot1.dialog', content: JSON.stringify({ $kind: 'aaa' }) }, } as Request; await ProjectController.updateFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should create dialog', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'test2.dialog', content: JSON.stringify({ $kind: 'aaa' }) }, } as Request; await ProjectController.createFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should remove dialog', async () => { const mockReq = { params: { name: 'test2.dialog', projectId }, query: {}, body: {}, } as Request; await ProjectController.removeFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); //current opened bot is the newBot describe('dialog schema operation', () => { let projectId = ''; beforeEach(async () => { projectId = await BotProjectService.openProject(location2); }); it('should create dialog schema', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'test2.dialog.schema', content: '' }, } as Request; await ProjectController.createFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should update dialog schema', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'test2.dialog.schema', content: '' }, } as Request; await ProjectController.updateFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should remove dialog schema', async () => { const mockReq = { params: { name: 'test2.dialog.schema', projectId }, query: {}, body: {}, } as Request; await ProjectController.removeFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('lg operation', () => { let projectId = ''; beforeEach(async () => { projectId = await BotProjectService.openProject(location2); }); it('should update lg file', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'common.en-us.lg', content: '' }, } as Request; await ProjectController.updateFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should create lg file', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'test1.en-us.lg', content: '' }, } as Request; await ProjectController.createFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should remove lg file', async () => { const mockReq = { params: { name: 'test1.en-us.lg', projectId }, query: {}, body: {}, } as Request; await ProjectController.removeFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('lu operation', () => { let projectId = ''; beforeEach(async () => { projectId = await BotProjectService.openProject(location2); }); it('should update lu file', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'b.en-us.lu', content: '' }, } as Request; await ProjectController.updateFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should create lu file', async () => { const mockReq = { params: { projectId }, query: {}, body: { name: 'c.en-us.lu', content: '' }, } as Request; await ProjectController.createFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); it('should remove lu file', async () => { const mockReq = { params: { name: 'c.en-us.lu', projectId }, query: {}, body: {}, } as Request; await ProjectController.removeFile(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('skill operation', () => { let projectId = ''; beforeEach(async () => { projectId = await BotProjectService.openProject(location2); }); it('should retrieve skill manifest', async () => { mockSendRequest.mockResolvedValue({}); const url = 'https://yuesuemailskill0207-gjvga67.azurewebsites.net/manifest/manifest-1.0.json'; const mockReq = { params: { projectId }, query: { url, }, body: {}, } as Request; await ProjectController.getSkill(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); expect(mockSendRequest).toHaveBeenCalledWith({ url, method: 'GET', }); }, 10000); it('should create skill files', async () => { const url = 'https://yuesuemailskill0207-gjvga67.azurewebsites.net/manifest/manifest-1.0.json'; const mockReq = { params: { projectId }, body: { url, skillName: 'manifest', zipContent: {}, }, } as Request; await ProjectController.createSkillFiles(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }, 10000); it('should remove skill files', async () => { const mockReq = { params: { projectId, name: 'manifest' }, } as Request; await ProjectController.removeSkillFiles(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }, 10000); }); // TODO: add a success publish test. describe('publish luis files', () => { let projectId = ''; beforeEach(async () => { projectId = await BotProjectService.openProject(location1); }); it('should publish all luis & qna files', async () => { const mockReq = { params: { projectId }, query: {}, body: { authoringKey: '0d4991873f334685a9686d1b48e0ff48', projectId: projectId, crossTrainConfig: {}, luFiles: [], }, setTimeout: (msecs: number, callback: () => any): void => {}, } as Request & { setTimeout }; await ProjectController.build(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalled(); }); }); describe('remove project', () => { let projectId = ''; beforeEach(async () => { projectId = await BotProjectService.openProject(location2); }); it('should remove current project', async () => { const mockReq = { params: { projectId }, query: {}, body: {}, } as Request; await ProjectController.removeProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); }); }); describe('getting a project by alias', () => { let getProjectByAliasBackup; beforeEach(() => { getProjectByAliasBackup = BotProjectService.getProjectByAlias; }); afterEach(() => { BotProjectService.getProjectByAlias = getProjectByAliasBackup; }); it('should get a project by its alias if it exists', async () => { const mockReq: any = { params: { alias: 'my-bot.alias', }, }; const mockBotProject = { id: 'botId', dir: '/path/to/bot', exists: jest.fn().mockResolvedValue(true), name: 'my-bot', }; BotProjectService.getProjectByAlias = jest.fn().mockResolvedValueOnce(mockBotProject); await ProjectController.getProjectByAlias(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); expect(mockRes.json).toHaveBeenCalledWith({ location: mockBotProject.dir, id: mockBotProject.id, name: 'my-bot', }); }); it('should return a 404 if no matching project is found for the alias', async () => { const mockReq: any = { params: { alias: 'my-bot.non-existent-alias', }, }; BotProjectService.getProjectByAlias = jest.fn().mockResolvedValueOnce(undefined); await ProjectController.getProjectByAlias(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(404); expect(mockRes.json).toHaveBeenCalledWith({ message: 'No matching bot project found for alias my-bot.non-existent-alias', }); }); it('should return a 400 if no alias is sent with the request', async () => { const mockReq: any = { params: { alias: undefined, }, }; await ProjectController.getProjectByAlias(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(400); expect(mockRes.json).toHaveBeenCalledWith({ message: 'Parameters not provided, requires "alias" parameter', }); }); it('should return a 500 if an error is thrown', async () => { const mockReq: any = { params: { alias: 'my-bot.alias', }, }; const error = new Error('Something went wrong while getting the project by alias'); BotProjectService.getProjectByAlias = jest.fn().mockRejectedValueOnce(error); await ProjectController.getProjectByAlias(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(500); expect(mockRes.json).toHaveBeenCalledWith({ message: error.message, }); }); }); describe('Backing up a project', () => { let getProjectByIdBackup; let backupProjectBackup; beforeEach(() => { getProjectByIdBackup = BotProjectService.getProjectById; backupProjectBackup = BotProjectService.backupProject; }); afterEach(() => { BotProjectService.getProjectById = getProjectByIdBackup; BotProjectService.backupProject = backupProjectBackup; }); it('should backup a project', async () => { BotProjectService.getProjectById = jest.fn().mockResolvedValueOnce({}); BotProjectService.backupProject = jest.fn().mockResolvedValueOnce('/backup/path'); const mockReq: any = { params: { projectId: 'projectId', }, }; await ProjectController.backupProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(200); expect(mockRes.json).toHaveBeenCalledWith({ path: '/backup/path' }); }); it('should return a 404 if it cannot find the specified project', async () => { BotProjectService.getProjectById = jest.fn().mockResolvedValueOnce(undefined); const mockReq: any = { params: { projectId: 'projectId', }, }; await ProjectController.backupProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(404); expect(mockRes.json).toHaveBeenCalledWith({ message: 'Could not find bot project with ID: projectId' }); }); it('should return a 500 if an error is thrown', async () => { const error = 'Something went wrong while backing up.'; BotProjectService.getProjectById = jest.fn().mockResolvedValueOnce({}); BotProjectService.backupProject = jest.fn().mockRejectedValueOnce(new Error(error)); const mockReq: any = { params: { projectId: 'projectId', }, }; await ProjectController.backupProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(500); expect(mockRes.json).toHaveBeenCalledWith(new Error(error)); }); }); describe('copying a template to an existing project', () => { let getProjectByIdBackup; let backupProjectBackup; let setProjectLocationDataBackup; let assetServiceManagerBackup; beforeEach(() => { getProjectByIdBackup = BotProjectService.getProjectById; backupProjectBackup = BotProjectService.backupProject; setProjectLocationDataBackup = BotProjectService.setProjectLocationData; assetServiceManagerBackup = { ...AssetService.manager }; }); afterEach(() => { BotProjectService.getProjectById = getProjectByIdBackup; BotProjectService.backupProject = backupProjectBackup; BotProjectService.setProjectLocationData = setProjectLocationDataBackup; AssetService.manager = assetServiceManagerBackup; }); it('should copy a template to an existing project', async () => { const mockReq: any = { body: { eTag: 'someEtag', templateDir: '/template/dir', }, params: { projectId: 'projectId', }, }; const mockBotProject = { fileStorage: { rmrfDir: jest.fn().mockResolvedValue(undefined), }, }; BotProjectService.getProjectById = jest.fn().mockResolvedValueOnce(mockBotProject); BotProjectService.setProjectLocationData = jest.fn().mockReturnValue(undefined); (AssetService.manager as any) = { copyRemoteProjectTemplateTo: jest.fn().mockResolvedValue(undefined), }; await ProjectController.copyTemplateToExistingProject(mockReq, mockRes); expect(mockRes.sendStatus).toHaveBeenCalledWith(200); }); it('should return a 400 if templateDir parameter is missing in request', async () => { const mockReq: any = { body: { eTag: 'someEtag', templateDir: undefined, }, params: { projectId: 'projectId', }, }; await ProjectController.copyTemplateToExistingProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(400); expect(mockRes.json).toHaveBeenCalledWith({ message: 'Missing parameters: templateDir required.' }); }); it('should return a 404 if no project is found with the specified id', async () => { const mockReq: any = { body: { eTag: 'someEtag', templateDir: '/template/dir', }, params: { projectId: 'nonExistentProjectId', }, }; BotProjectService.getProjectById = jest.fn().mockResolvedValueOnce(undefined); await ProjectController.copyTemplateToExistingProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(404); expect(mockRes.json).toHaveBeenCalledWith({ message: 'Could not find bot project with ID: nonExistentProjectId' }); }); it('should return a 500 an error is thrown', async () => { const mockReq: any = { body: { eTag: 'someEtag', templateDir: '/template/dir', }, params: { projectId: 'nonExistentProjectId', }, }; const error = new Error('Something went wrong while prepping for incoming template content.'); const mockBotProject = { fileStorage: { rmrfDir: jest.fn().mockRejectedValue(error), }, }; BotProjectService.getProjectById = jest.fn().mockResolvedValueOnce(mockBotProject); await ProjectController.copyTemplateToExistingProject(mockReq, mockRes); expect(mockRes.status).toHaveBeenCalledWith(500); expect(mockRes.json).toHaveBeenCalledWith(error); }); });
the_stack
import { errors, getSyntaxKindName, StringUtils, SyntaxKind, ts } from "@ts-morph/common"; import { CommentNodeKind, CompilerCommentClassElement, CompilerCommentEnumMember, CompilerCommentNode, CompilerCommentObjectLiteralElement, CompilerCommentStatement, CompilerCommentTypeElement } from "../comment/CompilerComments"; enum CommentKind { SingleLine, MultiLine, JsDoc, } export type StatementContainerNodes = | ts.SourceFile | ts.Block | ts.ModuleBlock | ts.CaseClause | ts.DefaultClause; export type ContainerNodes = | StatementContainerNodes | ts.ClassDeclaration | ts.InterfaceDeclaration | ts.EnumDeclaration | ts.ClassExpression | ts.TypeLiteralNode | ts.ObjectLiteralExpression; type CommentSyntaxKinds = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia; const childrenSaver = new WeakMap<ContainerNodes, (ts.Node | CompilerCommentNode)[]>(); const commentNodeParserKinds = new Set<SyntaxKind>([ SyntaxKind.SourceFile, SyntaxKind.Block, SyntaxKind.ModuleBlock, SyntaxKind.CaseClause, SyntaxKind.DefaultClause, SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration, SyntaxKind.EnumDeclaration, SyntaxKind.ClassExpression, SyntaxKind.TypeLiteral, SyntaxKind.ObjectLiteralExpression, ]); export class CommentNodeParser { private constructor() { } static getOrParseChildren(container: ContainerNodes | ts.SyntaxList, sourceFile: ts.SourceFile) { // always store the syntax list result on the parent so that a second array isn't created if (isSyntaxList(container)) container = container.parent as ContainerNodes; // cache the result let children = childrenSaver.get(container); if (children == null) { children = Array.from(getNodes(container, sourceFile)); childrenSaver.set(container, children); } return children; } static shouldParseChildren(container: ts.Node): container is ContainerNodes { // this needs to be really fast because it's used whenever getting the children, so use a map return commentNodeParserKinds.has(container.kind) // Ignore zero length nodes... for some reason this might happen when parsing // jsx in non-jsx files. && container.pos !== container.end; } static hasParsedChildren(container: ContainerNodes | ts.SyntaxList) { if (isSyntaxList(container)) container = container.parent as ContainerNodes; return childrenSaver.has(container); } static isCommentStatement(node: ts.Node): node is CompilerCommentStatement { return (node as CompilerCommentNode)._commentKind === CommentNodeKind.Statement; } static isCommentClassElement(node: ts.Node): node is CompilerCommentClassElement { return (node as CompilerCommentNode)._commentKind === CommentNodeKind.ClassElement; } static isCommentTypeElement(node: ts.Node): node is CompilerCommentTypeElement { return (node as CompilerCommentNode)._commentKind === CommentNodeKind.TypeElement; } static isCommentObjectLiteralElement(node: ts.Node): node is CompilerCommentObjectLiteralElement { return (node as CompilerCommentNode)._commentKind === CommentNodeKind.ObjectLiteralElement; } static isCommentEnumMember(node: ts.Node): node is CompilerCommentEnumMember { return (node as CompilerCommentNode)._commentKind === CommentNodeKind.EnumMember; } static getContainerBodyPos(container: ContainerNodes, sourceFile: ts.SourceFile) { if (ts.isSourceFile(container)) return 0; if (ts.isClassDeclaration(container) || ts.isEnumDeclaration(container) || ts.isInterfaceDeclaration(container) || ts.isTypeLiteralNode(container) || ts.isClassExpression(container) || ts.isBlock(container) || ts.isModuleBlock(container) || ts.isObjectLiteralExpression(container)) { // this function is only used when there are no statements or members, so only do this return getTokenEnd(container, SyntaxKind.OpenBraceToken); } if (ts.isCaseClause(container) || ts.isDefaultClause(container)) return getTokenEnd(container, SyntaxKind.ColonToken); return errors.throwNotImplementedForNeverValueError(container); function getTokenEnd(node: ts.Node, kind: SyntaxKind.OpenBraceToken | SyntaxKind.ColonToken) { // @code-fence-allow(getChildren): Ok, not searching for comments. return node.getChildren(sourceFile).find(c => c.kind === kind)?.end; } } } function* getNodes(container: ContainerNodes, sourceFile: ts.SourceFile): IterableIterator<ts.Node | CompilerCommentNode> { const sourceFileText = sourceFile.text; const childNodes = getContainerChildren(); const createComment = getCreationFunction(); if (childNodes.length === 0) { // it might not have a position if the code has syntax errors, so just ignore const bodyStartPos = CommentNodeParser.getContainerBodyPos(container, sourceFile); if (bodyStartPos != null) yield* getCommentNodes(bodyStartPos, false); // do not skip js docs because they won't have a node to be attached to } else { for (const childNode of childNodes) { yield* getCommentNodes(childNode.pos, true); yield childNode; } // get the comments on a newline after the last node const lastChild = childNodes[childNodes.length - 1]; yield* getCommentNodes(lastChild.end, false); // parse any jsdocs afterwards } function* getCommentNodes(pos: number, stopAtJsDoc: boolean) { const fullStart = pos; skipTrailingLine(); const leadingComments = Array.from(getLeadingComments()); // `pos` will be at the first significant token of the next node or at the source file length. // At this point, allow comments that end at the end of the source file or on the same line as the close brace token const maxEnd = sourceFileText.length === pos || sourceFileText[pos] === "}" ? pos : StringUtils.getLineStartFromPos(sourceFileText, pos); for (const leadingComment of leadingComments) { if (leadingComment.end <= maxEnd) yield leadingComment; } function skipTrailingLine() { // skip first line of the block as the comment there is likely to describe the header if (pos === 0) return; let lineEnd = StringUtils.getLineEndFromPos(sourceFileText, pos); while (pos < lineEnd) { const commentKind = getCommentKind(); if (commentKind != null) { const comment = parseForComment(commentKind); if (comment.kind === SyntaxKind.SingleLineCommentTrivia) return; else lineEnd = StringUtils.getLineEndFromPos(sourceFileText, pos); } // skip any trailing comments too else if (!StringUtils.isWhitespace(sourceFileText[pos]) && sourceFileText[pos] !== ",") return; else pos++; } while (StringUtils.startsWithNewLine(sourceFileText[pos])) pos++; } function* getLeadingComments() { while (pos < sourceFileText.length) { const commentKind = getCommentKind(); if (commentKind != null) { const isJsDoc = commentKind === CommentKind.JsDoc; if (isJsDoc && stopAtJsDoc) return; else yield parseForComment(commentKind); // treat comments on same line as trailing skipTrailingLine(); } else if (!StringUtils.isWhitespace(sourceFileText[pos])) return; else pos++; } } function parseForComment(commentKind: CommentKind) { if (commentKind === CommentKind.SingleLine) return parseSingleLineComment(); const isJsDoc = commentKind === CommentKind.JsDoc; return parseMultiLineComment(isJsDoc); } function getCommentKind() { const currentChar = sourceFileText[pos]; if (currentChar !== "/") return undefined; const nextChar = sourceFileText[pos + 1]; if (nextChar === "/") return CommentKind.SingleLine; if (nextChar !== "*") return undefined; const nextNextChar = sourceFileText[pos + 2]; return nextNextChar === "*" ? CommentKind.JsDoc : CommentKind.MultiLine; } function parseSingleLineComment() { const start = pos; skipSingleLineComment(); const end = pos; return createComment(fullStart, start, end, SyntaxKind.SingleLineCommentTrivia); } function skipSingleLineComment() { pos += 2; // skip the slash slash while (pos < sourceFileText.length && sourceFileText[pos] !== "\n" && sourceFileText[pos] !== "\r") pos++; } function parseMultiLineComment(isJsDoc: boolean) { const start = pos; skipSlashStarComment(isJsDoc); const end = pos; return createComment(fullStart, start, end, SyntaxKind.MultiLineCommentTrivia); } function skipSlashStarComment(isJsDoc: boolean) { pos += isJsDoc ? 3 : 2; // skip slash star star or slash star while (pos < sourceFileText.length) { if (sourceFileText[pos] === "*" && sourceFileText[pos + 1] === "/") { pos += 2; // skip star slash break; } pos++; } } } function getContainerChildren() { if (ts.isSourceFile(container) || ts.isBlock(container) || ts.isModuleBlock(container) || ts.isCaseClause(container) || ts.isDefaultClause(container)) return container.statements; if (ts.isClassDeclaration(container) || ts.isClassExpression(container) || ts.isEnumDeclaration(container) || ts.isInterfaceDeclaration(container) || ts.isTypeLiteralNode(container) || ts.isClassExpression(container)) { return container.members; } if (ts.isObjectLiteralExpression(container)) return container.properties; return errors.throwNotImplementedForNeverValueError(container); } function getCreationFunction(): (fullStart: number, pos: number, end: number, kind: CommentSyntaxKinds) => CompilerCommentNode { const ctor = getCtor(); return (fullStart: number, pos: number, end: number, kind: CommentSyntaxKinds) => new ctor(fullStart, pos, end, kind, sourceFile, container); function getCtor() { if (isStatementContainerNode(container)) return CompilerCommentStatement; if (ts.isClassLike(container)) return CompilerCommentClassElement; if (ts.isInterfaceDeclaration(container) || ts.isTypeLiteralNode(container)) return CompilerCommentTypeElement; if (ts.isObjectLiteralExpression(container)) return CompilerCommentObjectLiteralElement; if (ts.isEnumDeclaration(container)) return CompilerCommentEnumMember; throw new errors.NotImplementedError(`Not implemented comment node container type: ${getSyntaxKindName(container.kind)}`); } } } function isSyntaxList(node: ts.Node): node is ts.SyntaxList { return node.kind === SyntaxKind.SyntaxList; } function isStatementContainerNode(node: ts.Node) { return getStatementContainerNode() != null; function getStatementContainerNode(): StatementContainerNodes | undefined { // this is a bit of a hack so the type checker ensures this is correct const container = node as any as StatementContainerNodes; if (ts.isSourceFile(container) || ts.isBlock(container) || ts.isModuleBlock(container) || ts.isCaseClause(container) || ts.isDefaultClause(container)) { return container; } const assertNever: never = container; return undefined; } }
the_stack
import React, { FC, ReactElement, useState } from 'react'; import { Typography, Table, Tag, Modal, Input, Form, Switch, Button, AutoComplete } from 'antd'; import { ColumnsType } from 'antd/es/table'; import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, MenuOutlined } from '@ant-design/icons'; import axios from 'axios'; import useSWR from 'swr'; import { arrayMoveImmutable } from 'array-move'; import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; import countries from 'i18n-iso-countries'; import i18nZh from 'i18n-iso-countries/langs/zh.json'; import i18nEn from 'i18n-iso-countries/langs/en.json'; import { IResp, IServer } from '../types'; import { notify } from '../utils'; import Loading from '../components/Loading'; const { Title } = Typography; countries.registerLocale(i18nZh); countries.registerLocale(i18nEn); const Management: FC = () => { const [modifyVisible, setModifyVisible] = useState<boolean>(false); const [currentNode, setCurrentNode] = useState<string>(''); const [multiImport, setMultiImport] = useState<boolean>(false); const [sortOrder, setSortOrder] = useState(false); const [shouldPagination, setShouldPagination] = useState<false | undefined>(undefined); const [regionResult, setRegionResult] = useState<string[]>([]); const { data, mutate } = useSWR<IResp>('/api/server'); const [form] = Form.useForm(); const { confirm } = Modal; const dataSource = data?.data as IServer[]; const resetStatus = (fetch = true) => { fetch && mutate(); form.resetFields(); setCurrentNode(''); setMultiImport(false); setModifyVisible(false); }; const handleModify = () => { const data = form.getFieldsValue(); axios.put<IResp>('/api/server', { username: currentNode, data }).then(res => { notify('Success', res.data.msg, 'success'); resetStatus(); }); }; const handleCreate = () => { const data = form.getFieldsValue(); axios.post<IResp>('/api/server', { ...data }).then(res => { notify('Success', res.data.msg, 'success'); resetStatus(); }); }; const handleDelete = (username: string) => () => { axios.delete<IResp>(`/api/server/${username}`).then(res => { notify('Success', res.data.msg, 'success'); resetStatus(); }); }; const handleSortOrder = (order: number[]) => { axios.put<IResp>('/api/server/order', { order }).then(res => { notify('Success', res.data.msg, 'success'); resetStatus(); }); }; const columns: ColumnsType<IServer> = [ { title: 'Sort', dataIndex: 'sort', width: 30, align: 'center', render: () => undefined }, { title: 'SERVER', dataIndex: 'server', align: 'center', // eslint-disable-next-line react/display-name render(_, record) { return ( <div className="flex items-center text-sm"> <svg viewBox="0 0 100 100" className="mr-3 block h-12 w-12"> <use xlinkHref={`#${record.region}`} /> </svg> <div className="whitespace-nowrap"> <p className="font-semibold">{record.name}</p> <p className="text-left text-xs text-gray-600">{record.location}</p> </div> </div> ); } }, { title: 'USERNAME', dataIndex: 'username', align: 'center' }, { title: 'TYPE', dataIndex: 'type', align: 'center' }, { title: 'LOCATION', dataIndex: 'location', align: 'center' }, { title: 'REGION', dataIndex: 'region', align: 'center' }, { title: 'STATUS', dataIndex: 'disabled', align: 'center', // eslint-disable-next-line react/display-name render: disabled => ( disabled ? <Tag color="error">Disabled</Tag> : <Tag color="success">Enabled</Tag> ) }, { title: 'ACTION', dataIndex: 'action', align: 'center', // eslint-disable-next-line react/display-name render(_, record) { return ( <div className="flex justify-evenly items-center"> <EditOutlined onClick={() => { form.setFieldsValue(record); setCurrentNode(record.username); setModifyVisible(true); }} /> <DeleteOutlined onClick={() => confirm({ title: 'Are you sure you want to delete this item?', icon: <ExclamationCircleOutlined />, onOk: handleDelete(record.username) })} /> </div> ); } } ]; const DraggableContainer: FC = props => ( <Droppable droppableId="table"> { provided => ( <tbody {...props} {...provided.droppableProps} ref={provided.innerRef}> {props.children} {provided.placeholder} </tbody> ) } </Droppable> ); const DraggableBodyRow: FC<any> = props => { const index = dataSource.findIndex(x => x.id === props['data-row-key']); return ( <Draggable draggableId={props['data-row-key']?.toString() || 'k'} index={index} isDragDisabled={!sortOrder}> {provided => { const children = props.children?.map?.((el: ReactElement) => { if (el.props.dataIndex === 'sort') { const props = el.props ? { ...el.props } : {}; props.render = () => ( <MenuOutlined style={{ cursor: 'grab', color: '#999' }} {...provided.dragHandleProps} /> ); return React.cloneElement(el, props); } return el; }) || props.children; return ( <tr {...props} {...provided.draggableProps} ref={provided.innerRef}> {children} </tr> ); }} </Draggable> ); }; return ( <> <Title level={2} className="my-6">Management</Title> { data ? ( <DragDropContext onDragEnd={result => { const { destination, source } = result; if (!destination) return; if (destination.droppableId === source.droppableId && destination.index === source.index) return; const newDataSource = arrayMoveImmutable(dataSource, source.index, destination.index); mutate({ ...data, data: newDataSource }, false).then(); }} > <Table dataSource={dataSource} columns={columns} rowKey="id" components={{ body: { wrapper: DraggableContainer, row: DraggableBodyRow } }} pagination={shouldPagination} footer={() => ( <> <Button type="primary" className="mr-6" onClick={() => setModifyVisible(true)}>New</Button> <Button type="primary" className="mr-6" onClick={() => { setMultiImport(true); setModifyVisible(true); }} > Import </Button> <Button type="primary" danger={sortOrder} onClick={() => { if (sortOrder) { const order = dataSource.map(item => item.id); order.reverse(); handleSortOrder(order); } setSortOrder(val => !val); setShouldPagination(val => (val === undefined ? false : undefined)); }} > {!sortOrder ? 'Sort' : 'Save'} </Button> </> )} /> <Modal title={currentNode ? 'Modify Configuration' : 'New'} visible={modifyVisible} onOk={currentNode ? handleModify : handleCreate} onCancel={() => resetStatus(false)} > <Form layout="vertical" form={form}> {multiImport ? ( <Form.Item label="Data" name="data"> <Input.TextArea rows={4} /> </Form.Item> ) : ( <> <Form.Item label="Username" name="username"> <Input /> </Form.Item> <Form.Item label="Password" name="password"> <Input.Password placeholder="留空不修改" /> </Form.Item> <Form.Item label="Name" name="name"> <Input /> </Form.Item> <Form.Item label="Type" name="type"> <Input /> </Form.Item> <Form.Item label="Location" name="location"> <Input /> </Form.Item> <Form.Item label="Region" name="region" rules={[{ validator(_, value) { if (countries.isValid(value)) return Promise.resolve(); return Promise.reject(new Error('Country not found!')); } }]} > <AutoComplete options={regionResult.map(value => ({ value, label: value }))} onChange={value => { const code = countries.getAlpha2Code(value, 'zh'); const codeEn = countries.getAlpha2Code(value, 'en'); return setRegionResult([code, codeEn].filter(v => !!v)); }} > <Input /> </AutoComplete> </Form.Item> <Form.Item label="Disabled" name="disabled" valuePropName="checked"> <Switch /> </Form.Item> </> )} </Form> </Modal> </DragDropContext> ) : <Loading /> } </> ); }; export default Management;
the_stack
import React from 'react'; import {FormattedDate, FormattedMessage, FormattedTime} from 'react-intl'; import {Link} from 'react-router-dom'; import {UserProfile} from 'mattermost-redux/types/users'; import {ActionResult} from 'mattermost-redux/types/actions'; import {OAuthApp} from 'mattermost-redux/types/integrations'; import Constants from 'utils/constants'; import {t} from 'utils/i18n'; import * as Utils from 'utils/utils.jsx'; import icon50 from 'images/icon50x50.png'; import AccessHistoryModal from 'components/access_history_modal'; import ActivityLogModal from 'components/activity_log_modal'; import LocalizedIcon from 'components/localized_icon'; import SettingItemMax from 'components/setting_item_max.jsx'; import SettingItemMin from 'components/setting_item_min'; import ToggleModalButton from 'components/toggle_modal_button.jsx'; import MfaSection from './mfa_section'; import UserAccessTokenSection from './user_access_token_section'; const SECTION_MFA = 'mfa'; const SECTION_PASSWORD = 'password'; const SECTION_SIGNIN = 'signin'; const SECTION_APPS = 'apps'; const SECTION_TOKENS = 'tokens'; type Actions = { getMe: () => void; updateUserPassword: ( userId: string, currentPassword: string, newPassword: string ) => Promise<ActionResult>; getAuthorizedOAuthApps: () => Promise<ActionResult>; deauthorizeOAuthApp: (clientId: string) => Promise<ActionResult>; }; type Props = { user: UserProfile; activeSection?: string; updateSection: (section: string) => void; closeModal: () => void; collapseModal: () => void; setRequireConfirm: () => void; canUseAccessTokens: boolean; enableOAuthServiceProvider: boolean; enableSignUpWithEmail: boolean; enableSignUpWithGitLab: boolean; enableSignUpWithGoogle: boolean; enableSignUpWithOpenId: boolean; enableLdap: boolean; enableSaml: boolean; enableSignUpWithOffice365: boolean; experimentalEnableAuthenticationTransfer: boolean; passwordConfig: Utils.PasswordConfig; militaryTime: boolean; actions: Actions; }; type State = { currentPassword: string; newPassword: string; confirmPassword: string; passwordError: React.ReactNode; serverError: string | null; tokenError: string; savingPassword: boolean; authorizedApps: OAuthApp[]; }; export default class SecurityTab extends React.PureComponent<Props, State> { constructor(props: Props) { super(props); this.state = this.getDefaultState(); } getDefaultState() { return { currentPassword: '', newPassword: '', confirmPassword: '', passwordError: '', serverError: '', tokenError: '', authService: this.props.user.auth_service, savingPassword: false, authorizedApps: [], }; } componentDidMount() { if (this.props.enableOAuthServiceProvider) { this.loadAuthorizedOAuthApps(); } } loadAuthorizedOAuthApps = async () => { const res = await this.props.actions.getAuthorizedOAuthApps(); if ('data' in res) { const {data} = res; this.setState({authorizedApps: data, serverError: null}); //eslint-disable-line react/no-did-mount-set-state } else if ('error' in res) { const {error} = res; this.setState({serverError: error.message}); //eslint-disable-line react/no-did-mount-set-state } }; submitPassword = async () => { const user = this.props.user; const currentPassword = this.state.currentPassword; const newPassword = this.state.newPassword; const confirmPassword = this.state.confirmPassword; if (currentPassword === '') { this.setState({ passwordError: Utils.localizeMessage( 'user.settings.security.currentPasswordError', 'Please enter your current password.', ), serverError: '', }); return; } const {valid, error} = Utils.isValidPassword( newPassword, this.props.passwordConfig, ); if (!valid && error) { this.setState({ passwordError: error, serverError: '', }); return; } if (newPassword !== confirmPassword) { const defaultState = Object.assign(this.getDefaultState(), { passwordError: Utils.localizeMessage( 'user.settings.security.passwordMatchError', 'The new passwords you entered do not match.', ), serverError: '', }); this.setState(defaultState); return; } this.setState({savingPassword: true}); const res = await this.props.actions.updateUserPassword( user.id, currentPassword, newPassword, ); if ('data' in res) { this.props.updateSection(''); this.props.actions.getMe(); this.setState(this.getDefaultState()); } else if ('error' in res) { const {error: err} = res; const state = this.getDefaultState(); if (err.message) { state.serverError = err.message; } else { state.serverError = err; } state.passwordError = ''; this.setState(state); } }; updateCurrentPassword = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({currentPassword: e.target.value}); }; updateNewPassword = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({newPassword: e.target.value}); }; updateConfirmPassword = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({confirmPassword: e.target.value}); }; deauthorizeApp = async (e: React.MouseEvent) => { e.preventDefault(); const appId = e.currentTarget.getAttribute('data-app') as string; const res = await this.props.actions.deauthorizeOAuthApp(appId); if ('data' in res) { const authorizedApps = this.state.authorizedApps.filter((app) => { return app.id !== appId; }); this.setState({authorizedApps, serverError: null}); } else if ('error' in res) { const {error} = res; this.setState({serverError: error.message}); } }; handleUpdateSection = (section: string) => { if (section) { this.props.updateSection(section); } else { switch (this.props.activeSection) { case SECTION_MFA: case SECTION_SIGNIN: case SECTION_TOKENS: case SECTION_APPS: this.setState({ serverError: null, }); break; case SECTION_PASSWORD: this.setState({ currentPassword: '', newPassword: '', confirmPassword: '', serverError: null, passwordError: null, }); break; default: } this.props.updateSection(''); } }; createPasswordSection = () => { if (this.props.activeSection === SECTION_PASSWORD) { const inputs = []; let submit; if (this.props.user.auth_service === '') { submit = this.submitPassword; inputs.push( <div key='currentPasswordUpdateForm' className='form-group' > <label className='col-sm-5 control-label'> <FormattedMessage id='user.settings.security.currentPassword' defaultMessage='Current Password' /> </label> <div className='col-sm-7'> <input id='currentPassword' autoFocus={true} className='form-control' type='password' onChange={this.updateCurrentPassword} value={this.state.currentPassword} aria-label={Utils.localizeMessage( 'user.settings.security.currentPassword', 'Current Password', )} /> </div> </div>, ); inputs.push( <div key='newPasswordUpdateForm' className='form-group' > <label className='col-sm-5 control-label'> <FormattedMessage id='user.settings.security.newPassword' defaultMessage='New Password' /> </label> <div className='col-sm-7'> <input id='newPassword' className='form-control' type='password' onChange={this.updateNewPassword} value={this.state.newPassword} aria-label={Utils.localizeMessage( 'user.settings.security.newPassword', 'New Password', )} /> </div> </div>, ); inputs.push( <div key='retypeNewPasswordUpdateForm' className='form-group' > <label className='col-sm-5 control-label'> <FormattedMessage id='user.settings.security.retypePassword' defaultMessage='Retype New Password' /> </label> <div className='col-sm-7'> <input id='confirmPassword' className='form-control' type='password' onChange={this.updateConfirmPassword} value={this.state.confirmPassword} aria-label={Utils.localizeMessage( 'user.settings.security.retypePassword', 'Retype New Password', )} /> </div> </div>, ); } else if ( this.props.user.auth_service === Constants.GITLAB_SERVICE ) { inputs.push( <div key='oauthEmailInfo' className='form-group' > <div className='pb-3'> <FormattedMessage id='user.settings.security.passwordGitlabCantUpdate' defaultMessage='Login occurs through GitLab. Password cannot be updated.' /> </div> </div>, ); } else if ( this.props.user.auth_service === Constants.LDAP_SERVICE ) { inputs.push( <div key='oauthEmailInfo' className='form-group' > <div className='pb-3'> <FormattedMessage id='user.settings.security.passwordLdapCantUpdate' defaultMessage='Login occurs through AD/LDAP. Password cannot be updated.' /> </div> </div>, ); } else if ( this.props.user.auth_service === Constants.SAML_SERVICE ) { inputs.push( <div key='oauthEmailInfo' className='form-group' > <div className='pb-3'> <FormattedMessage id='user.settings.security.passwordSamlCantUpdate' defaultMessage='This field is handled through your login provider. If you want to change it, you need to do so through your login provider.' /> </div> </div>, ); } else if ( this.props.user.auth_service === Constants.GOOGLE_SERVICE ) { inputs.push( <div key='oauthEmailInfo' className='form-group' > <div className='pb-3'> <FormattedMessage id='user.settings.security.passwordGoogleCantUpdate' defaultMessage='Login occurs through Google Apps. Password cannot be updated.' /> </div> </div>, ); } else if ( this.props.user.auth_service === Constants.OFFICE365_SERVICE ) { inputs.push( <div key='oauthEmailInfo' className='form-group' > <div className='pb-3'> <FormattedMessage id='user.settings.security.passwordOffice365CantUpdate' defaultMessage='Login occurs through Office 365. Password cannot be updated.' /> </div> </div>, ); } return ( <SettingItemMax title={ <FormattedMessage id='user.settings.security.password' defaultMessage='Password' /> } inputs={inputs} submit={submit} saving={this.state.savingPassword} serverError={this.state.serverError} clientError={this.state.passwordError} updateSection={this.handleUpdateSection} /> ); } let describe; if (this.props.user.auth_service === '') { const d = new Date(this.props.user.last_password_update); describe = ( <FormattedMessage id='user.settings.security.lastUpdated' defaultMessage='Last updated {date} at {time}' values={{ date: ( <FormattedDate value={d} day='2-digit' month='short' year='numeric' /> ), time: ( <FormattedTime value={d} hour12={!this.props.militaryTime} hour='2-digit' minute='2-digit' /> ), }} /> ); } else if (this.props.user.auth_service === Constants.GITLAB_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.loginGitlab' defaultMessage='Login done through GitLab' /> ); } else if (this.props.user.auth_service === Constants.LDAP_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.loginLdap' defaultMessage='Login done through AD/LDAP' /> ); } else if (this.props.user.auth_service === Constants.SAML_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.loginSaml' defaultMessage='Login done through SAML' /> ); } else if (this.props.user.auth_service === Constants.GOOGLE_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.loginGoogle' defaultMessage='Login done through Google Apps' /> ); } else if ( this.props.user.auth_service === Constants.OFFICE365_SERVICE ) { describe = ( <FormattedMessage id='user.settings.security.loginOffice365' defaultMessage='Login done through Office 365' /> ); } return ( <SettingItemMin title={ <FormattedMessage id='user.settings.security.password' defaultMessage='Password' /> } describe={describe} section={SECTION_PASSWORD} updateSection={this.handleUpdateSection} /> ); }; createSignInSection = () => { const user = this.props.user; if (this.props.activeSection === SECTION_SIGNIN) { let emailOption; let gitlabOption; let googleOption; let office365Option; let openidOption; let ldapOption; let samlOption; if (user.auth_service === '') { if (this.props.enableSignUpWithGitLab) { gitlabOption = ( <div className='pb-3'> <Link className='btn btn-primary' to={ '/claim/email_to_oauth?email=' + encodeURIComponent(user.email) + '&old_type=' + user.auth_service + '&new_type=' + Constants.GITLAB_SERVICE } > <FormattedMessage id='user.settings.security.switchGitlab' defaultMessage='Switch to Using GitLab SSO' /> </Link> <br/> </div> ); } if (this.props.enableSignUpWithGoogle) { googleOption = ( <div className='pb-3'> <Link className='btn btn-primary' to={ '/claim/email_to_oauth?email=' + encodeURIComponent(user.email) + '&old_type=' + user.auth_service + '&new_type=' + Constants.GOOGLE_SERVICE } > <FormattedMessage id='user.settings.security.switchGoogle' defaultMessage='Switch to Using Google SSO' /> </Link> <br/> </div> ); } if (this.props.enableSignUpWithOffice365) { office365Option = ( <div className='pb-3'> <Link className='btn btn-primary' to={ '/claim/email_to_oauth?email=' + encodeURIComponent(user.email) + '&old_type=' + user.auth_service + '&new_type=' + Constants.OFFICE365_SERVICE } > <FormattedMessage id='user.settings.security.switchOffice365' defaultMessage='Switch to Using Office 365 SSO' /> </Link> <br/> </div> ); } if (this.props.enableSignUpWithOpenId) { openidOption = ( <div className='pb-3'> <Link className='btn btn-primary' to={ '/claim/email_to_oauth?email=' + encodeURIComponent(user.email) + '&old_type=' + user.auth_service + '&new_type=' + Constants.OPENID_SERVICE } > <FormattedMessage id='user.settings.security.switchOpenId' defaultMessage='Switch to Using OpenID SSO' /> </Link> <br/> </div> ); } if (this.props.enableLdap) { ldapOption = ( <div className='pb-3'> <Link className='btn btn-primary' to={ '/claim/email_to_ldap?email=' + encodeURIComponent(user.email) } > <FormattedMessage id='user.settings.security.switchLdap' defaultMessage='Switch to Using AD/LDAP' /> </Link> <br/> </div> ); } if (this.props.enableSaml) { samlOption = ( <div className='pb-3'> <Link className='btn btn-primary' to={ '/claim/email_to_oauth?email=' + encodeURIComponent(user.email) + '&old_type=' + user.auth_service + '&new_type=' + Constants.SAML_SERVICE } > <FormattedMessage id='user.settings.security.switchSaml' defaultMessage='Switch to Using SAML SSO' /> </Link> <br/> </div> ); } } else if (this.props.enableSignUpWithEmail) { let link; if (user.auth_service === Constants.LDAP_SERVICE) { link = '/claim/ldap_to_email?email=' + encodeURIComponent(user.email); } else { link = '/claim/oauth_to_email?email=' + encodeURIComponent(user.email) + '&old_type=' + user.auth_service; } emailOption = ( <div className='pb-3'> <Link className='btn btn-primary' to={link} > <FormattedMessage id='user.settings.security.switchEmail' defaultMessage='Switch to Using Email and Password' /> </Link> <br/> </div> ); } const inputs = []; inputs.push( <div key='userSignInOption'> {emailOption} {gitlabOption} {googleOption} {office365Option} {openidOption} {ldapOption} {samlOption} </div>, ); const extraInfo = ( <span> <FormattedMessage id='user.settings.security.oneSignin' defaultMessage='You may only have one sign-in method at a time. Switching sign-in method will send an email notifying you if the change was successful.' /> </span> ); return ( <SettingItemMax title={Utils.localizeMessage( 'user.settings.security.method', 'Sign-in Method', )} extraInfo={extraInfo} inputs={inputs} serverError={this.state.serverError} updateSection={this.handleUpdateSection} /> ); } let describe = ( <FormattedMessage id='user.settings.security.emailPwd' defaultMessage='Email and Password' /> ); if (this.props.user.auth_service === Constants.GITLAB_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.gitlab' defaultMessage='GitLab' /> ); } else if (this.props.user.auth_service === Constants.GOOGLE_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.google' defaultMessage='Google' /> ); } else if ( this.props.user.auth_service === Constants.OFFICE365_SERVICE ) { describe = ( <FormattedMessage id='user.settings.security.office365' defaultMessage='Office 365' /> ); } else if ( this.props.user.auth_service === Constants.OPENID_SERVICE ) { describe = ( <FormattedMessage id='user.settings.security.openid' defaultMessage='OpenID' /> ); } else if (this.props.user.auth_service === Constants.LDAP_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.ldap' defaultMessage='AD/LDAP' /> ); } else if (this.props.user.auth_service === Constants.SAML_SERVICE) { describe = ( <FormattedMessage id='user.settings.security.saml' defaultMessage='SAML' /> ); } return ( <SettingItemMin title={Utils.localizeMessage( 'user.settings.security.method', 'Sign-in Method', )} describe={describe} section={SECTION_SIGNIN} updateSection={this.handleUpdateSection} /> ); }; createOAuthAppsSection = () => { if (this.props.activeSection === SECTION_APPS) { let apps; if ( this.state.authorizedApps && this.state.authorizedApps.length > 0 ) { apps = this.state.authorizedApps.map((app) => { const homepage = ( <a href={app.homepage} target='_blank' rel='noopener noreferrer' > {app.homepage} </a> ); return ( <div key={app.id} className='pb-3 authorized-app' > <div className='col-sm-10'> <div className='authorized-app__name'> {app.name} <span className='authorized-app__url'> {' -'} {homepage} </span> </div> <div className='authorized-app__description'> {app.description} </div> <div className='authorized-app__deauthorize'> <a href='#' data-app={app.id} onClick={this.deauthorizeApp} > <FormattedMessage id='user.settings.security.deauthorize' defaultMessage='Deauthorize' /> </a> </div> </div> <div className='col-sm-2 pull-right'> <img alt={app.name} src={app.icon_url || icon50} /> </div> <br/> </div> ); }); } else { apps = ( <div className='pb-3 authorized-app'> <div className='setting-list__hint'> <FormattedMessage id='user.settings.security.noApps' defaultMessage='No OAuth 2.0 Applications are authorized.' /> </div> </div> ); } const inputs = []; let wrapperClass; let helpText; if (Array.isArray(apps)) { wrapperClass = 'authorized-apps__wrapper'; helpText = ( <div className='authorized-apps__help'> <FormattedMessage id='user.settings.security.oauthAppsHelp' defaultMessage='Applications act on your behalf to access your data based on the permissions you grant them.' /> </div> ); } inputs.push( <div className={wrapperClass} key='authorizedApps' > {apps} </div>, ); const title = ( <div> <FormattedMessage id='user.settings.security.oauthApps' defaultMessage='OAuth 2.0 Applications' /> {helpText} </div> ); return ( <SettingItemMax title={title} inputs={inputs} serverError={this.state.serverError} updateSection={this.handleUpdateSection} width='full' cancelButtonText={ <FormattedMessage id='user.settings.security.close' defaultMessage='Close' /> } /> ); } return ( <SettingItemMin title={Utils.localizeMessage( 'user.settings.security.oauthApps', 'OAuth 2.0 Applications', )} describe={ <FormattedMessage id='user.settings.security.oauthAppsDescription' defaultMessage="Click 'Edit' to manage your OAuth 2.0 Applications" /> } section={SECTION_APPS} updateSection={this.handleUpdateSection} /> ); }; render() { const user = this.props.user; const passwordSection = this.createPasswordSection(); let numMethods = 0; numMethods = this.props.enableSignUpWithGitLab ? numMethods + 1 : numMethods; numMethods = this.props.enableSignUpWithGoogle ? numMethods + 1 : numMethods; numMethods = this.props.enableSignUpWithOffice365 ? numMethods + 1 : numMethods; numMethods = this.props.enableSignUpWithOpenId ? numMethods + 1 : numMethods; numMethods = this.props.enableLdap ? numMethods + 1 : numMethods; numMethods = this.props.enableSaml ? numMethods + 1 : numMethods; // If there are other sign-in methods and either email is enabled or the user's account is email, then allow switching let signInSection; if ( (this.props.enableSignUpWithEmail || user.auth_service === '') && numMethods > 0 && this.props.experimentalEnableAuthenticationTransfer ) { signInSection = this.createSignInSection(); } let oauthSection; if (this.props.enableOAuthServiceProvider) { oauthSection = this.createOAuthAppsSection(); } let tokensSection; if (this.props.canUseAccessTokens) { tokensSection = ( <UserAccessTokenSection user={this.props.user} active={this.props.activeSection === SECTION_TOKENS} updateSection={this.handleUpdateSection} setRequireConfirm={this.props.setRequireConfirm} /> ); } return ( <div> <div className='modal-header'> <button type='button' className='close' data-dismiss='modal' aria-label={Utils.localizeMessage('user.settings.security.close', 'Close')} onClick={this.props.closeModal} > <span aria-hidden='true'>{'×'}</span> </button> <h4 className='modal-title' ref='title' > <div className='modal-back'> <LocalizedIcon className='fa fa-angle-left' title={{id: t('generic_icons.collapse'), defaultMessage: 'Collapse Icon'}} onClick={this.props.collapseModal} /> </div> <FormattedMessage id='user.settings.security.title' defaultMessage='Security Settings' /> </h4> </div> <div className='user-settings'> <h3 className='tab-header'> <FormattedMessage id='user.settings.security.title' defaultMessage='Security Settings' /> </h3> <div className='divider-dark first'/> {passwordSection} <div className='divider-light'/> <MfaSection active={this.props.activeSection === SECTION_MFA} updateSection={this.handleUpdateSection} /> <div className='divider-light'/> {oauthSection} <div className='divider-light'/> {tokensSection} <div className='divider-light'/> {signInSection} <div className='divider-dark'/> <br/> <ToggleModalButton className='security-links color--link' dialogType={AccessHistoryModal} id='viewAccessHistory' > <LocalizedIcon className='fa fa-clock-o' title={{id: t('user.settings.security.viewHistory.icon'), defaultMessage: 'Access History Icon'}} /> <FormattedMessage id='user.settings.security.viewHistory' defaultMessage='View Access History' /> </ToggleModalButton> <ToggleModalButton className='security-links color--link mt-2' dialogType={ActivityLogModal} id='viewAndLogOutOfActiveSessions' > <LocalizedIcon className='fa fa-clock-o' title={{id: t('user.settings.security.logoutActiveSessions.icon'), defaultMessage: 'Active Sessions Icon'}} /> <FormattedMessage id='user.settings.security.logoutActiveSessions' defaultMessage='View and Log Out of Active Sessions' /> </ToggleModalButton> </div> </div> ); } } /* eslint-enable react/no-string-refs */
the_stack
import * as crypto from "crypto"; import * as fs from "fs"; import * as os from "os"; import { URL } from "url"; import { TimeStampedDataPoint } from ".."; import { IMindConnectConfiguration } from "./mindconnect-models"; const groupby = require("json-groupby"); export const convertToTdpArray = (data: any[]): TimeStampedDataPoint[] => { const tdpArray: TimeStampedDataPoint[] = []; const groupedData = groupby(data, ["timestamp"]); for (const element in groupedData) { groupedData[element].forEach((x: any) => { delete x["timestamp"]; }); const tdp: TimeStampedDataPoint = { timestamp: element, values: groupedData[element], }; tdpArray.push(tdp); } return tdpArray; }; export type authJson = { auth: string; iv: string; gateway: string; tenant: string; usertenant: string; appName: string; appVersion: string; selected: boolean; type: "SERVICE" | "APP"; createdAt: string; }; export function upgradeOldConfiguration(obj: any) { if (obj.auth && obj.iv && obj.gateway && obj.tenant) { return { credentials: [ { ...obj, selected: true, type: "SERVICE", createdAt: new Date().toISOString(), appName: "", appVersion: "", usertenant: "", }, ], }; } return obj; } export const isUrl = (url: string): boolean => { try { new URL(url); return true; } catch (e) { return false; } }; export const getPiamUrl = (gateway: string, tenant: string): string => { const piamUrl = gateway.replace("gateway", `${tenant}.piam`); return piamUrl.endsWith("/") ? piamUrl : piamUrl + "/"; }; const normalizePasskey = (passkey: string): string => { return passkey.length < 32 ? passkey + new Array(33 - passkey.length).join("$") : passkey.substr(0, 32); }; export const encrypt = ({ user, password, passkey, gateway, tenant, type, usertenant, appName, appVersion, createdAt, selected, }: credentialEntry): authJson => { const base64encoded = Buffer.from(`${user}:${password}`).toString("base64"); const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv("aes-256-ctr", Buffer.from(normalizePasskey(passkey)), iv); let crypted = cipher.update(`Basic ${base64encoded}`, "utf8", "hex"); crypted += cipher.final("hex"); const encryptedAuth = { auth: crypted.toString(), iv: iv.toString("base64"), gateway: gateway, tenant: tenant, type: type, usertenant: usertenant, appName: appName, appVersion: appVersion, createdAt: createdAt, selected: selected, }; // console.log(encryptedAuth); return encryptedAuth; }; export type credentialEntry = { user: string; password: string; passkey: string; gateway: string; tenant: string; type: "SERVICE" | "APP"; usertenant: string; appName: string; appVersion: string; createdAt: string; selected: boolean; }; export const decrypt = (encryptedAuth: authJson, passkey: string): string => { const decipher = crypto.createDecipheriv( "aes-256-ctr", normalizePasskey(passkey), Buffer.from(encryptedAuth.iv, "base64") ); let dec = decipher.update(encryptedAuth.auth, "hex", "utf8"); dec += decipher.final("utf8"); return dec; }; export const getAgentDir = (path?: string) => { let result; if (fs.existsSync(`${path}/.mc/`)) { result = `${path}/.mc/`; } else if (fs.existsSync(`${process.cwd()}/.mc/`)) { result = `${process.cwd()}/.mc/`; } else { result = getHomeDotMcDir(); } return result; }; export const getHomeDotMcDir = () => { return `${os.homedir()}/.mc/`; }; export const storeAuth = (auth: { credentials: authJson[] }) => { const homeDir = getHomeDotMcDir(); if (!fs.existsSync(homeDir)) { fs.mkdirSync(homeDir); } const pathName = `${getHomeDotMcDir()}auth.json`; fs.writeFileSync(pathName, JSON.stringify(auth)); }; export const loadAuth = (): authJson => { const fullConfig = getFullConfig(); let result: authJson | undefined = undefined; for (let index = 0; index < fullConfig.credentials.length; index++) { const element = fullConfig.credentials[index]; if (element.selected) { result = element; break; } } !result && throwError( "please configure the authentication: https://opensource.mindsphere.io/docs/mindconnect-nodejs/cli/setting-up-the-cli.html " ); return result!; }; export function getFullConfig(): { credentials: authJson[] } { const homeDir = getHomeDotMcDir(); if (!fs.existsSync(homeDir)) { fs.mkdirSync(homeDir); console.log(`creating ${homeDir} folder`); } // create empty auth.json const pathName = `${getHomeDotMcDir()}auth.json`; if (!fs.existsSync(pathName)) { fs.writeFileSync(pathName, JSON.stringify({ credentials: [] })); console.log(`initializing ${pathName} with empty configuration`); } const buffer = fs.readFileSync(pathName); let obj = JSON.parse(buffer.toString()); // console.log(obj); if (obj.auth && obj.iv && obj.gateway && obj.tenant) { const upgraded = upgradeOldConfiguration(obj); fs.writeFileSync(pathName, JSON.stringify(upgraded)); obj = upgraded; console.log("upgraded configuration to the new format"); } return obj; } export const getConfigProfile = (config: IMindConnectConfiguration): string => { try { const result = `${config.content.clientCredentialProfile}`; if (["SHARED_SECRET", "RSA_3072"].indexOf(result) < 0) { throw new Error( "Configuration profile not supported. The library only supports the shared_secret and RSA_3072 config profiles" ); } return result; } catch (err) { throw new Error( "Configuration profile not supported. The library only supports the shared_secret and RSA_3072 config profiles" ); } }; export const checkCertificate = (config: IMindConnectConfiguration, options: any): boolean => { const profile = getConfigProfile(config); if (profile === "RSA_3072") { if (!options.cert) { throw new Error("You have to specify --cert parameter for RSA_3072 agents"); } if (!fs.existsSync(options.cert)) { throw new Error(`Can't find file ${options.cert}`); } } return profile === "RSA_3072"; }; const sleep = (ms: any) => new Promise((resolve) => setTimeout(resolve, ms)); /** * retry the function n times (while progressively waiting for the success) until success * the waiting schema is iteration * timeoutInMiliseconds (default is 300ms) * * @param {number} n * @param {Function} func * @param {number} [timoutinMilliseconds=300] * @param {Function} [logFunction] * @returns */ export const retry = async (n: number, func: Function, timoutinMilliseconds: number = 300, logFunction?: Function) => { let error; for (let i = 0; i < n; i++) { try { if (logFunction) { logFunction(); } if (i > 0) { await sleep(i * timoutinMilliseconds); } return await func(); } catch (err) { error = err; } } throw error; }; export const checkAssetId = (agentId: string) => { if (!/[a-f0-9]{32}/gi.test(agentId)) { throw new Error("You have to pass valid 32 char long asset id"); } }; export const throwError = (error: string) => { throw new Error(error); }; export const toQueryString = (qs: any) => { return Object.keys(qs || {}) .filter((key) => { return qs[key] !== undefined; }) .map((key) => { const value = qs[key] instanceof Date ? qs[key].toISOString() : qs[key]; return encodeURIComponent(key) + "=" + encodeURIComponent(value); }) .join("&"); }; export const removeUndefined = (obj: any) => { Object.keys(obj).forEach((key) => obj[key] === undefined && delete obj[key]); return obj; }; export async function checksumFile(hashName: string, path: string): Promise<string> { return new Promise((resolve, reject) => { const hash = crypto.createHash(hashName); const stream = fs.createReadStream(path); stream.on("error", (err) => reject(err)); stream.on("data", (chunk) => hash.update(chunk)); stream.on("end", () => resolve(hash.digest("hex"))); }); } export function pruneCert(s: string): string { return s .split(/\r\n|\r|\n/) .filter((x) => { return x.indexOf("CERTIFICATE") < 0; }) .join(""); } export function addAndStoreConfiguration(configuration: any) { const newConfiguration: { credentials: authJson[]; } = { credentials: [], }; (!configuration || !configuration.credentials) && throwError("invalid configuration!"); configuration.credentials.forEach((element: credentialEntry) => { element.gateway = isUrl(element.gateway) ? element.gateway : `https://gateway.${element.gateway}.mindsphere.io`; newConfiguration.credentials.push(element.passkey ? encrypt(element) : ((element as unknown) as authJson)); }); checkList(newConfiguration.credentials); storeAuth(newConfiguration); } export function checkList(list: any[]) { let count = 0; for (let i = 0; i < list.length; i++) { const element = list[i]; element.selected && count++; } if (count !== 1) { for (let i = 0; i < list.length; i++) { const element = list[i]; element.selected = i === 0; } } } /** * Iterates over all properties of an object and returns it serialized as data points * * @export * @param {{ [x: string]: any }} obj Object to iterate over * @param {string} aspect aspect name in mindsphere * @param {((propertyName: string, aspect: string) => string | undefined)} dataPointFunction find id in the object * @param {((propertyName: string, aspect: string) => string | undefined)} qualityCodeFunction find quality code in the object * @param {(propertyName: string, aspect: string) => void} invalidDataFunction what to do if the data is not available * @returns */ export function convertToDataPoints( obj: { [x: string]: any }, aspect: string, dataPointFunction: (propertyName: string, aspect: string) => string | undefined, qualityCodeFunction: (propertyName: string, aspect: string) => string | undefined, invalidDataFunction: (propertyName: string, aspect: string) => void ): { dataPointId: string; qualityCode: string; value: string }[] { const res: { dataPointId: string; qualityCode: string; value: string }[] = []; function recurse(obj: { [x: string]: any }) { for (const propertyName in obj) { const value = obj[propertyName]; if (value) { if (Array.isArray(value)) { const dataPointId = dataPointFunction(propertyName, aspect); const qualityCode = qualityCodeFunction(propertyName, aspect); if (!dataPointId || !qualityCode) { invalidDataFunction(propertyName, aspect); } res.push({ dataPointId: `${dataPointId}`, qualityCode: `${qualityCode}`, value: `${JSON.stringify(value)}`, }); } else if (value && typeof value === "object") { recurse(value); } else { const dataPointId = dataPointFunction(propertyName, aspect); const qualityCode = qualityCodeFunction(propertyName, aspect); if (!dataPointId || !qualityCode) { invalidDataFunction(propertyName, aspect); } res.push({ dataPointId: `${dataPointId}`, qualityCode: `${qualityCode}`, value: `${value}`, }); } } } } recurse(obj); return res; } export function isGuid(x: string): boolean { const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; return guidRegex.test(x); }
the_stack
import {KIND_TEXT} from '@remote-ui/core'; import type { RemoteRoot, RemoteComponent, RemoteText, RemoteChild, } from '@remote-ui/core'; import {Fragment} from '../Fragment'; import {createVNode} from '../create-element'; import {EMPTY_ARRAY} from '../constants'; import {removeNode} from '../utilities'; import options from '../options'; import type { VNode, Ref, Options, RefObject, RemoteChildNode, RemoteParentNode, RemoteComponentNode, ComponentInternal, ComponentClass, FunctionComponent, ContextInternal, ComponentChildren, RemoteRootNode, Component as ComponentInstance, RenderableProps, } from '../types'; import {diffProps} from './props'; // In Preact, this is in a separate, top level ./Components.js file. This causes // issues because `Component` needs to depend on `diff()`, and `diff()` needs to // depend on `Component`. For simplicity, I just plunked all the contents in the // same file. export class Component<P = {}, S = {}> implements ComponentInstance<P, S> { readonly state!: S; constructor(public props: P, public context: any) {} setState<K extends keyof S>( update: | (( prevState: Readonly<S>, props: Readonly<P>, ) => Pick<S, K> | Partial<S> | null) | (Pick<S, K> | Partial<S> | null), callback?: () => void, ) { const internalThis = this as any as ComponentInternal<P, S>; // only clone state when copying to nextState the first time. let state: S | undefined; const {state: currentState, _nextState: nextState} = internalThis; if (nextState != null && nextState !== currentState) { state = nextState; } else { state = {...currentState}; internalThis._nextState = state; } const resolvedUpdate = typeof update === 'function' ? update({...state}, internalThis.props) : update; if (resolvedUpdate) { Object.assign(state, resolvedUpdate); } // Skip update if updater function returned null if (resolvedUpdate == null) return; if (internalThis._vnode) { if (callback) internalThis._renderCallbacks.push(callback); enqueueRender(internalThis); } } forceUpdate(callback?: () => void) { const internalThis = this as any as ComponentInternal<P, S>; if (internalThis._vnode) { // Set render mode so that we can differentiate where the render request // is coming from. We need this because forceUpdate should never call // shouldComponentUpdate internalThis._force = true; if (callback) internalThis._renderCallbacks.push(callback); enqueueRender(internalThis); } } render({children}: RenderableProps<P>) { return children; } } /** * Trigger in-place re-rendering of a component. */ function renderComponent(component: ComponentInternal<any, any>) { const vnode = component._vnode!; const oldRemoteNode = vnode!._remoteNode; const parentRemoteNode = component._parentRemoteNode; if (parentRemoteNode) { const commitQueue: ComponentInternal<any, any>[] = []; const oldVNode = {...vnode}; oldVNode._original = oldVNode; const newRemoteNode = diff( parentRemoteNode, component._remoteRoot, vnode, oldVNode, component._globalContext, [], commitQueue, oldRemoteNode == null ? getRemoteSibling(vnode) : oldRemoteNode, ); commitRoot(commitQueue, vnode); if (newRemoteNode !== oldRemoteNode) { updateRemoteNodePointers(vnode); } } } function updateRemoteNodePointers(vnode: VNode<any>) { const parentVNode = vnode._parent; const parentComponent = parentVNode?._component; if (parentVNode != null && parentComponent != null) { parentVNode._remoteNode = null; parentComponent.base = undefined; for (const child of parentVNode._children!) { if (child?._remoteNode != null) { const newRemoteNode = child._remoteNode; parentVNode._remoteNode = newRemoteNode; parentComponent.base = newRemoteNode; break; } } updateRemoteNodePointers(parentVNode); } } /** * The render queue * @type {Array<import('./internal').Component>} */ let rerenderQueue: ComponentInternal<any, any>[] = []; const defer = typeof Promise === 'function' ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout; /* * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is * important that contributors to Preact can consistently reason about what calls to `setState`, etc. * do, and when their effects will be applied. See the links below for some further reading on designing * asynchronous APIs. * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony) * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/) */ let prevDebounce: Options['debounceRendering'] | undefined; export function enqueueRender(component: ComponentInternal<any, any>) { let shouldProcess = false; if (component._dirty) { shouldProcess = prevDebounce !== options.debounceRendering; } else { component._dirty = true; rerenderQueue.push(component); // We only want to process if we aren’t already in the middle of consuming // the current render queue shouldProcess = process._rerenderCount === 0; process._rerenderCount += 1; } if (shouldProcess) { prevDebounce = options.debounceRendering; (prevDebounce ?? defer)(process); } } /** Flush the render queue by rerendering all queued components */ function process() { let queue: ComponentInternal<any, any>[]; while ((process._rerenderCount = rerenderQueue.length)) { queue = rerenderQueue.sort( (componentA, componentB) => // We know _vnode is defined here because only components that have // actually rendered can be rerendered. componentA._vnode!._depth - componentB._vnode!._depth, ); rerenderQueue = []; // Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary // process() calls from getting scheduled while `queue` is still being consumed. queue.forEach((component) => { if (component._dirty) renderComponent(component); }); } } process._rerenderCount = 0; function getRemoteSibling( vnode: VNode<any>, childIndex?: number, ): RemoteChildNode | null { if (childIndex == null) { // Use childIndex==null as a signal to resume the search from the vnode's sibling return vnode._parent ? getRemoteSibling( vnode._parent!, vnode._parent!._children!.indexOf(vnode) + 1, ) : null; } for (const sibling of vnode._children!) { if (sibling?._remoteNode != null) { // Since updateParentDomPointers keeps _dom pointer correct, // we can rely on _dom to tell us if this subtree contains a // rendered DOM node, and what the first rendered DOM node is return sibling._remoteNode; } } // If we get here, we have not found a DOM node in this vnode's children. // We must resume from this vnode's sibling (in it's parent _children array) // Only climb up and search the parent if we aren't searching through a DOM // VNode (meaning we reached the DOM parent of the original vnode that began // the search) return typeof vnode.type === 'function' ? getRemoteSibling(vnode) : null; } /** * Diff two virtual nodes and apply proper changes to a remote node */ export function diff( parentNode: RemoteParentNode, remoteRoot: RemoteRoot<any, any>, newVNode: VNode<any>, oldVNode: VNode<any> | undefined, globalContext: any, excessRemoteChildren: (RemoteChildNode | null | undefined)[] | null, commitQueue: ComponentInternal<any, any>[], oldRemoteNode?: RemoteChildNode | null, ) { const newType = newVNode.type; // When passing through createElement it assigns the object // constructor as undefined. This to prevent JSON-injection. if (newVNode.constructor !== undefined) return null; options._diff?.(newVNode); try { // eslint-disable-next-line no-labels outer: if (typeof newType === 'function') { let isNew = false; let clearProcessingException: ComponentInternal< any, any >['_pendingError']; let component: ComponentInternal<any, any>; const oldComponent = oldVNode?._component; const newProps = newVNode.props; // Necessary for createContext api. Setting this property will pass // the context value as `this.context` just for this component. const contextType = (newType as ComponentClass<any>) .contextType as ContextInternal<any>; const provider = contextType && globalContext[contextType._id]; // eslint-disable-next-line no-nested-ternary const componentContext = contextType ? provider ? provider.props.value : contextType._defaultValue : globalContext; if (oldComponent) { component = oldComponent; newVNode._component = component; clearProcessingException = component._pendingError; component._processingException = component._pendingError; } else { // Instantiate the new component if ('prototype' in newType && newType.prototype.render) { component = new (newType as any)(newProps, componentContext); } else { component = new Component(newProps, componentContext) as any; component.constructor = newType; component.render = doRender; } newVNode._component = component; if (provider) provider.sub(component); component.props = newProps; if (!component.state) component.state = {}; component.context = componentContext; component._globalContext = globalContext; component._remoteRoot = remoteRoot; component._dirty = true; component._renderCallbacks = []; isNew = true; } // Invoke getDerivedStateFromProps if (component._nextState == null) { component._nextState = component.state; } if ((newType as ComponentClass<any>).getDerivedStateFromProps != null) { // Clone state to _nextState because we are about to assign new // state values to _nextState and we don’t want it to be visible // on state if (component._nextState === component.state) { component._nextState = {...component._nextState}; } Object.assign( component._nextState, (newType as ComponentClass<any>).getDerivedStateFromProps!( newProps, component._nextState, ), ); } let snapshot: any; const {props: oldProps, state: oldState} = component; // Invoke pre-render lifecycle methods if (isNew) { if ( (newType as ComponentClass<any>).getDerivedStateFromProps == null && component.componentWillMount != null ) { component.componentWillMount(); } if (component.componentDidMount != null) { component._renderCallbacks.push(component.componentDidMount); } } else { if ( (newType as ComponentClass<any>).getDerivedStateFromProps == null && newProps !== oldProps && component.componentWillReceiveProps != null ) { component.componentWillReceiveProps(newProps, componentContext); } if ( (!component._force && component.shouldComponentUpdate != null && component.shouldComponentUpdate( newProps, component._nextState, componentContext, ) === false) || newVNode._original === oldVNode?._original ) { component.props = newProps; component.state = component._nextState; // More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8 if (newVNode._original !== oldVNode!._original) { component._dirty = false; } component._vnode = newVNode; newVNode._remoteNode = oldVNode!._remoteNode; newVNode._children = oldVNode!._children; if (component._renderCallbacks.length) { commitQueue.push(component); } reorderChildren( newVNode, oldRemoteNode as RemoteComponentNode, parentNode, ); // eslint-disable-next-line no-labels break outer; } if (component.componentWillUpdate != null) { component.componentWillUpdate( newProps, component._nextState, componentContext, ); } if (component.componentDidUpdate != null) { component._renderCallbacks.push(() => { component.componentDidUpdate!(oldProps, oldState, snapshot); }); } } component.context = componentContext; component.props = newProps; component.state = component._nextState; options._render?.(newVNode); component._dirty = false; component._vnode = newVNode; component._parentRemoteNode = parentNode; const renderResult = component.render( component.props, component.state, component.context, ); const normalizedRenderResult = renderResult == null || (renderResult as any).type !== Fragment || (renderResult as any).key != null ? renderResult : (renderResult as VNode<any>).props.children; // Handle setState called in render component.state = component._nextState; const newContext = component.getChildContext == null ? globalContext : {...globalContext, ...component.getChildContext()}; if (!isNew && component.getSnapshotBeforeUpdate != null) { snapshot = component.getSnapshotBeforeUpdate(oldProps, oldState); } diffChildren( parentNode, remoteRoot, Array.isArray(normalizedRenderResult) ? normalizedRenderResult : [normalizedRenderResult], newVNode, oldVNode, newContext, excessRemoteChildren, commitQueue, oldRemoteNode, ); component.base = newVNode._remoteNode!; if (component._renderCallbacks.length) { commitQueue.push(component); } if (clearProcessingException) { component._pendingError = null; component._processingException = null; } component._force = false; } else if ( excessRemoteChildren == null && newVNode._original === oldVNode?._original ) { newVNode._children = oldVNode._children; newVNode._remoteNode = oldVNode._remoteNode; } else { newVNode._remoteNode = diffElementNodes( oldVNode?._remoteNode, remoteRoot, newVNode, oldVNode!, globalContext, excessRemoteChildren, commitQueue, ); } options.diffed?.(newVNode); } catch (error) { newVNode._original = null; // if creating initial tree, bailout preserves DOM: if (excessRemoteChildren != null) { newVNode._remoteNode = oldRemoteNode!; excessRemoteChildren[excessRemoteChildren.indexOf(oldRemoteNode!)] = null; } options._catchError(error, newVNode, oldVNode); } return newVNode._remoteNode; } export function commitRoot( commitQueue: ComponentInternal<any, any>[], vnode: VNode<any>, ) { options._commit?.(vnode, commitQueue); commitQueue.forEach((component) => { try { const renderCallbacks = component._renderCallbacks; component._renderCallbacks = []; renderCallbacks.forEach((cb) => { cb.call(component); }); } catch (error) { options._catchError(error, component._vnode!); } }); } /** * Unmount a virtual node from the tree and apply changes to the remote tree */ export function unmount( vnode: VNode<any>, parentVNode: VNode<any>, skipRemove = false, ) { options.unmount?.(vnode); const {ref, type, _component: component, _children: children} = vnode; let finalSkipRemove = skipRemove; let remoteNode: RemoteChildNode | null | undefined; if (ref) { if ( !(ref as RefObject<any>).current || (ref as RefObject<any>).current === vnode._remoteNode ) { applyRef(ref, null, parentVNode); } } if (!skipRemove && typeof type !== 'function') { remoteNode = vnode._remoteNode; finalSkipRemove = remoteNode != null; } // Must be set to `undefined` to properly clean up `_nextRemoteNode` // for which `null` is a valid value. See comment in `create-element.js` vnode._remoteNode = undefined; vnode._nextRemoteNode = undefined; if (component != null) { if (component.componentWillUnmount) { try { component.componentWillUnmount(); } catch (error) { options._catchError(error, parentVNode); } } component.base = null; component._parentRemoteNode = null; } if (children) { for (const child of children) { if (child) unmount(child, parentVNode, finalSkipRemove); } } remoteNode?.parent?.removeChild(remoteNode); } /** * Diff two virtual nodes representing DOM element * @param {import('../internal').PreactElement} dom The DOM element representing * the virtual nodes being diffed * @param {import('../internal').VNode} newVNode The new virtual node * @param {import('../internal').VNode} oldVNode The old virtual node * @param {object} globalContext The current context object * @param {boolean} isSvg Whether or not this DOM node is an SVG node * @param {*} excessRemoteChildren * @param {Array<import('../internal').Component>} commitQueue List of components * which have callbacks to invoke in commitRoot * @param {boolean} isHydrating Whether or not we are in hydration * @returns {import('../internal').PreactElement} */ function diffElementNodes( remoteNode: RemoteChildNode | undefined | null, remoteRoot: RemoteRoot<any, any>, newVNode: VNode<any>, oldVNode: VNode<any> | undefined, globalContext: any, excessChildren: (RemoteChildNode | null | undefined)[] | null, commitQueue: ComponentInternal<any, any>[], ) { const oldProps = oldVNode?.props; const newProps = newVNode.props; let resolvedRemoteNode = remoteNode; let resolvedExcessChildren = excessChildren; if (excessChildren != null) { for (const child of excessChildren) { // if newVNode matches an element in excessRemoteChildren or the `dom` // argument matches an element in excessRemoteChildren, remove it from // excessRemoteChildren so it isn't later removed in diffChildren if ( child != null && ((newVNode.type === null ? child.kind === KIND_TEXT : (child as RemoteComponent<any, any>).type === newVNode.type) || remoteNode === child) ) { resolvedRemoteNode = child; excessChildren[excessChildren.indexOf(child)] = null; break; } } } if (resolvedRemoteNode == null) { if (newVNode.type === null) { return remoteRoot.createText(newProps); } resolvedRemoteNode = remoteRoot.createComponent(newVNode.type); // we created a new parent, so none of the previously attached children can be reused: resolvedExcessChildren = null; } if (newVNode.type === null) { if ( oldProps !== newProps && (resolvedRemoteNode as RemoteText<any>).text !== newProps ) { (resolvedRemoteNode as RemoteText<any>).updateText(newProps); } } else { resolvedRemoteNode = resolvedRemoteNode as RemoteComponentNode; if (excessChildren != null) { resolvedExcessChildren = [...resolvedRemoteNode.children]; } diffProps(resolvedRemoteNode, newProps, oldProps ?? {}); const {children} = newProps; diffChildren( resolvedRemoteNode, remoteRoot, Array.isArray(children) ? children : [children], newVNode, oldVNode, globalContext, resolvedExcessChildren, commitQueue, ); } return resolvedRemoteNode; } export function applyRef<T>(ref: Ref<T>, value: T, vnode: VNode<any>) { try { if (typeof ref === 'function') { ref(value); } else { ref.current = value; } } catch (error) { options._catchError(error, vnode); } } function reorderChildren( newVNode: VNode<any>, oldRemoteNode: RemoteChildNode, parentRemoteNode: RemoteParentNode, ) { for (const vnode of newVNode._children!) { if (vnode == null) continue; vnode._parent = newVNode; if (vnode._remoteNode) { if (typeof vnode.type === 'function' && vnode._children!.length > 1) { reorderChildren(vnode, oldRemoteNode, parentRemoteNode); } const updatedRemoteNode = placeChild( parentRemoteNode, vnode, vnode, newVNode._children!, null, vnode._remoteNode, oldRemoteNode, ); if (typeof newVNode.type === 'function') { newVNode._nextRemoteNode = updatedRemoteNode; } } } } /** The `.render()` method for a PFC backing instance. */ function doRender( this: {constructor: FunctionComponent<any>}, props: any, _state: any, context: any, ) { return this.constructor(props, context); } /** * Diff the children of a virtual node. */ function diffChildren( parentNode: RemoteParentNode, remoteRoot: RemoteRootNode, renderResult: ComponentChildren[], newParentVNode: VNode<any>, oldParentVNode: VNode<any> | undefined, globalContext: object, excessRemoteChildren: (RemoteChildNode | null | undefined)[] | null, commitQueue: ComponentInternal<any, any>[], oldRemoteNode?: RemoteChildNode | null, ) { const oldChildren = oldParentVNode?._children ?? EMPTY_ARRAY; const oldChildrenLength = oldChildren.length; let resolvedOldRemoteNode: typeof oldRemoteNode | null = oldRemoteNode; // Only in very specific places should this logic be invoked (top level `render` and `diffElementNodes`). // I'm using `EMPTY_OBJ` to signal when `diffChildren` is invoked in these situations. I can't use `null` // for this purpose, because `null` is a valid value for `oldDom` which can mean to skip to this logic // (e.g. if mounting a new tree in which the old DOM should be ignored (usually for Fragments). if (resolvedOldRemoteNode == null) { if (excessRemoteChildren != null) { resolvedOldRemoteNode = excessRemoteChildren[0]; } else if (oldChildrenLength) { resolvedOldRemoteNode = getRemoteSibling(oldParentVNode!, 0); } else { resolvedOldRemoteNode = null; } } newParentVNode._children = []; let index: number; let refs!: [Ref<any>, any, VNode<any>][]; let firstRemoteNode: RemoteChildNode | undefined; for (index = 0; index < renderResult.length; index++) { const rendered = renderResult[index]; let childVNode: VNode<any> | undefined | null; if (rendered == null || typeof rendered === 'boolean') { childVNode = null; } else if (typeof rendered === 'string' || typeof rendered === 'number') { childVNode = createVNode(null, rendered, null, undefined, rendered); } else if (Array.isArray(rendered)) { childVNode = createVNode( Fragment, {children: rendered}, null, undefined, null, ); } else if ( (rendered as VNode<any>)._remoteNode != null || (rendered as VNode<any>)._component != null ) { childVNode = createVNode( (rendered as VNode<any>).type, (rendered as VNode<any>).props, (rendered as VNode<any>).key, undefined, (rendered as VNode<any>)._original, ); } else { childVNode = rendered as VNode<any> | null; } newParentVNode._children[index] = childVNode; // Terser removes the `continue` here and wraps the loop body // in a `if (childVNode) { ... } condition if (childVNode == null) { continue; } childVNode._parent = newParentVNode; childVNode._depth = newParentVNode._depth + 1; // Check if we find a corresponding element in oldChildren. // If found, delete the array item by setting to `undefined`. // We use `undefined`, as `null` is reserved for empty placeholders // (holes). let oldVNode = oldChildren[index]; if ( oldVNode === null || (oldVNode && childVNode.key === oldVNode.key && childVNode.type === oldVNode.type) ) { oldChildren[index] = undefined; } else { // Either oldVNode === undefined or oldChildrenLength > 0, // so after this loop oldVNode == null or oldVNode is a valid value. for (let oldIndex = 0; oldIndex < oldChildrenLength; oldIndex++) { oldVNode = oldChildren[oldIndex]; // If childVNode is unkeyed, we only match similarly unkeyed nodes, otherwise we match by key. // We always match by type (in either case). if ( oldVNode && childVNode.key === oldVNode.key && childVNode.type === oldVNode.type ) { oldChildren[oldIndex] = undefined; break; } oldVNode = null; } } // Morph the old element into the new one, but don't append it to the dom yet const newRemoteNode = diff( parentNode, remoteRoot, childVNode, oldVNode ?? undefined, globalContext, excessRemoteChildren, commitQueue, resolvedOldRemoteNode, ); const ref = childVNode.ref; if (ref && oldVNode?.ref !== ref) { if (!refs) { refs = []; } if (oldVNode?.ref) { refs.push([oldVNode.ref, null, childVNode]); } refs.push([ref, childVNode._component ?? newRemoteNode, childVNode]); } if (newRemoteNode != null) { if (firstRemoteNode == null) { firstRemoteNode = newRemoteNode; } resolvedOldRemoteNode = placeChild( parentNode, childVNode, oldVNode, oldChildren, excessRemoteChildren, newRemoteNode, resolvedOldRemoteNode, ); if (typeof newParentVNode.type === 'function') { // Because the newParentVNode is Fragment-like, we need to set it's // _nextDom property to the nextSibling of its last child DOM node. // // `resolvedOldRemoteNode` contains the correct value here because if the last child // is a Fragment-like, then resolvedOldRemoteNode has already been set to that child's _nextRemoteNode. // If the last child is a DOM VNode, then oldDom will be set to that DOM // node's nextSibling. newParentVNode._nextRemoteNode = resolvedOldRemoteNode!; } } else if ( resolvedOldRemoteNode && // eslint-disable-next-line eqeqeq oldVNode?._remoteNode == resolvedOldRemoteNode && resolvedOldRemoteNode.parent !== parentNode ) { // The above condition is to handle null placeholders resolvedOldRemoteNode = getRemoteSibling(oldVNode); } } newParentVNode._remoteNode = firstRemoteNode!; // Remove children that are not part of any vnode. if ( excessRemoteChildren != null && typeof newParentVNode.type !== 'function' ) { for (let index = excessRemoteChildren.length; index--; ) { if (excessRemoteChildren[index] != null) { removeNode(excessRemoteChildren[index]!); } } } // Remove remaining oldChildren if there are any. for (let index = oldChildrenLength; index--; ) { const child = oldChildren[index]; if (child != null) { unmount(child, child); } } // Set refs only after unmount if (refs) { for (const refEntry of refs) { applyRef(...refEntry); } } } function placeChild( parentNode: RemoteParentNode, childVNode: VNode<any>, oldVNode: VNode<any> | null | undefined, oldChildren: (VNode<any> | null | undefined)[], excessRemoteChildren: (RemoteChildNode | null | undefined)[] | null, newRemoteNode: RemoteChildNode, oldRemoteNode: RemoteChildNode | null | undefined, ) { let nextRemoteNode: RemoteChildNode | null | undefined; if (childVNode._nextRemoteNode !== undefined) { // Only Fragments or components that return Fragment like VNodes will // have a non-undefined _nextRemoteNode. Continue the diff from the sibling // of last DOM child of this child VNode nextRemoteNode = childVNode._nextRemoteNode; // Eagerly cleanup _nextRemoteNode. We don't need to persist the value because // it is only used by `diffChildren` to determine where to resume the diff after // diffing Components and Fragments. Once we store it the nextRemoteNode local var, we // can clean up the property childVNode._nextRemoteNode = undefined; } else if ( // eslint-disable-next-line eqeqeq excessRemoteChildren == oldVNode || newRemoteNode !== oldRemoteNode || newRemoteNode.parent == null ) { // NOTE: excessDomChildren==oldVNode above: // This is a compression of excessDomChildren==null && oldVNode==null! // The values only have the same type when `null`. // eslint-disable-next-line no-labels outer: if (oldRemoteNode == null || oldRemoteNode.parent !== parentNode) { parentNode.appendChild(newRemoteNode); nextRemoteNode = null; } else { // `j<oldChildrenLength; j+=2` is an alternative to `j++<oldChildrenLength/2` for ( let siblingRemoteNode = oldRemoteNode, j = 0; (siblingRemoteNode = nextSiblingRemote(siblingRemoteNode)) && j < oldChildren.length; j += 2 ) { if (siblingRemoteNode === newRemoteNode) { // eslint-disable-next-line no-labels break outer; } } parentNode.insertChildBefore(newRemoteNode, oldRemoteNode); nextRemoteNode = oldRemoteNode; } } // If we have pre-calculated the nextDOM node, use it. Else calculate it now // Strictly check for `undefined` here cuz `null` is a valid value of `nextDom`. // See more detail in create-element.js:createVNode return nextRemoteNode === undefined ? nextSiblingRemote(newRemoteNode) : nextRemoteNode; } function nextSiblingRemote(node: RemoteChild<any>) { const {parent} = node; if (parent == null) return null; const parentChildren = parent.children; return parentChildren[parentChildren.indexOf(node) + 1] || null; }
the_stack
'use strict'; const elementId: { [key: string]: string } = { // Basic settings configName: "configName", configNameInvalid: "configNameInvalid", configSelection: "configSelection", addConfigDiv: "addConfigDiv", addConfigBtn: "addConfigBtn", addConfigInputDiv: "addConfigInputDiv", addConfigOk: "addConfigOk", addConfigCancel: "addConfigCancel", addConfigName: "addConfigName", compilerPath: "compilerPath", compilerPathInvalid: "compilerPathInvalid", knownCompilers: "knownCompilers", noCompilerPathsDetected: "noCompilerPathsDetected", compilerArgs: "compilerArgs", intelliSenseMode: "intelliSenseMode", intelliSenseModeInvalid: "intelliSenseModeInvalid", includePath: "includePath", includePathInvalid: "includePathInvalid", defines: "defines", cStandard: "cStandard", cppStandard: "cppStandard", // Advanced settings windowsSdkVersion: "windowsSdkVersion", macFrameworkPath: "macFrameworkPath", macFrameworkPathInvalid: "macFrameworkPathInvalid", compileCommands: "compileCommands", compileCommandsInvalid: "compileCommandsInvalid", configurationProvider: "configurationProvider", forcedInclude: "forcedInclude", forcedIncludeInvalid: "forcedIncludeInvalid", mergeConfigurations: "mergeConfigurations", // Browse properties browsePath: "browsePath", browsePathInvalid: "browsePathInvalid", limitSymbolsToIncludedHeaders: "limitSymbolsToIncludedHeaders", databaseFilename: "databaseFilename", databaseFilenameInvalid: "databaseFilenameInvalid", // Other showAdvanced: "showAdvanced", advancedSection: "advancedSection" }; interface VsCodeApi { postMessage(msg: {}): void; setState(state: {}): void; getState(): {}; } declare function acquireVsCodeApi(): VsCodeApi; class SettingsApp { private readonly vsCodeApi: VsCodeApi; private updating: boolean = false; constructor() { this.vsCodeApi = acquireVsCodeApi(); window.addEventListener("keydown", this.onTabKeyDown.bind(this)); window.addEventListener("message", this.onMessageReceived.bind(this)); // Add event listeners to UI elements this.addEventsToConfigNameChanges(); this.addEventsToInputValues(); document.getElementById(elementId.knownCompilers).addEventListener("change", this.onKnownCompilerSelect.bind(this)); // Set view state of advanced settings and add event const oldState: any = this.vsCodeApi.getState(); const advancedShown: boolean = (oldState && oldState.advancedShown); document.getElementById(elementId.advancedSection).style.display = advancedShown ? "block" : "none"; document.getElementById(elementId.showAdvanced).classList.toggle(advancedShown ? "collapse" : "expand", true); document.getElementById(elementId.showAdvanced).addEventListener("click", this.onShowAdvanced.bind(this)); this.vsCodeApi.postMessage({ command: "initialized" }); } private addEventsToInputValues(): void { const elements: NodeListOf<HTMLElement> = document.getElementsByName("inputValue"); elements.forEach(el => { el.addEventListener("change", this.onChanged.bind(this, el.id)); }); // Special case for checkbox elements document.getElementById(elementId.limitSymbolsToIncludedHeaders).addEventListener("change", this.onChangedCheckbox.bind(this, elementId.limitSymbolsToIncludedHeaders)); document.getElementById(elementId.mergeConfigurations).addEventListener("change", this.onChangedCheckbox.bind(this, elementId.mergeConfigurations)); } private addEventsToConfigNameChanges(): void { document.getElementById(elementId.configName).addEventListener("change", this.onConfigNameChanged.bind(this)); document.getElementById(elementId.configSelection).addEventListener("change", this.onConfigSelect.bind(this)); document.getElementById(elementId.addConfigBtn).addEventListener("click", this.onAddConfigBtn.bind(this)); document.getElementById(elementId.addConfigOk).addEventListener("click", this.OnAddConfigConfirm.bind(this, true)); document.getElementById(elementId.addConfigCancel).addEventListener("click", this.OnAddConfigConfirm.bind(this, false)); } private onTabKeyDown(e: any): void { if (e.keyCode === 9) { document.body.classList.add("tabbing"); window.removeEventListener("keydown", this.onTabKeyDown); window.addEventListener("mousedown", this.onMouseDown.bind(this)); } } private onMouseDown(): void { document.body.classList.remove("tabbing"); window.removeEventListener("mousedown", this.onMouseDown); window.addEventListener("keydown", this.onTabKeyDown.bind(this)); } private onShowAdvanced(): void { const isShown: boolean = (document.getElementById(elementId.advancedSection).style.display === "block"); document.getElementById(elementId.advancedSection).style.display = isShown ? "none" : "block"; // Save view state this.vsCodeApi.setState({ advancedShown: !isShown }); // Update chevron on button const element: HTMLElement = document.getElementById(elementId.showAdvanced); element.classList.toggle("collapse"); element.classList.toggle("expand"); } private onAddConfigBtn(): void { this.showElement(elementId.addConfigDiv, false); this.showElement(elementId.addConfigInputDiv, true); } private OnAddConfigConfirm(request: boolean): void { this.showElement(elementId.addConfigInputDiv, false); this.showElement(elementId.addConfigDiv, true); // If request is yes, send message to create new config if (request) { const el: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId.addConfigName); if (el.value !== undefined && el.value !== "") { this.vsCodeApi.postMessage({ command: "addConfig", name: el.value }); el.value = ""; } } } private onConfigNameChanged(): void { if (this.updating) { return; } const configName: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId.configName); const list: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.configSelection); if (configName.value === "") { (<HTMLInputElement>document.getElementById(elementId.configName)).value = list.options[list.selectedIndex].value; return; } // Update name on selection list.options[list.selectedIndex].value = configName.value; list.options[list.selectedIndex].text = configName.value; this.onChanged(elementId.configName); } private onConfigSelect(): void { if (this.updating) { return; } const el: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.configSelection); (<HTMLInputElement>document.getElementById(elementId.configName)).value = el.value; this.vsCodeApi.postMessage({ command: "configSelect", index: el.selectedIndex }); } private onKnownCompilerSelect(): void { if (this.updating) { return; } const el: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId.knownCompilers); (<HTMLInputElement>document.getElementById(elementId.compilerPath)).value = el.value; this.onChanged(elementId.compilerPath); // Post message that this control was used for telemetry this.vsCodeApi.postMessage({ command: "knownCompilerSelect" }); // Reset selection to none el.value = ""; } private onChangedCheckbox(id: string): void { if (this.updating) { return; } const el: HTMLInputElement = <HTMLInputElement>document.getElementById(id); this.vsCodeApi.postMessage({ command: "change", key: id, value: el.checked }); } private onChanged(id: string): void { if (this.updating) { return; } const el: HTMLInputElement = <HTMLInputElement>document.getElementById(id); this.vsCodeApi.postMessage({ command: "change", key: id, value: el.value }); } private onMessageReceived(e: MessageEvent): void { const message: any = e.data; // The json data that the extension sent switch (message.command) { case 'updateConfig': this.updateConfig(message.config); break; case 'updateErrors': this.updateErrors(message.errors); break; case 'setKnownCompilers': this.setKnownCompilers(message.compilers); break; case 'updateConfigSelection': this.updateConfigSelection(message); break; } } private updateConfig(config: any): void { this.updating = true; try { const joinEntries: (input: any) => string = (input: string[]) => (input && input.length) ? input.join("\n") : ""; // Basic settings (<HTMLInputElement>document.getElementById(elementId.configName)).value = config.name; (<HTMLInputElement>document.getElementById(elementId.compilerPath)).value = config.compilerPath ? config.compilerPath : ""; (<HTMLInputElement>document.getElementById(elementId.compilerArgs)).value = joinEntries(config.compilerArgs); (<HTMLInputElement>document.getElementById(elementId.intelliSenseMode)).value = config.intelliSenseMode ? config.intelliSenseMode : "${default}"; (<HTMLInputElement>document.getElementById(elementId.includePath)).value = joinEntries(config.includePath); (<HTMLInputElement>document.getElementById(elementId.defines)).value = joinEntries(config.defines); (<HTMLInputElement>document.getElementById(elementId.cStandard)).value = config.cStandard; (<HTMLInputElement>document.getElementById(elementId.cppStandard)).value = config.cppStandard; // Advanced settings (<HTMLInputElement>document.getElementById(elementId.windowsSdkVersion)).value = config.windowsSdkVersion ? config.windowsSdkVersion : ""; (<HTMLInputElement>document.getElementById(elementId.macFrameworkPath)).value = joinEntries(config.macFrameworkPath); (<HTMLInputElement>document.getElementById(elementId.compileCommands)).value = config.compileCommands ? config.compileCommands : ""; (<HTMLInputElement>document.getElementById(elementId.mergeConfigurations)).checked = config.mergeConfigurations; (<HTMLInputElement>document.getElementById(elementId.configurationProvider)).value = config.configurationProvider ? config.configurationProvider : ""; (<HTMLInputElement>document.getElementById(elementId.forcedInclude)).value = joinEntries(config.forcedInclude); if (config.browse) { (<HTMLInputElement>document.getElementById(elementId.browsePath)).value = joinEntries(config.browse.path); (<HTMLInputElement>document.getElementById(elementId.limitSymbolsToIncludedHeaders)).checked = (config.browse.limitSymbolsToIncludedHeaders && config.browse.limitSymbolsToIncludedHeaders); (<HTMLInputElement>document.getElementById(elementId.databaseFilename)).value = config.browse.databaseFilename ? config.browse.databaseFilename : ""; } else { (<HTMLInputElement>document.getElementById(elementId.browsePath)).value = ""; (<HTMLInputElement>document.getElementById(elementId.limitSymbolsToIncludedHeaders)).checked = false; (<HTMLInputElement>document.getElementById(elementId.databaseFilename)).value = ""; } } finally { this.updating = false; } } private updateErrors(errors: any): void { this.updating = true; try { this.showErrorWithInfo(elementId.configNameInvalid, errors.name); this.showErrorWithInfo(elementId.intelliSenseModeInvalid, errors.intelliSenseMode); this.showErrorWithInfo(elementId.compilerPathInvalid, errors.compilerPath); this.showErrorWithInfo(elementId.includePathInvalid, errors.includePath); this.showErrorWithInfo(elementId.macFrameworkPathInvalid, errors.macFrameworkPath); this.showErrorWithInfo(elementId.forcedIncludeInvalid, errors.forcedInclude); this.showErrorWithInfo(elementId.compileCommandsInvalid, errors.compileCommands); this.showErrorWithInfo(elementId.browsePathInvalid, errors.browsePath); this.showErrorWithInfo(elementId.databaseFilenameInvalid, errors.databaseFilename); } finally { this.updating = false; } } private showErrorWithInfo(elementID: string, errorInfo: string): void { this.showElement(elementID, errorInfo ? true : false); document.getElementById(elementID).innerHTML = errorInfo ? errorInfo : ""; } private updateConfigSelection(message: any): void { this.updating = true; try { const list: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.configSelection); // Clear list before updating list.options.length = 0; // Update list for (const name of message.selections) { const option: HTMLOptionElement = document.createElement("option"); option.text = name; option.value = name; list.append(option); } list.selectedIndex = message.selectedIndex; } finally { this.updating = false; } } private setKnownCompilers(compilers: string[]): void { this.updating = true; try { const list: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.knownCompilers); // No need to add items unless webview is reloaded, in which case it will not have any elements. // Otherwise, add items again. if (list.firstChild) { return; } if (compilers.length === 0) { // Get HTML element containing the string, as we can't localize strings in HTML js const noCompilerSpan: HTMLSpanElement = <HTMLSpanElement>document.getElementById(elementId.noCompilerPathsDetected); const option: HTMLOptionElement = document.createElement("option"); option.text = noCompilerSpan.textContent; option.disabled = true; list.append(option); } else { for (const path of compilers) { const option: HTMLOptionElement = document.createElement("option"); option.text = path; option.value = path; list.append(option); } } this.showElement(elementId.compilerPath, true); this.showElement(elementId.knownCompilers, true); // Initialize list with no selected item list.value = ""; } finally { this.updating = false; } } private showElement(elementID: string, show: boolean): void { document.getElementById(elementID).style.display = show ? "block" : "none"; } } const app: SettingsApp = new SettingsApp();
the_stack
import Alert from 'antd/es/alert'; import BackTop from 'antd/es/back-top'; import Card from 'antd/es/card'; import Col from 'antd/es/col'; import Row from 'antd/es/row'; import Spin from 'antd/es/spin'; import clsx from 'clsx'; import * as echarts from 'echarts/lib/echarts'; import { find, get, isEmpty, last, map } from 'lodash'; import mapboxgl from 'mapbox-gl'; import * as React from 'react'; import { useEffect } from 'react'; import { ApiKey } from '../constants/api-key'; import { coordinates } from '../constants/coordinates'; import { dailyChartConfig, pieChartConfig, testsChartConfig } from './chart-config'; declare let process: { env: { NODE_ENV: string; }; }; const CLOUD_URL = process.env.NODE_ENV === 'development' ? 'http://localhost:3000/covidData' : 'https://covid19nz.s3.amazonaws.com/covid-19.json'; export const Covid19: React.FC = () => { const [isLoadingState, setIsloadingState] = React.useState(true); const [errorState, setErrorState] = React.useState(null); const [covidState, setCovidState] = React.useState(null); const [largestState, setLargestState] = React.useState(0); const [totalCasesState, setTotalCasesState] = React.useState(0); const renderChart = () => { try { const covidChart = document.getElementById('covid-daily-chart'); covidChart.parentNode.removeChild(covidChart); const pieChart = document.getElementById('covid-pie-chart'); pieChart.parentNode.removeChild(pieChart); const testsChart = document.getElementById('covid-tests-chart'); testsChart.parentNode.removeChild(testsChart); } catch (err) {} // Generate div element dynamically for ECharts const covidDailyDivElement: HTMLDivElement = document.createElement('div'); covidDailyDivElement.setAttribute('id', 'covid-daily-chart'); covidDailyDivElement.setAttribute('class', 'covid-daily-chart'); document.getElementById('covid-chart-wrapper').appendChild(covidDailyDivElement); const covidPieDivElement: HTMLDivElement = document.createElement('div'); covidPieDivElement.setAttribute('id', 'covid-pie-chart'); covidPieDivElement.setAttribute('class', 'covid-pie-chart'); document.getElementById('covid-pie-wrapper').appendChild(covidPieDivElement); const covidTestsDivElement: HTMLDivElement = document.createElement('div'); covidTestsDivElement.setAttribute('id', 'covid-tests-chart'); covidTestsDivElement.setAttribute('class', 'covid-tests-chart'); document.getElementById('covid-tests-wrapper').appendChild(covidTestsDivElement); let dailyChart = echarts.getInstanceByDom(covidDailyDivElement); let pieChart = echarts.getInstanceByDom(covidPieDivElement); let testsChart = echarts.getInstanceByDom(covidTestsDivElement); if (!dailyChart && !pieChart && !testsChart) { dailyChart = echarts.init(covidDailyDivElement); dailyChart.setOption(dailyChartConfig(covidState.daily)); pieChart = echarts.init(covidPieDivElement); pieChart.setOption(pieChartConfig(covidState.ages, covidState.ethnicity)); testsChart = echarts.init(covidTestsDivElement); testsChart.setOption(testsChartConfig(covidState.daily)); } }; const renderMapbox = () => { const features: { type: 'Feature'; geometry: { type: 'Point'; coordinates: number[]; }; properties: { region: string; totalCases: number; femaleCases: number; maleCases: number; unknownCases: number; percentage: number; }; }[] = []; const caseByRegion = { Auckland: { total: 0, female: 0, male: 0, unknown: 0, }, Wellington: { total: 0, female: 0, male: 0, unknown: 0, }, Waikato: { total: 0, female: 0, male: 0, unknown: 0, }, 'Manawatu-Whanganui': { total: 0, female: 0, male: 0, unknown: 0, }, Canterbury: { total: 0, female: 0, male: 0, unknown: 0, }, }; // Calculate the totalCases const totalCases = last(covidState.daily)['totalConfirmed'] + last(covidState.daily)['totalProbable']; setTotalCasesState(totalCases); const regionTotalCases = (key: string) => { return ( get(covidState.location[key], 'female', 0) + get(covidState.location[key], 'male', 0) + get(covidState.location[key], 'unknown', 0) ); }; const getCaseDataByRegion = (caseByRegion: any, key: string, region: string) => { caseByRegion[region].total += regionTotalCases(key); caseByRegion[region].female += get(covidState.location[key], 'female', 0); caseByRegion[region].male += get(covidState.location[key], 'male', 0); caseByRegion[region].unknown += get(covidState.location[key], 'unknown', 0); }; // Prepare GeoJson data Object.keys(covidState.location).forEach((key) => { if (key === 'Auckland' || key === 'Counties Manukau' || key === 'Waitemata') { // Auckland region getCaseDataByRegion(caseByRegion, key, 'Auckland'); } else if (key === 'Capital and Coast' || key === 'Hutt Valley' || key === 'Wairarapa') { // Wellington region getCaseDataByRegion(caseByRegion, key, 'Wellington'); } else if (key === 'Waikato' || key === 'Lakes') { // Waikato region getCaseDataByRegion(caseByRegion, key, 'Waikato'); } else if (key === 'Whanganui' || key === 'MidCentral') { // Manawatu-Whanganui region getCaseDataByRegion(caseByRegion, key, 'Manawatu-Whanganui'); } else if (key === 'Canterbury' || key === 'South Canterbury') { // Canterbury region getCaseDataByRegion(caseByRegion, key, 'Canterbury'); } else { features.push({ type: 'Feature', geometry: { type: 'Point', coordinates: find(coordinates, (coordinate) => key === 'Tairāwhiti' ? coordinate.region === 'Gisborne' : key === 'Southern' ? coordinate.region === 'Otago Southland' : coordinate.region === key ).coordinates, }, properties: { region: key === 'Tairāwhiti' ? 'Gisborne' : key === 'Southern' ? 'Otago Southland' : key, totalCases: regionTotalCases(key), femaleCases: get(covidState.location[key], 'female', 0), maleCases: get(covidState.location[key], 'male', 0), unknownCases: get(covidState.location[key], 'unknown', 0), percentage: Math.ceil((regionTotalCases(key) / totalCases) * 100), }, }); } }); Object.keys(caseByRegion).forEach((region) => { features.push({ type: 'Feature', geometry: { type: 'Point', coordinates: find(coordinates, (coordinate) => coordinate.region === region).coordinates, }, properties: { region: region, totalCases: caseByRegion[region].total, femaleCases: caseByRegion[region].female, maleCases: caseByRegion[region].male, unknownCases: caseByRegion[region].unknown, percentage: Math.ceil((caseByRegion[region].total / totalCases) * 100), }, }); }); // Find the largest number in the regions const largest = Math.max.apply(Math, map(features, 'properties.totalCases')); setLargestState(largest); // Initial Mapbox mapboxgl.accessToken = ApiKey.mapbox; const mapBox = new mapboxgl.Map({ container: 'new-zealand-map', style: 'mapbox://styles/mapbox/light-v10', center: [173.295319, -41.288483], // [lng, lat], Nelson zoom: 5, }); // disable map rotation using right click + drag mapBox.dragRotate.disable(); // disable map rotation using touch rotation gesture mapBox.touchZoomRotate.disableRotation(); mapBox.on('load', () => { mapBox.addSource('covidCases', { type: 'geojson', data: { type: 'FeatureCollection', features, }, }); // Add a layer showing the places. mapBox.addLayer({ id: 'regions', interactive: true, type: 'circle', source: 'covidCases', paint: { 'circle-color': ['interpolate', ['linear'], ['get', 'totalCases'], 1, '#FCA107', largest, '#7F3121'], 'circle-opacity': 0.65, 'circle-radius': ['interpolate', ['linear'], ['get', 'totalCases'], 1, 10, largest, Math.ceil(largest / 7)], }, }); // Add a layer showing the number of cases. mapBox.addLayer({ id: 'cases-count', type: 'symbol', source: 'covidCases', layout: { 'text-field': '{totalCases}', 'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'], 'text-size': 12, }, paint: { 'text-color': 'rgba(0,0,0,0.45)', }, }); // Create a popup, but don't add it to the map yet. const popup = new mapboxgl.Popup({ closeButton: false, closeOnClick: false, }); mapBox.on('mouseenter', 'regions', (event: any) => { // Change the cursor style as a UI indicator. mapBox.getCanvas().style.cursor = 'pointer'; const coordinates = event.features[0].geometry.coordinates.slice(); const description = `<strong>${event.features[0].properties.region}</strong><br/>` + `${event.features[0].properties.totalCases} cases, ${event.features[0].properties.percentage}%<br/>` + `female: ${event.features[0].properties.femaleCases}, male: ${event.features[0].properties.maleCases}, unknown: ${event.features[0].properties.unknownCases}`; // Ensure that if the map is zoomed out such that multiple // copies of the feature are visible, the popup appears // over the copy being pointed to. while (Math.abs(event.lngLat.lng - coordinates[0]) > 180) { coordinates[0] += event.lngLat.lng > coordinates[0] ? 360 : -360; } // Populate the popup and set its coordinates // based on the feature found. popup.setLngLat(coordinates).setHTML(description).addTo(mapBox); }); mapBox.on('mouseleave', 'regions', () => { mapBox.getCanvas().style.cursor = ''; popup.remove(); }); }); }; useEffect(() => { fetch(CLOUD_URL) .then((response: any): any => response.json()) .then((data: any) => { setCovidState(data); setIsloadingState(false); }) .catch((error) => { setIsloadingState(false); setErrorState(error); }); }, []); useEffect(() => { if (!isLoadingState && !isEmpty(covidState)) { renderChart(); renderMapbox(); } }); return ( <div> <Row justify='center' className='covid-title'> Covid-19 in New Zealand </Row> {isLoadingState ? ( <Row justify='center' className='fetching-weather-content'> <Spin className='fetching-weather-spinner' size='large' /> <h2 className='loading-text'>Loading...</h2> </Row> ) : !isEmpty(errorState) ? ( <div> <Row justify='center' className='fetching-weather-content'> <Col xs={24} sm={24} md={18} lg={16} xl={16}> <Alert message='Error' description={errorState} type='error' showIcon={true} /> </Col> </Row> </div> ) : ( <> {/* Grid */} <Row justify='center' gutter={16}> <Col sm={6} md={6} lg={4} xl={4} xxl={3} className='covid-cases-card'> <Card title='Total Confirmed'> <div className='covid-cases-card-content'>{last(covidState.daily)['totalConfirmed']}</div> </Card> </Col> <Col sm={6} md={6} lg={4} xl={4} xxl={3} className='covid-cases-card'> <Card title='Total Cases'> <div className='covid-cases-card-content'>{totalCasesState}</div> </Card> </Col> <Col sm={6} md={6} lg={4} xl={4} xxl={3} className='covid-cases-card'> <Card title='Total Recovered'> <div className={clsx('covid-recovered-cases-content', 'covid-cases-card-content')}> {last(covidState.daily)['totalRecovered']} </div> </Card> </Col> <Col sm={6} md={6} lg={4} xl={4} xxl={3} className='covid-cases-card'> <Card title='Total Death'> <div className={clsx('covid-death-cases-content', 'covid-cases-card-content')}> {last(covidState.daily)['totalDeath']} </div> </Card> </Col> </Row> <Row justify='center' style={{ padding: '1rem 0' }}> [<a href='#covid-pie-wrapper'>Age, Gender and Ethnicity Groups</a>] [<a href='#new-zealand-map'>Map</a>] [ <a href='#covid-tests-wrapper'>Tests v.s Cases</a>] </Row> <Row justify='center'> <div className='forecast-summary'>1st case on 28-02-2020</div> </Row> {/* Chart */} <Row justify='center' id='covid-chart-wrapper' /> <Row justify='center' id='covid-pie-wrapper' /> <Row justify='center' id='covid-tests-wrapper' /> {/* Map */} <Row justify='center'> <div className='map-title'>Total Cases by Regions</div> </Row> <Row justify='center'> <div style={{ position: 'relative' }}> <div id='new-zealand-map' /> <div className='map-legend-overlay'> <div className='map-legend-wrapper'> <div> <div style={{ display: 'flex', justifyContent: 'space-between' }}> <div>1</div> <div>{largestState}</div> </div> <div className='map-legend' /> <div>Cases</div> </div> </div> </div> </div> </Row> {/* Last updated */} <Row justify='center'> <Col span={24} className={clsx('covid-cases-card', 'last-updated')}> Last updated: {covidState.lastUpdated} </Col> </Row> </> )} <BackTop /> </div> ); };
the_stack
import localVarRequest = require('request'); import http = require('http'); import Promise = require('bluebird'); let defaultBasePath = 'http://petstore.swagger.io/v2'; // =============================================== // This file is autogenerated - Please do not edit // =============================================== /* tslint:disable:no-unused-variable */ let primitives = [ "string", "boolean", "double", "integer", "long", "float", "number", "any" ]; class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { return expectedType; } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { return expectedType; } else if (expectedType === "Date") { return expectedType; } else { if (enumsMap[expectedType]) { return expectedType; } if (!typeMap[expectedType]) { return expectedType; // w/e we don't know the type } // Check the discriminator let discriminatorProperty = typeMap[expectedType].discriminator; if (discriminatorProperty == null) { return expectedType; // the type does not have a discriminator. use it. } else { if (data[discriminatorProperty]) { return data[discriminatorProperty]; // use the type given in the discriminator } else { return expectedType; // discriminator was not present (or an empty string) } } } } public static serialize(data: any, type: string) { if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index in data) { let date = data[index]; transformedData.push(ObjectSerializer.serialize(date, subType)); } return transformedData; } else if (type === "Date") { return data.toString(); } else { if (enumsMap[type]) { return data; } if (!typeMap[type]) { // in case we dont know the type return data; } // get the map for the correct type. let attributeTypes = typeMap[type].getAttributeTypeMap(); let instance: {[index: string]: any} = {}; for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); } return instance; } } public static deserialize(data: any, type: string) { // polymorphism may change the actual type. type = ObjectSerializer.findCorrectType(data, type); if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index in data) { let date = data[index]; transformedData.push(ObjectSerializer.deserialize(date, subType)); } return transformedData; } else if (type === "Date") { return new Date(data); } else { if (enumsMap[type]) {// is Enum return data; } if (!typeMap[type]) { // dont know the type return data; } let instance = new typeMap[type](); let attributeTypes = typeMap[type].getAttributeTypeMap(); for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); } return instance; } } } /** * some description */ export class Amount { /** * some description */ 'value': number; 'currency': Currency; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "value", "baseName": "value", "type": "number" }, { "name": "currency", "baseName": "currency", "type": "Currency" } ]; static getAttributeTypeMap() { return Amount.attributeTypeMap; } } /** * Describes the result of uploading an image resource */ export class ApiResponse { 'code'?: number; 'type'?: string; 'message'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "code", "baseName": "code", "type": "number" }, { "name": "type", "baseName": "type", "type": "string" }, { "name": "message", "baseName": "message", "type": "string" } ]; static getAttributeTypeMap() { return ApiResponse.attributeTypeMap; } } /** * A category for a pet */ export class Category { 'id'?: number; 'name'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "id", "baseName": "id", "type": "number" }, { "name": "name", "baseName": "name", "type": "string" } ]; static getAttributeTypeMap() { return Category.attributeTypeMap; } } /** * some description */ export class Currency { static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ ]; static getAttributeTypeMap() { return Currency.attributeTypeMap; } } /** * An order for a pets from the pet store */ export class Order { 'id'?: number; 'petId'?: number; 'quantity'?: number; 'shipDate'?: Date; /** * Order Status */ 'status'?: Order.StatusEnum; 'complete'?: boolean; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "id", "baseName": "id", "type": "number" }, { "name": "petId", "baseName": "petId", "type": "number" }, { "name": "quantity", "baseName": "quantity", "type": "number" }, { "name": "shipDate", "baseName": "shipDate", "type": "Date" }, { "name": "status", "baseName": "status", "type": "Order.StatusEnum" }, { "name": "complete", "baseName": "complete", "type": "boolean" } ]; static getAttributeTypeMap() { return Order.attributeTypeMap; } } export namespace Order { export enum StatusEnum { Placed = <any> 'placed', Approved = <any> 'approved', Delivered = <any> 'delivered' } } /** * A pet for sale in the pet store */ export class Pet { 'id'?: number; 'category'?: Category; 'name': string; 'photoUrls': Array<string>; 'tags'?: Array<Tag>; /** * pet status in the store */ 'status'?: Pet.StatusEnum; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "id", "baseName": "id", "type": "number" }, { "name": "category", "baseName": "category", "type": "Category" }, { "name": "name", "baseName": "name", "type": "string" }, { "name": "photoUrls", "baseName": "photoUrls", "type": "Array<string>" }, { "name": "tags", "baseName": "tags", "type": "Array<Tag>" }, { "name": "status", "baseName": "status", "type": "Pet.StatusEnum" } ]; static getAttributeTypeMap() { return Pet.attributeTypeMap; } } export namespace Pet { export enum StatusEnum { Available = <any> 'available', Pending = <any> 'pending', Sold = <any> 'sold' } } /** * A tag for a pet */ export class Tag { 'id'?: number; 'name'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "id", "baseName": "id", "type": "number" }, { "name": "name", "baseName": "name", "type": "string" } ]; static getAttributeTypeMap() { return Tag.attributeTypeMap; } } /** * A User who is purchasing from the pet store */ export class User { 'id'?: number; 'username'?: string; 'firstName'?: string; 'lastName'?: string; 'email'?: string; 'password'?: string; 'phone'?: string; /** * User Status */ 'userStatus'?: number; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "id", "baseName": "id", "type": "number" }, { "name": "username", "baseName": "username", "type": "string" }, { "name": "firstName", "baseName": "firstName", "type": "string" }, { "name": "lastName", "baseName": "lastName", "type": "string" }, { "name": "email", "baseName": "email", "type": "string" }, { "name": "password", "baseName": "password", "type": "string" }, { "name": "phone", "baseName": "phone", "type": "string" }, { "name": "userStatus", "baseName": "userStatus", "type": "number" } ]; static getAttributeTypeMap() { return User.attributeTypeMap; } } let enumsMap: {[index: string]: any} = { "Order.StatusEnum": Order.StatusEnum, "Pet.StatusEnum": Pet.StatusEnum, } let typeMap: {[index: string]: any} = { "Amount": Amount, "ApiResponse": ApiResponse, "Category": Category, "Currency": Currency, "Order": Order, "Pet": Pet, "Tag": Tag, "User": User, } export interface Authentication { /** * Apply authentication settings to header and query params. */ applyToRequest(requestOptions: localVarRequest.Options): void; } export class HttpBasicAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } } } export class ApiKeyAuth implements Authentication { public apiKey: string = ''; constructor(private location: string, private paramName: string) { } applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (<any>requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { requestOptions.headers[this.paramName] = this.apiKey; } } } export class OAuth implements Authentication { public accessToken: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } } } export class VoidAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(_: localVarRequest.Options): void { // Do nothing } } export enum PetApiApiKeys { api_key, } export class PetApi { protected _basePath = defaultBasePath; protected defaultHeaders : any = {}; protected _useQuerystring : boolean = false; protected authentications = { 'default': <Authentication>new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), 'petstore_auth': new OAuth(), } constructor(basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; } } else { if (basePathOrUsername) { this.basePath = basePathOrUsername } } } set useQuerystring(value: boolean) { this._useQuerystring = value; } set basePath(basePath: string) { this._basePath = basePath; } get basePath() { return this._basePath; } public setDefaultAuthentication(auth: Authentication) { this.authentications.default = auth; } public setApiKey(key: PetApiApiKeys, value: string) { (this.authentications as any)[PetApiApiKeys[key]].apiKey = value; } set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } /** * * @summary Add a new pet to the store * @param body Pet object that needs to be added to the store * @param {*} [options] Override http request options. */ public addPet (body: Pet, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Deletes a pet * @param petId Pet id to delete * @param apiKey * @param {*} [options] Override http request options. */ public deletePet (petId: number, apiKey?: string, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } localVarHeaderParams['api_key'] = ObjectSerializer.serialize(apiKey, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * Multiple status values can be provided with comma separated strings * @summary Finds Pets by status * @param status Status values that need to be considered for filter * @param {*} [options] Override http request options. */ public findPetsByStatus (status: Array<'available' | 'pending' | 'sold'>, options: any = {}) : Promise<{ response: http.ClientResponse; body: Array<Pet>; }> { const localVarPath = this.basePath + '/pet/findByStatus'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } if (status !== undefined) { localVarQueryParameters['status'] = ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>"); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Array<Pet>; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Array<Pet>"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @summary Finds Pets by tags * @param tags Tags to filter by * @param {*} [options] Override http request options. */ public findPetsByTags (tags: Array<string>, options: any = {}) : Promise<{ response: http.ClientResponse; body: Array<Pet>; }> { const localVarPath = this.basePath + '/pet/findByTags'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } if (tags !== undefined) { localVarQueryParameters['tags'] = ObjectSerializer.serialize(tags, "Array<string>"); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Array<Pet>; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Array<Pet>"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * Returns a single pet * @summary Find pet by ID * @param petId ID of pet to return * @param {*} [options] Override http request options. */ public getPetById (petId: number, options: any = {}) : Promise<{ response: http.ClientResponse; body: Pet; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.api_key.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Pet; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Pet"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Update an existing pet * @param body Pet object that needs to be added to the store * @param {*} [options] Override http request options. */ public updatePet (body: Pet, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Pet") }; this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Updates a pet in the store with form data * @param petId ID of pet that needs to be updated * @param name Updated name of the pet * @param status Updated status of the pet * @param {*} [options] Override http request options. */ public updatePetWithForm (petId: number, name?: string, status?: string, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; if (name !== undefined) { localVarFormParams['name'] = ObjectSerializer.serialize(name, "string"); } if (status !== undefined) { localVarFormParams['status'] = ObjectSerializer.serialize(status, "string"); } let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary uploads an image * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload * @param {*} [options] Override http request options. */ public uploadFile (petId: number, additionalMetadata?: string, file?: Buffer, options: any = {}) : Promise<{ response: http.ClientResponse; body: ApiResponse; }> { const localVarPath = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; if (additionalMetadata !== undefined) { localVarFormParams['additionalMetadata'] = ObjectSerializer.serialize(additionalMetadata, "string"); } if (file !== undefined) { localVarFormParams['file'] = file; } localVarUseFormData = true; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.petstore_auth.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: ApiResponse; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "ApiResponse"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } } export enum StoreApiApiKeys { api_key, } export class StoreApi { protected _basePath = defaultBasePath; protected defaultHeaders : any = {}; protected _useQuerystring : boolean = false; protected authentications = { 'default': <Authentication>new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), 'petstore_auth': new OAuth(), } constructor(basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; } } else { if (basePathOrUsername) { this.basePath = basePathOrUsername } } } set useQuerystring(value: boolean) { this._useQuerystring = value; } set basePath(basePath: string) { this._basePath = basePath; } get basePath() { return this._basePath; } public setDefaultAuthentication(auth: Authentication) { this.authentications.default = auth; } public setApiKey(key: StoreApiApiKeys, value: string) { (this.authentications as any)[StoreApiApiKeys[key]].apiKey = value; } set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @summary Delete purchase order by ID * @param orderId ID of the order that needs to be deleted * @param {*} [options] Override http request options. */ public deleteOrder (orderId: string, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * Returns a map of status codes to quantities * @summary Returns pet inventories by status * @param {*} [options] Override http request options. */ public getInventory (options: any = {}) : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const localVarPath = this.basePath + '/store/inventory'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.api_key.applyToRequest(localVarRequestOptions); this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @summary Find purchase order by ID * @param orderId ID of pet that needs to be fetched * @param {*} [options] Override http request options. */ public getOrderById (orderId: number, options: any = {}) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Place an order for a pet * @param body order placed for purchasing the pet * @param {*} [options] Override http request options. */ public placeOrder (body: Order, options: any = {}) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Order") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: Order; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Order"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } } export enum UserApiApiKeys { api_key, } export class UserApi { protected _basePath = defaultBasePath; protected defaultHeaders : any = {}; protected _useQuerystring : boolean = false; protected authentications = { 'default': <Authentication>new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), 'petstore_auth': new OAuth(), } constructor(basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; } } else { if (basePathOrUsername) { this.basePath = basePathOrUsername } } } set useQuerystring(value: boolean) { this._useQuerystring = value; } set basePath(basePath: string) { this._basePath = basePath; } get basePath() { return this._basePath; } public setDefaultAuthentication(auth: Authentication) { this.authentications.default = auth; } public setApiKey(key: UserApiApiKeys, value: string) { (this.authentications as any)[UserApiApiKeys[key]].apiKey = value; } set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } /** * This can only be done by the logged in user. * @summary Create user * @param body Created user object * @param {*} [options] Override http request options. */ public createUser (body: User, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Creates list of users with given input array * @param body List of user object * @param {*} [options] Override http request options. */ public createUsersWithArrayInput (body: Array<User>, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithArray'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Array<User>") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Creates list of users with given input array * @param body List of user object * @param {*} [options] Override http request options. */ public createUsersWithListInput (body: Array<User>, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithList'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Array<User>") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * This can only be done by the logged in user. * @summary Delete user * @param username The name that needs to be deleted * @param {*} [options] Override http request options. */ public deleteUser (username: string, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. * @param {*} [options] Override http request options. */ public getUserByName (username: string, options: any = {}) : Promise<{ response: http.ClientResponse; body: User; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: User; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "User"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Logs user into the system * @param username The user name for login * @param password The password for login in clear text * @param {*} [options] Override http request options. */ public loginUser (username: string, password: string, options: any = {}) : Promise<{ response: http.ClientResponse; body: string; }> { const localVarPath = this.basePath + '/user/login'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } // verify required parameter 'password' is not null or undefined if (password === null || password === undefined) { throw new Error('Required parameter password was null or undefined when calling loginUser.'); } if (username !== undefined) { localVarQueryParameters['username'] = ObjectSerializer.serialize(username, "string"); } if (password !== undefined) { localVarQueryParameters['password'] = ObjectSerializer.serialize(password, "string"); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body: string; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "string"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Logs out current logged in user session * @param {*} [options] Override http request options. */ public logoutUser (options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/logout'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * This can only be done by the logged in user. * @summary Updated user * @param username name that need to be deleted * @param body Updated user object * @param {*} [options] Override http request options. */ public updateUser (username: string, body: User, options: any = {}) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', encodeURIComponent(String(username))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updateUser.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "User") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } }
the_stack
import { ConnectionDetachedParams, ConnectionEstablishedParams, ConnectionMovedParams } from '../callbacks' import { JsPlumbInstance, jsPlumbElement } from "../core" import {UIGroup, GroupOptions, UINode} from "./group" import * as Constants from "../constants" import {PointXY, removeWithFunction, Dictionary, suggest, forEach, isString} from "@jsplumb/util" import { WILDCARD } from "@jsplumb/common" import {Connection} from "../connector/connection-impl" import {ConnectionSelection} from "../selection/connection-selection" import {SELECTOR_MANAGED_ELEMENT} from "../constants" interface GroupMemberEventParams<E> { el:jsPlumbElement<E>, group:UIGroup<E> } interface GroupMemberAddedParams<E> extends GroupMemberEventParams<E> { pos:PointXY } interface GroupMemberRemovedParams<E> extends GroupMemberEventParams<E> { targetGroup?:UIGroup<E> } export interface GroupCollapsedParams<E> { group:UIGroup<E> } export interface GroupExpandedParams<E> { group:UIGroup<E> } export interface AddGroupOptions<E> extends GroupOptions { el:E collapsed?:boolean } export class GroupManager<E> { groupMap:Dictionary<UIGroup<E>> = {} _connectionSourceMap:Dictionary<UIGroup<E>> = {} _connectionTargetMap:Dictionary<UIGroup<E>> = {} constructor(public instance:JsPlumbInstance) { instance.bind(Constants.EVENT_INTERNAL_CONNECTION, (p:ConnectionEstablishedParams<E>) => { const sourceGroup = this.getGroupFor(p.source) const targetGroup = this.getGroupFor(p.target) if (sourceGroup != null && targetGroup != null && sourceGroup === targetGroup) { this._connectionSourceMap[p.connection.id] = sourceGroup this._connectionTargetMap[p.connection.id] = sourceGroup suggest(sourceGroup.connections.internal, p.connection) } else { if (sourceGroup != null) { if ((p.target as unknown as jsPlumbElement<E>)._jsPlumbGroup === sourceGroup) { suggest(sourceGroup.connections.internal, p.connection) } else { suggest(sourceGroup.connections.source, p.connection) } this._connectionSourceMap[p.connection.id] = sourceGroup } if (targetGroup != null) { if ((p.source as unknown as jsPlumbElement<E>)._jsPlumbGroup === targetGroup) { suggest(targetGroup.connections.internal, p.connection) } else { suggest(targetGroup.connections.target, p.connection) } this._connectionTargetMap[p.connection.id] = targetGroup } } }) instance.bind(Constants.EVENT_INTERNAL_CONNECTION_DETACHED, (p:ConnectionDetachedParams<E>) => { this._cleanupDetachedConnection(p.connection) }) instance.bind(Constants.EVENT_CONNECTION_MOVED, (p:ConnectionMovedParams) => { const originalElement = p.originalEndpoint.element, originalGroup = this.getGroupFor(originalElement), newEndpoint = p.connection.endpoints[p.index], newElement = newEndpoint.element, newGroup = this.getGroupFor(newElement), connMap = p.index === 0 ? this._connectionSourceMap : this._connectionTargetMap, otherConnMap = p.index === 0 ? this._connectionTargetMap : this._connectionSourceMap // adjust group manager's map for source/target (depends on index). if (newGroup != null) { connMap[p.connection.id] = newGroup // if source === target set the same ref in the other map if (p.connection.source === p.connection.target) { otherConnMap[p.connection.id] = newGroup } } else { // otherwise if the connection's endpoint for index is no longer in a group, remove from the map. delete connMap[p.connection.id] // if source === target delete the ref in the other map. if (p.connection.source === p.connection.target) { delete otherConnMap[p.connection.id] } } if (originalGroup != null) { this._updateConnectionsForGroup(originalGroup) } if (newGroup != null) { this._updateConnectionsForGroup(newGroup) } }) } private _cleanupDetachedConnection(conn:Connection) { conn.proxies.length = 0 let group = this._connectionSourceMap[conn.id], f if (group != null) { f = (c:Connection) => { return c.id === conn.id; } removeWithFunction(group.connections.source, f) removeWithFunction(group.connections.target, f) removeWithFunction(group.connections.internal, f) delete this._connectionSourceMap[conn.id] } group = this._connectionTargetMap[conn.id] if (group != null) { f = (c:Connection) => { return c.id === conn.id; } removeWithFunction(group.connections.source, f) removeWithFunction(group.connections.target, f) removeWithFunction(group.connections.internal, f) delete this._connectionTargetMap[conn.id] } } addGroup(params:AddGroupOptions<E>) { const jel = params.el as unknown as jsPlumbElement<E> if (this.groupMap[params.id] != null) { throw new Error("cannot create Group [" + params.id + "]; a Group with that ID exists") } if (jel._isJsPlumbGroup != null) { throw new Error("cannot create Group [" + params.id + "]; the given element is already a Group") } let group:UIGroup<E> = new UIGroup(this.instance, params.el, params) this.groupMap[group.id] = group if (params.collapsed) { this.collapseGroup(group) } this.instance.manage(group.el) this.instance.addClass(group.el, Constants.CLASS_GROUP_EXPANDED) group.manager = this this._updateConnectionsForGroup(group) this.instance.fire(Constants.EVENT_GROUP_ADDED, { group:group }) return group } getGroup (groupId:string | UIGroup<E>):UIGroup<E> { let group = groupId if (isString(groupId)) { group = this.groupMap[groupId as string] if (group == null) { throw new Error("No such group [" + groupId + "]") } } return group as UIGroup<E> } getGroupFor(el:E):UIGroup<E> { let jel = el as unknown as jsPlumbElement<E> const c = this.instance.getContainer() let abort = false, g = null while (!abort) { if (jel == null || jel === c) { abort = true } else { if (jel._jsPlumbParentGroup) { g = jel._jsPlumbParentGroup abort = true } else { // TODO knows about the DOM. jel = (jel as any).parentNode } } } return g } getGroups():Array<UIGroup<E>> { const g = [] for (let key in this.groupMap) { g.push(this.groupMap[key]) } return g } removeGroup(group:string | UIGroup<E>, deleteMembers?:boolean, manipulateView?:boolean, doNotFireEvent?:boolean):Dictionary<PointXY> { let actualGroup = this.getGroup(group) this.expandGroup(actualGroup, true) // this reinstates any original connections and removes all proxies, but does not fire an event. let newPositions:Dictionary<PointXY> = {} // remove `group` from child nodes forEach(actualGroup.children,(uiNode:UINode<E>) => { const entry = this.instance.getManagedElements()[this.instance.getId(uiNode.el)] if (entry) { delete entry.group } }) if (deleteMembers) { // remove all child groups forEach(actualGroup.getGroups(), (cg:UIGroup<E>) => this.removeGroup(cg, deleteMembers, manipulateView)) // remove all child nodes actualGroup.removeAll(manipulateView, doNotFireEvent) } else { // if we want to retain the child nodes then we need to test if there is a group that the parent of actualGroup. // if so, transfer the nodes to that group if (actualGroup.group) { forEach(actualGroup.children, (c:UINode<E>) => actualGroup.group.add(c.el)) } newPositions = actualGroup.orphanAll() } if (actualGroup.group) { actualGroup.group.removeGroup(actualGroup) } this.instance.unmanage(actualGroup.el, true) delete this.groupMap[actualGroup.id] this.instance.fire(Constants.EVENT_GROUP_REMOVED, { group:actualGroup }) return newPositions; // this will be null in the case of remove, but be a map of {id->[x,y]} in the case of orphan } removeAllGroups (deleteMembers?:boolean, manipulateView?:boolean, doNotFireEvent?:boolean):void { for (let g in this.groupMap) { this.removeGroup(this.groupMap[g], deleteMembers, manipulateView, doNotFireEvent) } } forEach(f:(g:UIGroup<E>) => any):void { for (let key in this.groupMap) { f(this.groupMap[key]) } } // it would be nice to type `_el` as an element here, but the type of the element is currently specified by the // concrete implementation of jsplumb (of which there is 'DOM', a browser implementation, at the moment.) orphan(el:E, doNotTransferToAncestor:boolean):{id:string, pos:PointXY} { const jel = el as unknown as jsPlumbElement<E> if (jel._jsPlumbParentGroup) { const currentParent = jel._jsPlumbParentGroup const positionRelativeToGroup = this.instance.getOffset(jel) const id = this.instance.getId(jel) const pos = this.instance.getOffset(el); (jel as any).parentNode.removeChild(jel) if (doNotTransferToAncestor !== true && currentParent.group) { // if the current parent is itself a nested group, add the orphaned element to the parent group. This is not // necessarily correct when the node is being orphaned as a result of a drag, since the node may not in fact // be a child of any of the parents, and in that case the `doNotTransferToAncestor` will be set. pos.x += positionRelativeToGroup.x pos.y += positionRelativeToGroup.y this.instance.getGroupContentArea(currentParent.group).appendChild(el) } else { this.instance._appendElement(el, this.instance.getContainer()) // set back as child of container } this.instance.setPosition(el, pos) delete jel._jsPlumbParentGroup return {id, pos} } } _updateConnectionsForGroup(group:UIGroup<E>) { group.connections.source.length = 0 group.connections.target.length = 0 group.connections.internal.length = 0 // get all direct members, and any of their descendants. const members:Array<E> = group.children.slice().map(cn => cn.el) const childMembers:Array<E> = [] forEach(members,(member: E) => { Array.prototype.push.apply(childMembers, this.instance.getSelector(member, SELECTOR_MANAGED_ELEMENT)) }) Array.prototype.push.apply(members, childMembers) if (members.length > 0) { const c1 = this.instance.getConnections({ source: members, scope: WILDCARD }, true) as Array<Connection> const c2 = this.instance.getConnections({ target: members, scope: WILDCARD }, true) as Array<Connection> const processed = {} let gs, gt const oneSet = (c: Array<Connection>) => { for (let i = 0; i < c.length; i++) { if (processed[c[i].id]) { continue } processed[c[i].id] = true gs = this.getGroupFor(c[i].source) gt = this.getGroupFor(c[i].target) if ( (c[i].source === group.el && gt === group) || (c[i].target === group.el && gs === group) ) { group.connections.internal.push(c[i]) } else if (gs === group) { if (gt !== group) { group.connections.source.push(c[i]) } else { group.connections.internal.push(c[i]) } this._connectionSourceMap[c[i].id] = group } else if (gt === group) { group.connections.target.push(c[i]) this._connectionTargetMap[c[i].id] = group } } } oneSet(c1) oneSet(c2) } } private _collapseConnection(conn:Connection, index:number, group:UIGroup<E>):boolean { let otherEl = conn.endpoints[index === 0 ? 1 : 0].element if (otherEl._jsPlumbParentGroup && (!otherEl._jsPlumbParentGroup.proxied && otherEl._jsPlumbParentGroup.collapsed)) { return false } const es = conn.endpoints[0].element, esg = es._jsPlumbParentGroup, esgcp = esg != null ? (esg.collapseParent || esg) : null, et = conn.endpoints[1].element, etg = et._jsPlumbParentGroup, etgcp = etg != null ? (etg.collapseParent || etg) : null if (esgcp == null || etgcp == null || (esgcp.id !== etgcp.id)) { let groupEl = group.el, groupElId = this.instance.getId(groupEl) this.instance.proxyConnection(conn, index, groupEl, /*groupElId, */(conn:Connection, index:number) => { return group.getEndpoint(conn, index); }, (conn:Connection, index:number) => { return group.getAnchor(conn, index); }) return true } else { return false } } private _expandConnection(c:Connection, index:number, group:UIGroup<E>) { this.instance.unproxyConnection(c, index) } private isElementDescendant(el:any, parentEl:any): boolean { const c = this.instance.getContainer() let abort = false while (!abort) { if (el == null || el === c) { return false } else { if (el === parentEl) { return true } else { el = (el as any).parentNode; // TODO DOM specific. } } } } collapseGroup (group:string | UIGroup<E>) { let actualGroup = this.getGroup(group) if (actualGroup == null || actualGroup.collapsed) { return } let groupEl = actualGroup.el // is this group a descendant of some other group that is currently collapsed? if (actualGroup.collapseParent == null) { // if it isn't, we go through the process of proxying connections // first hide all connections this.instance.setGroupVisible(actualGroup, false) actualGroup.collapsed = true this.instance.removeClass(groupEl, Constants.CLASS_GROUP_EXPANDED) this.instance.addClass(groupEl, Constants.CLASS_GROUP_COLLAPSED) // if this group, when collapsed, should have its connections proxied (which is the default behaviour): if (actualGroup.proxied) { const collapsedConnectionIds = new Set<string>() // collapses all connections in a group. const _collapseSet = (conns: Array<Connection>, index: number) => { for (let i = 0; i < conns.length; i++) { let c = conns[i] if (this._collapseConnection(c, index, actualGroup) === true) { collapsedConnectionIds.add(c.id) } } } // setup proxies for sources and targets. note: internal connections are not proxied, and at this point have // been hidden. _collapseSet(actualGroup.connections.source, 0) _collapseSet(actualGroup.connections.target, 1) // cascade the collapse down to child groups forEach(actualGroup.getGroups(),(cg: UIGroup<E>) => { this.cascadeCollapse(actualGroup, cg, collapsedConnectionIds) }) } this.instance.revalidate(groupEl) this.repaintGroup(actualGroup) this.instance.fire<GroupCollapsedParams<E>>(Constants.EVENT_GROUP_COLLAPSE, { group:actualGroup }) } else { // if this group is a descendant of some other group that is already collapsed, then visually this group is // also collapsed, so we just set the `collapsed` flag and change the css classes, without altering any of the // group's connections. actualGroup.collapsed = true this.instance.removeClass(groupEl, Constants.CLASS_GROUP_EXPANDED) this.instance.addClass(groupEl, Constants.CLASS_GROUP_COLLAPSED) } } /** * Cascade a collapse from the given `collapsedGroup` into the given `targetGroup`. * @param collapsedGroup * @param targetGroup * @param collapsedIds Set of connection ids for already collapsed connections, which we can ignore. */ cascadeCollapse(collapsedGroup:UIGroup<E>, targetGroup:UIGroup<E>, collapsedIds:Set<string>) { if (collapsedGroup.proxied) { // collapses all connections in a group. const _collapseSet = (conns:Array<Connection>, index:number) => { for (let i = 0; i < conns.length; i++) { let c = conns[i] if (!collapsedIds.has(c.id)) { if (this._collapseConnection(c, index, collapsedGroup) === true) { collapsedIds.add(c.id) } } } } // setup proxies for sources and targets _collapseSet(targetGroup.connections.source, 0) _collapseSet(targetGroup.connections.target, 1) } forEach(targetGroup.getGroups(),(cg:UIGroup<E>) => { this.cascadeCollapse(collapsedGroup, cg, collapsedIds) }) } expandGroup(group:string | UIGroup<E>, doNotFireEvent?:boolean) { let actualGroup = this.getGroup(group) if (actualGroup == null) { return } const groupEl = actualGroup.el // is this group inside an ancestor group that is currently collapsed? if (actualGroup.collapseParent == null) { // ...if it is not, unproxy connections for this group. this.instance.setGroupVisible(actualGroup, true) actualGroup.collapsed = false this.instance.addClass(groupEl, Constants.CLASS_GROUP_EXPANDED) this.instance.removeClass(groupEl, Constants.CLASS_GROUP_COLLAPSED) if (actualGroup.proxied) { // expands all connections in a group. const _expandSet = (conns: Array<Connection>, index: number) => { for (let i = 0; i < conns.length; i++) { let c = conns[i] this._expandConnection(c, index, actualGroup) } } // discard proxies for sources and targets (internal connections are ignored, they've already been made visible and // were never proxied. _expandSet(actualGroup.connections.source, 0) _expandSet(actualGroup.connections.target, 1) const _expandNestedGroup = (group:UIGroup<E>, ignoreCollapsedStateForNested?:boolean) => { // if the group is collapsed: // - all of its internal connections should remain hidden. // - all external connections should be proxied to this group we are expanding (`actualGroup`) // otherwise: // just expend it as usual if (ignoreCollapsedStateForNested || group.collapsed) { const _collapseSet = (conns:Array<Connection>, index:number) => { for (let i = 0; i < conns.length; i++) { let c = conns[i] this._collapseConnection(c, index, group.collapseParent || group) } } // setup proxies for sources and targets _collapseSet(group.connections.source, 0) _collapseSet(group.connections.target, 1) // hide internal connections - the group is collapsed forEach(group.connections.internal,(c:Connection) => c.setVisible(false)) // collapse child groups forEach(group.getGroups(), (g) => _expandNestedGroup(g, true)) } else { this.expandGroup(group, true) } } //expand any nested groups. this will take into account if the nested group is collapsed. forEach(actualGroup.getGroups(), _expandNestedGroup) } this.instance.revalidate(groupEl) this.repaintGroup(actualGroup) if (!doNotFireEvent) { this.instance.fire<GroupExpandedParams<E>>(Constants.EVENT_GROUP_EXPAND, {group: actualGroup}) } } else { // if this group is a descendant of some collapsed group, just change the `collapsed` flag and // css classes on the group's element. actualGroup.collapsed = false this.instance.addClass(groupEl, Constants.CLASS_GROUP_EXPANDED) this.instance.removeClass(groupEl, Constants.CLASS_GROUP_COLLAPSED) } } toggleGroup(group:string|UIGroup<E>) { group = this.getGroup(group) if (group != null) { if (group.collapsed) { this.expandGroup(group) } else { this.collapseGroup(group) } } } repaintGroup (group:string|UIGroup<E>) { let actualGroup = this.getGroup(group) const m = actualGroup.children for (let i = 0; i < m.length; i++) { this.instance.revalidate(m[i].el) } } addToGroup(group:string | UIGroup<E>, doNotFireEvent:boolean, ...el:Array<E>) { let actualGroup = this.getGroup(group) if (actualGroup) { let groupEl = actualGroup.el const _one = (el:E) => { const jel = el as unknown as jsPlumbElement<E> let isGroup = jel._isJsPlumbGroup != null, droppingGroup = jel._jsPlumbGroup let currentGroup = jel._jsPlumbParentGroup // if already a member of this group, do nothing if (currentGroup !== actualGroup) { const entry = this.instance.manage(el) const elpos = this.instance.getOffset(el) const cpos = actualGroup.collapsed ? this.instance.getOffsetRelativeToRoot(groupEl) : this.instance.getOffset(this.instance.getGroupContentArea(actualGroup)) entry.group = actualGroup.elId // otherwise, transfer to this group. if (currentGroup != null) { currentGroup.remove(el, false, doNotFireEvent, false, actualGroup) this._updateConnectionsForGroup(currentGroup) } if (isGroup) { actualGroup.addGroup(droppingGroup) } else { actualGroup.add(el, doNotFireEvent) } const handleDroppedConnections = (list:ConnectionSelection, index:number) => { const oidx = index === 0 ? 1 : 0 list.each( (c:Connection) => { c.setVisible(false) if (c.endpoints[oidx].element._jsPlumbGroup === actualGroup) { c.endpoints[oidx].setVisible(false) this._expandConnection(c, oidx, actualGroup) } else { c.endpoints[index].setVisible(false) this._collapseConnection(c, index, actualGroup) } }) } if (actualGroup.collapsed) { handleDroppedConnections(this.instance.select({source: el}), 0) handleDroppedConnections(this.instance.select({target: el}), 1) } let elId = this.instance.getId(el) let newPosition = { x: elpos.x - cpos.x, y: elpos.y - cpos.y } this.instance.setPosition(el, newPosition) this._updateConnectionsForGroup(actualGroup) this.instance.revalidate(el) if (!doNotFireEvent) { // TODO fire a "child group added" event in that case? let p = {group: actualGroup, el: el, pos:newPosition} if (currentGroup) { (<any>p).sourceGroup = currentGroup } this.instance.fire(Constants.EVENT_GROUP_MEMBER_ADDED, p) } } } forEach(el, _one) } } removeFromGroup (group:string | UIGroup<E>, doNotFireEvent:boolean, ...el:Array<E>):void { let actualGroup = this.getGroup(group) if (actualGroup) { const _one = (_el:E) => { // if this group is currently collapsed then any proxied connections for the given el (or its descendants) need // to be put back on their original element, and unproxied if (actualGroup.collapsed) { const _expandSet = (conns: Array<Connection>, index: number) => { for (let i = 0; i < conns.length; i++) { const c = conns[i] if (c.proxies) { for (let j = 0; j < c.proxies.length; j++) { if (c.proxies[j] != null) { const proxiedElement = c.proxies[j].originalEp.element if (proxiedElement === _el || this.isElementDescendant(proxiedElement, _el)) { this._expandConnection(c, index, actualGroup) } } } } } } // setup proxies for sources and targets _expandSet(actualGroup.connections.source.slice(), 0) _expandSet(actualGroup.connections.target.slice(), 1) } actualGroup.remove(_el, null, doNotFireEvent) const entry = this.instance.getManagedElements()[this.instance.getId(_el)] if (entry) { delete entry.group } }; forEach(el, _one) } } getAncestors(group:UIGroup<E>):Array<UIGroup<E>> { const ancestors:Array<UIGroup<E>> = [] let p = group.group while (p != null) { ancestors.push(p) p = p.group } return ancestors } /** * Tests if `possibleAncestor` is in fact an ancestor of `group` * @param group * @param possibleAncestor */ isAncestor(group:UIGroup<E>, possibleAncestor:UIGroup<E>):boolean { if (group == null || possibleAncestor == null) { return false } return this.getAncestors(group).indexOf(possibleAncestor) !== -1 } getDescendants(group:UIGroup<E>):Array<UIGroup<E>> { const d:Array<UIGroup<E>> = [] const _one = (g:UIGroup<E>) => { const childGroups = g.getGroups() d.push(...childGroups) forEach(childGroups, _one) } _one(group) return d } isDescendant(possibleDescendant:UIGroup<E>, ancestor:UIGroup<E>):boolean { if (possibleDescendant == null || ancestor == null) { return false } return this.getDescendants(ancestor).indexOf(possibleDescendant) !== -1 } reset() { this._connectionSourceMap = {} this._connectionTargetMap = {} this.groupMap = {} } }
the_stack
import { action } from "../common"; import { ProviderPullRequestActionsTypes } from "./types"; import { logError } from "@codestream/webview/logger"; import { HostApi } from "@codestream/webview/webview-api"; import { FetchThirdPartyPullRequestRequestType, FetchThirdPartyPullRequestResponse, ExecuteThirdPartyTypedType, ExecuteThirdPartyTypedRequest, GetMyPullRequestsRequest, GetMyPullRequestsResponse, FetchThirdPartyPullRequestCommitsType, QueryThirdPartyRequestType, ExecuteThirdPartyRequestUntypedType, FetchAssignableUsersRequestType, FetchAssignableUsersResponse, GetCommitsFilesRequestType, GetCommitsFilesResponse } from "@codestream/protocols/agent"; import { CodeStreamState } from ".."; import { RequestType } from "vscode-languageserver-protocol"; import { setCurrentPullRequest, setCurrentPullRequestAndBranch, setCurrentReview } from "../context/actions"; import { getPullRequestExactId, isAnHourOld } from "./reducer"; export const reset = () => action("RESET"); export const _addPullRequestConversations = (providerId: string, id: string, pullRequest: any) => action(ProviderPullRequestActionsTypes.AddPullRequestConversations, { providerId, id, pullRequest }); export const _addPullRequestCollaborators = (providerId: string, id: string, collaborators: any) => action(ProviderPullRequestActionsTypes.AddPullRequestCollaborators, { providerId, id, collaborators }); export const updatePullRequestTitle = (providerId: string, id: string, pullRequestData: any) => action(ProviderPullRequestActionsTypes.UpdatePullRequestTitle, { providerId, id, pullRequestData }); export const _updatePullRequestFilter = (providerId: string, data: any, index: any) => action(ProviderPullRequestActionsTypes.UpdatePullRequestFilter, { providerId, data, index }); export const _addPullRequestFiles = ( providerId: string, id: string, commits: string, pullRequestFiles: any, accessRawDiffs?: boolean ) => action(ProviderPullRequestActionsTypes.AddPullRequestFiles, { providerId, id, commits, pullRequestFiles, accessRawDiffs }); export const _addPullRequestCommits = (providerId: string, id: string, pullRequestCommits: any) => action(ProviderPullRequestActionsTypes.AddPullRequestCommits, { providerId, id, pullRequestCommits }); export const _addMyPullRequests = (providerId: string, data: any) => action(ProviderPullRequestActionsTypes.AddMyPullRequests, { providerId, data }); export const _addPullRequestError = (providerId: string, id: string, error?: { message: string }) => action(ProviderPullRequestActionsTypes.AddPullRequestError, { providerId, id, error }); export const clearPullRequestError = (providerId: string, id: string) => action(ProviderPullRequestActionsTypes.ClearPullRequestError, { providerId, id, undefined }); export const handleDirectives = (providerId: string, id: string, data: any) => action(ProviderPullRequestActionsTypes.HandleDirectives, { providerId, id, data }); const _getPullRequestConversationsFromProvider = async ( providerId: string, id: string, src: string ) => { const response1 = await HostApi.instance.send(FetchThirdPartyPullRequestRequestType, { providerId: providerId, pullRequestId: id, src: src, force: true }); let response2: FetchAssignableUsersResponse | undefined = undefined; let boardId; if ( response1 && response1.repository && response1.repository.repoOwner && response1.repository.repoName ) { boardId = `${response1.repository.repoOwner}/${response1.repository.repoName}`; } else if ( response1 && (response1 as any).project && (response1 as any).project.mergeRequest && (response1 as any).project.mergeRequest.repository.nameWithOwner ) { // gitlab requires this to be encoded boardId = encodeURIComponent((response1 as any).project.mergeRequest.repository.nameWithOwner); } if (boardId) { response2 = await HostApi.instance.send(FetchAssignableUsersRequestType, { providerId: providerId, boardId: boardId }); } return { conversations: response1, collaborators: response2 && response2.users && response2.users.length ? response2.users.map(_ => { return { id: _.id, username: _.displayName, avatar: { image: _.avatarUrl } }; }) : [] }; }; export const getPullRequestConversationsFromProvider = ( providerId: string, id: string ) => async dispatch => { try { dispatch(clearPullRequestError(providerId, id)); const responses = await _getPullRequestConversationsFromProvider( providerId, id, "getPullRequestConversationsFromProvider" ); dispatch(_addPullRequestConversations(providerId, id, responses.conversations)); dispatch(_addPullRequestCollaborators(providerId, id, responses.collaborators)); return responses.conversations as FetchThirdPartyPullRequestResponse; } catch (error) { logError(`failed to refresh pullRequest: ${error}`, { providerId, id }); } return undefined; }; export const getPullRequestConversations = (providerId: string, id: string) => async ( dispatch, getState: () => CodeStreamState ) => { try { const state = getState(); const provider = state.providerPullRequests.pullRequests[providerId]; if (provider) { const pr = provider[id]; if (pr && pr.conversations) { if (isAnHourOld(pr.conversationsLastFetch)) { console.warn( `stale pullRequest conversations from store providerId=${providerId} id=${id}, re-fetching...` ); } else { console.log( `fetched pullRequest conversations from store providerId=${providerId} id=${id}` ); return pr.conversations; } } } const responses = await _getPullRequestConversationsFromProvider( providerId, id, "getPullRequestConversations" ); await dispatch(_addPullRequestConversations(providerId, id, responses.conversations)); await dispatch(_addPullRequestCollaborators(providerId, id, responses.collaborators)); return responses.conversations; } catch (error) { logError(`failed to get pullRequest conversations: ${error}`, { providerId, id }); return { error }; } }; /** * This resets the provider's files changed list * @param providerId * @param id */ export const clearPullRequestFiles = (providerId: string, id: string) => action(ProviderPullRequestActionsTypes.ClearPullRequestFiles, { providerId, id }); export const getPullRequestFiles = ( providerId: string, id: string, commits: string[] = [], repoId?: string, accessRawDiffs?: boolean ) => async (dispatch, getState: () => CodeStreamState) => { try { const state = getState(); const provider = state.providerPullRequests.pullRequests[providerId]; const commitsIndex = JSON.stringify(commits); let exactId = getPullRequestExactId(state); if (provider) { const pr = provider[exactId]; if ( pr && pr.files && pr.files[commitsIndex] && pr.files[commitsIndex].length && (pr.accessRawDiffs || !accessRawDiffs) ) { console.log(`fetched pullRequest files from store providerId=${providerId} id=${exactId}`); return pr.files[commitsIndex]; } } let response: GetCommitsFilesResponse[]; if (repoId && commits.length > 0) { response = await HostApi.instance.send(GetCommitsFilesRequestType, { repoId, commits }); } else { response = await dispatch( api("getPullRequestFilesChanged", { pullRequestId: id, accessRawDiffs }) ); } dispatch(_addPullRequestFiles(providerId, id, commitsIndex, response, accessRawDiffs)); return response; } catch (error) { logError(`failed to get pullRequest files: ${error}`, { providerId, id }); } return undefined; }; export const getPullRequestFilesFromProvider = ( providerId: string, id: string ) => async dispatch => { try { const response = await dispatch( api("getPullRequestFilesChanged", { pullRequestId: id }) ); // JSON.stringify matches the other use of this call dispatch(_addPullRequestFiles(providerId, id, JSON.stringify([]), response, undefined)); return response; } catch (error) { logError(`failed to get pullRequest files from provider: ${error}`, { providerId, id }); } return undefined; }; export const getMyPullRequests = ( providerId: string, queries: string[], openReposOnly: boolean, options?: { force?: boolean }, throwOnError?: boolean, test?: boolean, index?: Number ) => async (dispatch, getState: () => CodeStreamState) => { try { let force = false; if (!options || !options.force) { const state = getState(); const provider = state.providerPullRequests.myPullRequests[providerId]; if (provider && provider.data != null) { console.log(`fetched myPullRequest data from store providerId=${providerId}`); return provider.data; } // if the data was wiped... set force to get data from the provider api and // bypass our cache force = true; } const request = new RequestType< ExecuteThirdPartyTypedRequest<GetMyPullRequestsRequest>, GetMyPullRequestsResponse, any, any >("codestream/provider/generic"); const response = await HostApi.instance.send(request, { method: "getMyPullRequests", providerId: providerId, params: { queries, isOpen: openReposOnly, force: force || (options && options.force) } }); if (index !== undefined) { dispatch(_updatePullRequestFilter(providerId, response, index)); } else if (!test) dispatch(_addMyPullRequests(providerId, response)); return response; } catch (error) { if (throwOnError) { throw error; } // callee is handling, let them handle any logging logError(`failed to get my pullRequests: ${error}`, { providerId }); } return undefined; }; export const clearPullRequestCommits = (providerId: string, id: string) => action(ProviderPullRequestActionsTypes.ClearPullRequestCommits, { providerId, id }); export const getPullRequestCommitsFromProvider = ( providerId: string, id: string ) => async dispatch => { try { const response = await HostApi.instance.send(FetchThirdPartyPullRequestCommitsType, { providerId, pullRequestId: id }); dispatch(_addPullRequestCommits(providerId, id, response)); return response; } catch (error) { logError(`failed to refresh pullRequest commits: ${error}`, { providerId, id }); } return undefined; }; export const getPullRequestCommits = ( providerId: string, id: string, options?: { force: true } ) => async (dispatch, getState: () => CodeStreamState) => { try { const state = getState(); const provider = state.providerPullRequests.pullRequests[providerId]; if (options?.force) { console.log(`fetching new pullRequest commits from store providerId=${providerId}`); } else if (provider) { const exactId = getPullRequestExactId(state); const pr = provider[exactId]; if (pr && pr.commits && pr.commits.length) { console.log( `fetched pullRequest commits from store providerId=${providerId} id=${exactId}` ); return pr.commits; } } const response = await HostApi.instance.send(FetchThirdPartyPullRequestCommitsType, { providerId: providerId, pullRequestId: id }); dispatch(_addPullRequestCommits(providerId, id, response)); return response; } catch (error) { logError(`failed to get pullRequest commits: ${error}`, { providerId, id }); } return undefined; }; export const openPullRequestByUrl = ( url: string, options?: { source?: string; checkoutBranch?: any; } ) => async (dispatch, getState: () => CodeStreamState) => { let handled = false; let response; let providerInfo; try { providerInfo = await HostApi.instance.send(QueryThirdPartyRequestType, { url: url }); } catch (error) {} try { if (providerInfo && providerInfo.providerId) { const id = await HostApi.instance.send(ExecuteThirdPartyRequestUntypedType, { method: "getPullRequestIdFromUrl", providerId: providerInfo.providerId, params: { url } }); if (id) { dispatch(setCurrentReview("")); if (options && options.checkoutBranch) dispatch(setCurrentPullRequestAndBranch(id as string)); dispatch( setCurrentPullRequest( providerInfo.providerId, id as string, "", options ? options.source : undefined ) ); handled = true; } } } catch (error) { logError(`failed to openPullRequestByUrl: ${error}`, { url }); let errorString = typeof error === "string" ? error : error.message; if (errorString) { const target = "failed with message: "; const targetLength = target.length; const index = errorString.indexOf(target); if (index > -1) { errorString = errorString.substring(index + targetLength); } } return { error: errorString }; } if (!handled) { response = { error: "Unable to view PR" }; } return response; }; export const setProviderError = ( providerId: string, id: string, error?: { message: string } ) => async (dispatch, getState: () => CodeStreamState) => { try { dispatch(_addPullRequestError(providerId, id, error)); } catch (error) { logError(`failed to setProviderError: ${error}`, { providerId, id }); } }; export const clearProviderError = ( providerId: string, id: string, error?: { message: string } ) => async (dispatch, getState: () => CodeStreamState) => { try { dispatch(_addPullRequestError(providerId, id, error)); } catch (error) { logError(`failed to setProviderError: ${error}`, { providerId, id }); } }; /** * Provider api * * @param method the method in the agent * @param params the data to send to the provider * @param options optional options */ export const api = <T = any, R = any>( method: | "addReviewerToPullRequest" | "cancelMergeWhenPipelineSucceeds" | "createCommentReply" | "createPullRequestComment" | "createPullRequestCommentAndClose" | "createPullRequestCommentAndReopen" | "createPullRequestThread" | "createPullRequestInlineComment" | "createPullRequestInlineReviewComment" | "createToDo" | "deletePullRequest" | "deletePullRequestComment" | "deletePullRequestReview" | "getIssues" | "getLabels" | "getMilestones" | "getPullRequestFilesChanged" | "getPullRequestLastUpdated" | "getProjects" | "getReviewers" | "lockPullRequest" | "markPullRequestReadyForReview" | "markToDoDone" | "mergePullRequest" | "remoteBranches" | "removeReviewerFromPullRequest" | "resolveReviewThread" | "setAssigneeOnPullRequest" | "setIssueOnPullRequest" | "setLabelOnPullRequest" | "setReviewersOnPullRequest" | "setWorkInProgressOnPullRequest" | "submitReview" | "toggleReaction" | "toggleMilestoneOnPullRequest" | "toggleProjectOnPullRequest" | "togglePullRequestApproval" | "unresolveReviewThread" | "updateIssueComment" | "unlockPullRequest" | "updatePullRequest" | "updatePullRequestBody" | "updatePullRequestSubscription" | "updatePullRequestTitle" | "updateReview" | "updateReviewComment", params: any, options?: { updateOnSuccess?: boolean; preventClearError: boolean; preventErrorReporting?: boolean; } ) => async (dispatch, getState: () => CodeStreamState) => { let providerId; let pullRequestId; try { const state = getState(); const currentPullRequest = state.context.currentPullRequest; if (!currentPullRequest) { dispatch( setProviderError(providerId, pullRequestId, { message: "currentPullRequest not found" }) ); return; } ({ providerId, id: pullRequestId } = currentPullRequest); params = params || {}; if (!params.pullRequestId) params.pullRequestId = pullRequestId; if (currentPullRequest.metadata) { params = { ...params, ...currentPullRequest.metadata }; params.metadata = currentPullRequest.metadata; } const response = (await HostApi.instance.send(new ExecuteThirdPartyTypedType<T, R>(), { method: method, providerId: providerId, params: params })) as any; if (response && (!options || (options && !options.preventClearError))) { dispatch(clearPullRequestError(providerId, pullRequestId)); } if (response && response.directives) { dispatch(handleDirectives(providerId, pullRequestId, response.directives)); return { handled: true }; } return response as R; } catch (error) { let errorString = typeof error === "string" ? error : error.message; if (errorString) { if ( options && options.preventErrorReporting && (errorString.indexOf("ENOTFOUND") > -1 || errorString.indexOf("ETIMEDOUT") > -1 || errorString.indexOf("EAI_AGAIN") > -1 || errorString.indexOf("ECONNRESET") > -1 || errorString.indexOf("ENETDOWN") > -1 || errorString.indexOf("socket disconnected before secure") > -1) ) { // ignores calls where the user might be offline console.error(error); return undefined; } const target = "failed with message: "; const targetLength = target.length; const index = errorString.indexOf(target); if (index > -1) { errorString = errorString.substring(index + targetLength); const jsonIndex = errorString.indexOf(`: {\"`); // not the first character if (jsonIndex > 0) { errorString = errorString.substring(0, jsonIndex); } } } dispatch( setProviderError(providerId, pullRequestId, { message: errorString }) ); logError(error, { providerId, pullRequestId, method, message: errorString }); HostApi.instance.track("PR Error", { Host: providerId, Operation: method, Error: errorString, IsOAuthError: errorString && errorString.indexOf("OAuth App access restrictions") > -1 }); return undefined; } };
the_stack
import { stub, match, SinonStub, fake, replace } from 'sinon' import { random, lorem, internet } from 'faker' import { Logger, GraphQLRequestEnvelope, GraphQLStart, GraphQLStop, MessageTypes, BoosterConfig, ProviderConnectionsLibrary, GraphQLRequestEnvelopeError, UserEnvelope, ConnectionDataEnvelope, } from '@boostercloud/framework-types' import { GraphQLWebsocketHandler } from '../../../../src/services/graphql/websocket-protocol/graphql-websocket-protocol' import { ExecutionResult } from 'graphql' import { expect } from '../../../expect' import { BoosterTokenVerifier } from '../../../../src/booster-token-verifier' describe('the `GraphQLWebsocketHandler`', () => { let config: BoosterConfig let websocketHandler: GraphQLWebsocketHandler let connectionsManager: ProviderConnectionsLibrary let onStartCallback: ( envelope: GraphQLRequestEnvelope ) => Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult> let onStopCallback: (connectionID: string, messageID: string) => Promise<void> let onTerminateCallback: (connectionID: string) => Promise<void> let logger: Logger let envelope: GraphQLRequestEnvelope let boosterTokenVerifier: BoosterTokenVerifier beforeEach(() => { config = new BoosterConfig('test') boosterTokenVerifier = new BoosterTokenVerifier(config) connectionsManager = { sendMessage: stub(), deleteData: stub(), fetchData: stub(), storeData: stub(), } onStartCallback = stub() onStopCallback = stub() onTerminateCallback = stub() logger = console websocketHandler = new GraphQLWebsocketHandler( config, logger, connectionsManager, { onStartOperation: onStartCallback, onStopOperation: onStopCallback, onTerminate: onTerminateCallback, }, boosterTokenVerifier ) envelope = { currentUser: undefined, eventType: 'MESSAGE', requestID: random.alphaNumeric(10), } }) describe('the "handle" method', () => { let resultPromise: Promise<void> | undefined beforeEach(() => { resultPromise = undefined }) afterEach(async () => { // The handle method must never fail, just log or send the error to the connection ID. // We ensure here that the returned promise from the method is always fulfilled expect(resultPromise, "The test didn't set the 'resultPromise' variable with the result of 'handle' method").not .to.be.undefined await expect(resultPromise).to.eventually.be.fulfilled }) describe('with an envelope with no connectionID', () => { beforeEach(() => { envelope.connectionID = undefined }) it('just logs an error', async () => { logger.error = stub() resultPromise = websocketHandler.handle(envelope) await resultPromise expect(logger.error).to.be.calledOnceWithExactly('Missing websocket connectionID') }) }) describe('with an envelope with connectionID', () => { beforeEach(() => { envelope.connectionID = random.alphaNumeric(10) }) describe('with an error in the envelope', () => { const errorMessage = lorem.sentences(1) let envelopeWithError: GraphQLRequestEnvelopeError beforeEach(() => { envelopeWithError = { ...envelope, error: new Error(errorMessage), } }) it('sends the error to the client', async () => { resultPromise = websocketHandler.handle(envelopeWithError) await resultPromise expect(connectionsManager.sendMessage).to.be.calledOnceWithExactly( config, envelopeWithError.connectionID, match({ type: MessageTypes.GQL_CONNECTION_ERROR, payload: errorMessage, }) ) }) }) describe('with an empty value', () => { beforeEach(() => { envelope.value = undefined }) it('sends the right error', async () => { resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ type: MessageTypes.GQL_CONNECTION_ERROR, payload: 'Received an empty GraphQL body', }) ) }) }) describe('with a value with GQL_CONNECTION_INIT message', () => { beforeEach(() => { envelope.value = { type: MessageTypes.GQL_CONNECTION_INIT, payload: {}, } }) it('sends back a GQL_CONNECTION_ACK', async () => { resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ type: MessageTypes.GQL_CONNECTION_ACK }) ) }) it('stores connection data', async () => { resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.storeData).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ user: undefined, expirationTime: match.number, }) ) }) describe('with an access token', () => { beforeEach(() => { envelope.value = { type: MessageTypes.GQL_CONNECTION_INIT, payload: { Authorization: random.uuid(), }, } }) it('stores connection data including the user', async () => { const expectedUser: UserEnvelope = { username: internet.email(), role: lorem.word(), claims: {}, } const fakeVerifier = fake.returns(expectedUser) replace(boosterTokenVerifier, 'verify', fakeVerifier) resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.storeData).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ user: expectedUser, expirationTime: match.number, }) ) }) }) }) describe('with a value with GQL_START message', () => { beforeEach(() => { envelope.value = { id: random.alphaNumeric(10), type: MessageTypes.GQL_START, payload: { query: random.alphaNumeric(20), variables: { aField: random.alphaNumeric(5) }, operationName: random.alphaNumeric(10), }, } }) it('fails if there is no "id"', async () => { const value = envelope.value as GraphQLStart value.id = undefined as any // Force "id" to be undefined resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ type: MessageTypes.GQL_CONNECTION_ERROR, payload: `Missing "id" in ${MessageTypes.GQL_START} message`, }) ) }) it('fails if there is no "payload"', async () => { const value = envelope.value as GraphQLStart value.payload = undefined as any resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ type: MessageTypes.GQL_ERROR, id: value.id, payload: { errors: match.some( match.has('message', 'Message payload is invalid it must contain at least the "query" property') ), }, }) ) }) it('fails if there is no "query"', async () => { const message = envelope.value as GraphQLStart message.payload.query = undefined as any resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ type: MessageTypes.GQL_ERROR, id: message.id, payload: { errors: match.some( match.has('message', 'Message payload is invalid it must contain at least the "query" property') ), }, }) ) }) it('calls "onStartOperation" with the right parameters', async () => { const message = envelope.value as GraphQLStart const connectionData: ConnectionDataEnvelope = { user: { username: internet.email(), role: lorem.word(), claims: {}, }, expirationTime: random.number(), } const fetchDataFake: SinonStub = connectionsManager.fetchData as any fetchDataFake.withArgs(config, envelope.connectionID).returns(connectionData) resultPromise = websocketHandler.handle(envelope) await resultPromise expect(onStartCallback).to.be.calledOnceWithExactly({ ...envelope, currentUser: connectionData.user, value: { ...message.payload, id: message.id, }, }) }) context('when "onStartOperation" returns the result of a subscription', () => { beforeEach(() => { onStartCallback = stub().returns({ next: () => {} }) websocketHandler = new GraphQLWebsocketHandler( config, logger, connectionsManager, { onStartOperation: onStartCallback, onStopOperation: undefined as any, onTerminate: undefined as any, }, boosterTokenVerifier ) }) it('does not send anything back', async () => { resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).not.to.be.called }) }) context('when "onStartOperation" returns the result of a query or mutation', () => { const result = { data: 'The result', } beforeEach(() => { onStartCallback = stub().returns(result) websocketHandler = new GraphQLWebsocketHandler( config, logger, connectionsManager, { onStartOperation: onStartCallback, onStopOperation: undefined as any, onTerminate: undefined as any, }, boosterTokenVerifier ) }) it('sends back the expected messages', async () => { resultPromise = websocketHandler.handle(envelope) await resultPromise const sendMessageFake: SinonStub = connectionsManager.sendMessage as any expect(sendMessageFake).to.be.calledTwice expect(sendMessageFake.getCall(0).args).to.be.deep.equal([ config, envelope.connectionID, { type: MessageTypes.GQL_DATA, id: (envelope.value as GraphQLStart).id, payload: result, }, ]) expect(sendMessageFake.getCall(1).args).to.be.deep.equal([ config, envelope.connectionID, { type: MessageTypes.GQL_COMPLETE, id: (envelope.value as GraphQLStart).id, }, ]) }) }) }) describe('with a value with GQL_STOP message', () => { beforeEach(() => { envelope.value = { type: MessageTypes.GQL_STOP, id: random.alphaNumeric(10), } }) it('fails if there is no "id"', async () => { const value = envelope.value as GraphQLStop value.id = undefined as any // Force "id" to be undefined resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).to.be.calledOnceWithExactly( config, envelope.connectionID, match({ type: MessageTypes.GQL_CONNECTION_ERROR, payload: `Missing "id" in ${MessageTypes.GQL_STOP} message`, }) ) }) it('calls "onStopOperation" with the right parameters', async () => { const value = envelope.value as GraphQLStop resultPromise = websocketHandler.handle(envelope) await resultPromise expect(onStopCallback).to.have.been.calledOnceWithExactly(envelope.connectionID, value.id) }) it('sends back a GQL_COMPLETE message', async () => { const value = envelope.value as GraphQLStop resultPromise = websocketHandler.handle(envelope) await resultPromise expect(connectionsManager.sendMessage).to.have.been.calledOnceWithExactly( config, envelope.connectionID, match({ type: MessageTypes.GQL_COMPLETE, id: value.id, }) ) }) }) describe('with a value with GQL_CONNECTION_TERMINATE message', () => { beforeEach(() => { envelope.value = { type: MessageTypes.GQL_CONNECTION_TERMINATE, } }) it('calls "onTerminateOperation" with the right parameters and sends nothing back', async () => { resultPromise = websocketHandler.handle(envelope) await resultPromise expect(onTerminateCallback).to.have.been.calledOnceWithExactly(envelope.connectionID) expect(connectionsManager.sendMessage).not.to.have.been.called }) }) }) }) })
the_stack
import { Injectable } from '@angular/core'; import { combineLatest, Observable } from 'rxjs'; import { filter, map } from 'rxjs/operators'; import { helmEntityCatalog } from '../../../../helm/helm-entity-catalog'; import { ChartAttributes } from '../../../../helm/monocular/shared/models/chart'; import { ChartMetadata } from '../../../../helm/store/helm.types'; import { kubeEntityCatalog } from '../../../kubernetes-entity-generator'; import { ContainerStateCollection, KubernetesPod } from '../../../store/kube.types'; import { getHelmReleaseDetailsFromGuid } from '../../store/workloads-entity-factory'; import { HelmRelease, HelmReleaseChartData, HelmReleaseGraph, HelmReleaseGuid, HelmReleaseResources, HelmReleaseRevision, } from '../../workload.types'; import { workloadsEntityCatalog } from '../../workloads-entity-catalog'; // Simple class to represent MAJOR.MINOR.REVISION version export class Version { public major: number; public minor: number; public revision: number; public prerelease: string; public valid: boolean; constructor(v: string) { this.valid = false; if (typeof v === 'string') { let version = v; const pre = v.split('-'); if (pre.length > 1) { version = pre[0]; this.prerelease = pre[1]; } const parts = version.split('.'); if (parts.length === 3) { this.major = parseInt(parts[0], 10); this.minor = parseInt(parts[1], 10); this.revision = parseInt(parts[2], 10); this.valid = true; } } } // Is this version newer than the supplied other version? public isNewer(other: Version): boolean { if (!this.valid || !other.valid) { return false; } if (this.major > other.major) { return true; } if (this.major === other.major) { if (this.minor > other.minor) { return true; } if (this.minor === other.minor) { if (this.revision === other.revision) { // Same version numbers if (this.prerelease && !other.prerelease) { return false; } if (!this.prerelease && other.prerelease) { return true; } if (this.prerelease && other.prerelease) { return this.prerelease > other.prerelease; } return false; } return this.revision > other.revision; } } return false; } } type InternalHelmUpgrade = { release: HelmRelease, upgrade: ChartAttributes, version: string, monocularEndpointId: string; }; @Injectable() export class HelmReleaseHelperService { public isFetching$: Observable<boolean>; public release$: Observable<HelmRelease>; public guid: string; public endpointGuid: string; public namespace: string; public releaseTitle: string; constructor( helmReleaseGuid: HelmReleaseGuid, ) { this.guid = helmReleaseGuid.guid; const { endpointId, namespace, releaseTitle } = getHelmReleaseDetailsFromGuid(this.guid); this.releaseTitle = releaseTitle; this.namespace = namespace; this.endpointGuid = endpointId; const entityService = workloadsEntityCatalog.release.store.getEntityService( this.releaseTitle, this.endpointGuid, { namespace: this.namespace } ); this.release$ = entityService.waitForEntity$.pipe( map((item) => item.entity), map((item: HelmRelease) => { if (!item.chart.metadata.icon) { const copy = JSON.parse(JSON.stringify(item)); copy.chart.metadata.icon = '/core/assets/custom/app_placeholder.svg'; return copy; } return item; }) ); this.isFetching$ = entityService.isFetchingEntity$; } public guidAsUrlFragment(): string { return this.guid.replace(':', '/').replace(':', '/'); } public fetchReleaseGraph(): Observable<HelmReleaseGraph> { // Get helm release const guid = workloadsEntityCatalog.graph.actions.get(this.releaseTitle, this.endpointGuid).guid; return workloadsEntityCatalog.graph.store.getEntityMonitor(guid).entity$.pipe( filter(graph => !!graph) ); } public fetchReleaseResources(): Observable<HelmReleaseResources> { // Get helm release const guid = workloadsEntityCatalog.resource.actions.get(this.releaseTitle, this.endpointGuid).guid; return workloadsEntityCatalog.resource.store.getEntityMonitor(guid).entity$.pipe( filter(resources => !!resources) ); } public fetchReleaseChartStats(): Observable<HelmReleaseChartData> { return kubeEntityCatalog.pod.store.getInWorkload.getPaginationMonitor( this.endpointGuid, this.namespace, this.releaseTitle ).currentPage$.pipe( filter(pods => !!pods), map(pods => this.mapPods(pods)) ); } // Check to see if a workload has updates available public getCharts() { return helmEntityCatalog.chart.store.getPaginationService().entities$.pipe( filter(charts => !!charts) ); } public fetchReleaseHistory(): Observable<HelmReleaseRevision[]> { // Get the history for a Helm release return workloadsEntityCatalog.history.store.getEntityService( this.releaseTitle, this.endpointGuid, { namespace: this.namespace } ).waitForEntity$.pipe( map(historyEntity => historyEntity.entity.revisions) ); } private mapPods(pods: KubernetesPod[]): HelmReleaseChartData { const podPhases: { [phase: string]: number, } = {}; const containers = { ready: { name: 'Ready', value: 0 }, notReady: { name: 'Not Ready', value: 0 } }; pods.forEach(pod => { const status = pod.expandedStatus.status; if (!podPhases[status]) { podPhases[status] = 1; } else { podPhases[status]++; } if (pod.status.containerStatuses) { pod.status.containerStatuses.forEach(containerStatus => { const isReady = this.isContainerReady(containerStatus.state); if (isReady === true) { containers.ready.value++; } else if (isReady === false) { containers.notReady.value++; } }); } }); return { podsChartData: Object.entries(podPhases).map(([phase, count]) => ({ name: phase, value: count })), containersChartData: Object.values(containers) }; } // tslint:disable-next-line:ban-types private isContainerReady(state: ContainerStateCollection = {}): Boolean { if (state.running) { return true; } else if (!!state.waiting) { return false; } else if (!!state.terminated) { // Assume a failed state is not ready (covers completed init states), discard success state return state.terminated.exitCode === 0 ? null : false; } return false; } public hasUpgrade(returnLatest = false): Observable<InternalHelmUpgrade> { const updates = combineLatest(this.getCharts(), this.release$); return updates.pipe( map(([charts, release]) => { let score = -1; let match; for (const c of charts) { const matchScore = this.compareCharts(c.attributes, release.chart.metadata); if (matchScore > score) { score = matchScore; if (c.relationships && c.relationships.latestChartVersion && c.relationships.latestChartVersion.data) { const latest = new Version(c.relationships.latestChartVersion.data.version); const current = new Version(release.chart.metadata.version); if (latest.isNewer(current)) { match = { release, upgrade: c.attributes, version: c.relationships.latestChartVersion.data.version, monocularEndpointId: c.monocularEndpointId }; } } } } // Did we find a matching chart? If so, return it if (match) { return match; } // No newer release, so return the release itself if that is what was requested and we can find the chart // NOTE: If the helm repository is removed that we installed from, we won't be able to find the chart if (returnLatest) { // Need to check that the chart is probably the same const releaseChart = charts.find(c => this.compareCharts(c.attributes, release.chart.metadata) !== -1 && c.relationships.latestChartVersion.data.version === release.chart.metadata.version); if (releaseChart) { return { release, upgrade: releaseChart.attributes, version: releaseChart.relationships.latestChartVersion.data.version, monocularEndpointId: releaseChart.monocularEndpointId }; } } return null; }) ); } // We might have a chart with the same name in multiple repositories - we only have chart metadata // We don't know which Helm repository it came from, so use the name and sources to match // Also uses the common words in the description and returns a weight private compareCharts(a: ChartMetadata, b: ChartMetadata): number { // Basic properties must be the same if (a.name !== b.name) { return -1; } // Find common words in the descriptions const words = {}; for (let w of a.description.split(' ')) { w = w.toLowerCase(); if (w.length > 3 && w !== 'helm' && w !== 'chart') { words[w] = true; } } let common = 0; for (let w of b.description.split(' ')) { w = w.toLowerCase(); if (words[w]) { common++; } } if (!a.sources || !b.sources) { return common; } // Must have at least one source in common let count = 0; a.sources.forEach(source => { count += b.sources.findIndex((s) => s === source) === -1 ? 0 : 1; }); return common + count * 100; } }
the_stack
import { Address, Amount, AtomicSwap, AtomicSwapConnection, AtomicSwapHelpers, createTimestampTimeout, Identity, isBlockInfoPending, isBlockInfoSucceeded, isClaimedSwap, Preimage, SendTransaction, SwapClaimTransaction, SwapId, SwapIdBytes, SwapOfferTransaction, SwapProcessState, TokenTicker, UnsignedTransaction, } from "@iov/bcp"; import { createBnsConnector } from "@iov/bns"; import { Slip10RawIndex } from "@iov/crypto"; import { createEthereumConnector, Erc20ApproveTransaction, EthereumConnection } from "@iov/ethereum"; import { Ed25519HdWallet, HdPaths, Secp256k1HdWallet, UserProfile } from "@iov/keycontrol"; import { sleep } from "@iov/utils"; import BN from "bn.js"; import { MultiChainSigner } from "../multichainsigner"; const CASH = "CASH" as TokenTicker; const ETH = "ETH" as TokenTicker; const ASH = "ASH" as TokenTicker; // Copied from 'iov-ethereum/src/testconfig.spec.ts' const ganacheMnemonic = "oxygen fall sure lava energy veteran enroll frown question detail include maximum"; const atomicSwapErc20ContractAddress = "0x9768ae2339B48643d710B11dDbDb8A7eDBEa15BC" as Address; const ethereumBaseUrl = "http://localhost:8545"; const ethereumConnectionOptions = { wsUrl: "ws://localhost:8545/ws", // Low values to speedup test execution on the local ganache chain (using instant mine) pollInterval: 0.1, scraperApiUrl: undefined, atomicSwapEtherContractAddress: "0xE1C9Ea25A621Cf5C934a7E112ECaB640eC7D8d18" as Address, atomicSwapErc20ContractAddress: atomicSwapErc20ContractAddress, erc20Tokens: new Map([ [ "ASH" as TokenTicker, { contractAddress: "0xCb642A87923580b6F7D07D1471F93361196f2650" as Address, decimals: 12, symbol: "ASH", }, ], ]), }; async function tendermintSearchIndexUpdated(): Promise<void> { // Tendermint needs some time before a committed transaction is found in search return sleep(50); } function pendingWithoutBnsd(): void { if (!process.env.BNSD_ENABLED) { pending("Set BNSD_ENABLED to enable bnsd-based tests"); } } function pendingWithoutEthereum(): void { if (!process.env.ETHEREUM_ENABLED) { pending("Set ETHEREUM_ENABLED to enable ethereum-based tests"); } } interface ActorData { readonly signer: MultiChainSigner; readonly bnsConnection: AtomicSwapConnection; readonly ethereumConnection: AtomicSwapConnection; readonly bnsIdentity: Identity; readonly ethereumIdentity: Identity; } class Actor { public static async create( bnsMnemonic: string, bnsHdPath: readonly Slip10RawIndex[], ethereumMnemonic: string, ethereumHdPath: readonly Slip10RawIndex[], ): Promise<Actor> { const profile = new UserProfile(); const ed25519HdWallet = profile.addWallet(Ed25519HdWallet.fromMnemonic(bnsMnemonic)); const secp256k1HdWallet = profile.addWallet(Secp256k1HdWallet.fromMnemonic(ethereumMnemonic)); const signer = new MultiChainSigner(profile); const bnsConnection = (await signer.addChain(createBnsConnector("ws://localhost:23456"))).connection; const ethereumConnection = ( await signer.addChain(createEthereumConnector(ethereumBaseUrl, ethereumConnectionOptions)) ).connection; const bnsIdentity = await profile.createIdentity(ed25519HdWallet.id, bnsConnection.chainId, bnsHdPath); const ethereumIdentity = await profile.createIdentity( secp256k1HdWallet.id, ethereumConnection.chainId, ethereumHdPath, ); return new Actor({ signer: signer, bnsConnection: bnsConnection as AtomicSwapConnection, ethereumConnection: ethereumConnection as AtomicSwapConnection, bnsIdentity: bnsIdentity, ethereumIdentity: ethereumIdentity, }); } public readonly bnsIdentity: Identity; public readonly ethereumIdentity: Identity; public get bnsAddress(): Address { return this.signer.identityToAddress(this.bnsIdentity); } public get ethereumAddress(): Address { return this.signer.identityToAddress(this.ethereumIdentity); } private readonly signer: MultiChainSigner; private readonly bnsConnection: AtomicSwapConnection; private readonly ethereumConnection: AtomicSwapConnection; // tslint:disable-next-line:readonly-keyword private preimage: Preimage | undefined; public constructor(data: ActorData) { this.signer = data.signer; this.bnsConnection = data.bnsConnection; this.ethereumConnection = data.ethereumConnection; this.bnsIdentity = data.bnsIdentity; this.ethereumIdentity = data.ethereumIdentity; } // CASH is a token on BNS public async getCashBalance(): Promise<BN> { const account = await this.bnsConnection.getAccount({ pubkey: this.bnsIdentity.pubkey }); const balance = account ? account.balance : []; const amount = balance.find((row) => row.tokenTicker === CASH); return new BN(amount ? amount.quantity : 0); } // ETH is the native token on Ethereum public async getEthBalance(): Promise<BN> { const account = await this.ethereumConnection.getAccount({ pubkey: this.ethereumIdentity.pubkey }); const balance = account ? account.balance : []; const amount = balance.find((row) => row.tokenTicker === ETH); return new BN(amount ? amount.quantity : 0); } // ASH is a token on Ethereum public async getAshBalance(): Promise<BN> { const account = await this.ethereumConnection.getAccount({ pubkey: this.ethereumIdentity.pubkey }); const balance = account ? account.balance : []; const amount = balance.find((row) => row.tokenTicker === ASH); return new BN(amount ? amount.quantity : 0); } public async getBnsSwap(id: SwapId): Promise<AtomicSwap> { const swaps = await this.bnsConnection.getSwaps({ id: id }); return swaps[swaps.length - 1]; } public async getEthereumSwap(id: SwapId): Promise<AtomicSwap> { const swaps = await this.ethereumConnection.getSwaps({ id: id }); return swaps[swaps.length - 1]; } public async generatePreimage(): Promise<void> { // tslint:disable-next-line:no-object-mutation this.preimage = await AtomicSwapHelpers.createPreimage(); } public async sendTransaction( identity: Identity, transaction: UnsignedTransaction, ): Promise<Uint8Array | undefined> { const post = await this.signer.signAndPost(identity, transaction); const blockInfo = await post.blockInfo.waitFor((info) => !isBlockInfoPending(info)); if (!isBlockInfoSucceeded(blockInfo)) { throw new Error("Transaction failed"); } await tendermintSearchIndexUpdated(); return blockInfo.result; } public async sendBnsTokens(recipient: Address, amount: Amount): Promise<Uint8Array | undefined> { const transaction = await this.bnsConnection.withDefaultFee<SendTransaction>( { kind: "bcp/send", chainId: this.bnsIdentity.chainId, sender: this.bnsAddress, recipient: recipient, amount: amount, }, this.bnsAddress, ); return this.sendTransaction(this.bnsIdentity, transaction); } public async sendEthereumTokens(recipient: Address, amount: Amount): Promise<Uint8Array | undefined> { const transaction = await this.ethereumConnection.withDefaultFee<SendTransaction>({ kind: "bcp/send", chainId: this.ethereumIdentity.chainId, sender: this.ethereumAddress, recipient: recipient, amount: amount, }); return this.sendTransaction(this.ethereumIdentity, transaction); } public async approveErc20Spend(amount: Amount): Promise<Uint8Array | undefined> { const transaction = await this.ethereumConnection.withDefaultFee<Erc20ApproveTransaction>({ kind: "erc20/approve", chainId: this.ethereumIdentity.chainId, spender: atomicSwapErc20ContractAddress, amount: amount, }); return this.sendTransaction(this.ethereumIdentity, transaction); } public async sendSwapOfferOnBns(recipient: Address, amount: Amount): Promise<Uint8Array | undefined> { const transaction = await this.bnsConnection.withDefaultFee<SwapOfferTransaction>( { kind: "bcp/swap_offer", chainId: this.bnsIdentity.chainId, memo: "Take this cash", sender: this.bnsAddress, recipient: recipient, // Reset to something small after https://github.com/iov-one/weave/issues/718 timeout: createTimestampTimeout(36 * 3600), hash: AtomicSwapHelpers.hashPreimage(this.preimage!), amounts: [amount], }, this.bnsAddress, ); return this.sendTransaction(this.bnsIdentity, transaction); } public async sendSwapCounterOnEthereum( offer: AtomicSwap, id: SwapId, recipient: Address, amount: Amount, ): Promise<Uint8Array | undefined> { const transaction = await this.ethereumConnection.withDefaultFee<SwapOfferTransaction>({ kind: "bcp/swap_offer", chainId: this.ethereumIdentity.chainId, swapId: id, amounts: [amount], sender: this.ethereumAddress, recipient: recipient, timeout: { height: (await this.ethereumConnection.height()) + 10, }, hash: offer.data.hash, }); return this.sendTransaction(this.ethereumIdentity, transaction); } public async claimFromKnownPreimageOnEthereum(offer: AtomicSwap): Promise<Uint8Array | undefined> { const transaction = await this.ethereumConnection.withDefaultFee<SwapClaimTransaction>({ kind: "bcp/swap_claim", chainId: this.ethereumIdentity.chainId, swapId: offer.data.id, preimage: this.preimage!, }); return this.sendTransaction(this.ethereumIdentity, transaction); } public async claimFromRevealedPreimageOnBns( claim: AtomicSwap, unclaimedId: SwapId, ): Promise<Uint8Array | undefined> { if (!isClaimedSwap(claim)) { throw new Error("Expected swap to be claimed"); } const transaction = await this.bnsConnection.withDefaultFee<SwapClaimTransaction>( { kind: "bcp/swap_claim", chainId: this.bnsIdentity.chainId, swapId: unclaimedId, preimage: claim.preimage, // public data now! }, this.bnsAddress, ); return this.sendTransaction(this.bnsIdentity, transaction); } } describe("Full atomic swap between BNS and Ethereum", () => { // TODO: handle different fees... right now with assumes 0.01 of the main token as fee it("works for Ether", async () => { pendingWithoutBnsd(); pendingWithoutEthereum(); const alice = await Actor.create( "host century wave huge seed boost success right brave general orphan lion", HdPaths.iov(0), ganacheMnemonic, HdPaths.ethereum(0), ); expect(alice.bnsAddress).toEqual("tiov1xwvnaxahzcszkvmk362m7vndjkzumv8ufmzy3m"); expect(alice.ethereumAddress).toEqual("0x88F3b5659075D0E06bB1004BE7b1a7E66F452284"); const bob = await Actor.create( "dad kiss slogan offer outer bomb usual dream awkward jeans enlist mansion", HdPaths.iov(0), ganacheMnemonic, HdPaths.ethereum(2), ); expect(bob.bnsAddress).toEqual("tiov1qrw95py2x7fzjw25euuqlj6dq6t0jahe7rh8wp"); expect(bob.ethereumAddress).toEqual("0x585ec8C463C8f9481f606456402cE7CACb8D2d2A"); // We need to send a 0.01 tokens to the other ones to allow claim fees await alice.sendBnsTokens(bob.bnsAddress, { quantity: "10000000", fractionalDigits: 9, tokenTicker: CASH, }); await bob.sendEthereumTokens(alice.ethereumAddress, { quantity: "10000000", fractionalDigits: 18, tokenTicker: ETH, }); // alice owns CASH on BNS but does not need ETH const aliceInitialCash = await alice.getCashBalance(); const aliceInitialEth = await alice.getEthBalance(); expect(aliceInitialCash.gtn(100_000000000)).toEqual(true); // bob owns ETH on Ethereum but does not need CASH const bobInitialCash = await bob.getCashBalance(); const bobInitialEth = await bob.getEthBalance(); expect(bobInitialEth.gtn(100_000000000)).toEqual(true); // A secret that only Alice knows await alice.generatePreimage(); const aliceOfferId = { data: (await alice.sendSwapOfferOnBns(bob.bnsAddress, { quantity: "2000000000", fractionalDigits: 9, tokenTicker: CASH, })) as SwapIdBytes, }; // Alice's 2 CASH are locked in the contract (also consider fee) expect(aliceInitialCash.sub(await alice.getCashBalance()).toString()).toEqual("2010000000"); // check correct offer was sent on BNS const aliceOffer = await bob.getBnsSwap(aliceOfferId); expect(aliceOffer.kind).toEqual(SwapProcessState.Open); expect(aliceOffer.data.recipient).toEqual(bob.bnsAddress); expect(aliceOffer.data.amounts.length).toEqual(1); expect(aliceOffer.data.amounts[0]).toEqual({ quantity: "2000000000", fractionalDigits: 9, tokenTicker: CASH, }); const bobOfferId = await EthereumConnection.createEtherSwapId(); await bob.sendSwapCounterOnEthereum(aliceOffer, bobOfferId, alice.ethereumAddress, { quantity: "5000000000000000000", fractionalDigits: 18, tokenTicker: ETH, }); // Bob's 5 ETH are locked in the contract (plus the fee deduction) expect(bobInitialEth.sub(await bob.getEthBalance()).gt(new BN("5000000000000000000"))).toEqual(true); expect(bobInitialEth.sub(await bob.getEthBalance()).lt(new BN("5100000000000000000"))).toEqual(true); // check correct counteroffer was made on BCP const bobOffer = await alice.getEthereumSwap(bobOfferId); expect(bobOffer.kind).toEqual(SwapProcessState.Open); expect(bobOffer.data.recipient).toEqual(alice.ethereumAddress); expect(bobOffer.data.amounts.length).toEqual(1); expect(bobOffer.data.amounts[0]).toEqual({ quantity: "5000000000000000000", fractionalDigits: 18, tokenTicker: ETH, }); await alice.claimFromKnownPreimageOnEthereum(bobOffer); // Alice revealed her secret and should own 5 ETH now expect((await alice.getEthBalance()).sub(aliceInitialEth).lt(new BN("5000000000000000000"))).toEqual( true, ); expect((await alice.getEthBalance()).sub(aliceInitialEth).gt(new BN("4900000000000000000"))).toEqual( true, ); // check claim was made on BNS const aliceClaim = await bob.getEthereumSwap(bobOfferId); expect(aliceClaim.kind).toEqual(SwapProcessState.Claimed); await bob.claimFromRevealedPreimageOnBns(aliceClaim, aliceOfferId); // check claim was made on BNS const bobClaim = await alice.getBnsSwap(aliceOfferId); expect(bobClaim.kind).toEqual(SwapProcessState.Claimed); // Bob used Alice's preimage to claim his 2 CASH expect((await bob.getCashBalance()).sub(bobInitialCash).toString()).toEqual("1990000000"); // Alice's CASH balance now down by 2 (plus fees) expect(aliceInitialCash.sub(await alice.getCashBalance()).toString()).toEqual("2010000000"); // Bob's ETH balance now down by 5 (plus fees) expect(bobInitialEth.sub(await bob.getEthBalance()).gt(new BN("5000000000000000000"))).toEqual(true); expect(bobInitialEth.sub(await bob.getEthBalance()).lt(new BN("5100000000000000000"))).toEqual(true); }, 30_000); it("works for ERC20", async () => { pendingWithoutBnsd(); pendingWithoutEthereum(); const alice = await Actor.create( "host century wave huge seed boost success right brave general orphan lion", HdPaths.iov(0), ganacheMnemonic, HdPaths.ethereum(0), ); expect(alice.bnsAddress).toEqual("tiov1xwvnaxahzcszkvmk362m7vndjkzumv8ufmzy3m"); expect(alice.ethereumAddress).toEqual("0x88F3b5659075D0E06bB1004BE7b1a7E66F452284"); const bob = await Actor.create( "dad kiss slogan offer outer bomb usual dream awkward jeans enlist mansion", HdPaths.iov(0), ganacheMnemonic, HdPaths.ethereum(2), ); expect(bob.bnsAddress).toEqual("tiov1qrw95py2x7fzjw25euuqlj6dq6t0jahe7rh8wp"); expect(bob.ethereumAddress).toEqual("0x585ec8C463C8f9481f606456402cE7CACb8D2d2A"); // We need to send a 0.01 tokens to the other ones to allow claim fees await alice.sendBnsTokens(bob.bnsAddress, { quantity: "10000000", fractionalDigits: 9, tokenTicker: CASH, }); await bob.sendEthereumTokens(alice.ethereumAddress, { quantity: "10000000", fractionalDigits: 18, tokenTicker: ETH, }); // alice owns CASH on BNS but does not need ASH const aliceInitialCash = await alice.getCashBalance(); const aliceInitialAsh = await alice.getAshBalance(); expect(aliceInitialCash.gt(new BN(100_000000000))).toEqual(true); // bob owns ASH on Ethereum but does not need CASH const bobInitialCash = await bob.getCashBalance(); const bobInitialAsh = await bob.getAshBalance(); expect(bobInitialAsh.gt(new BN(10_000_000))).toEqual(true); // A secret that only Alice knows await alice.generatePreimage(); const aliceOfferId = { data: (await alice.sendSwapOfferOnBns(bob.bnsAddress, { quantity: "2000000000", fractionalDigits: 9, tokenTicker: CASH, })) as SwapIdBytes, }; // Alice's 2 CASH are locked in the contract (also consider fee) expect(aliceInitialCash.sub(await alice.getCashBalance()).toString()).toEqual("2010000000"); // check correct offer was sent on BNS const aliceOffer = await bob.getBnsSwap(aliceOfferId); expect(aliceOffer.kind).toEqual(SwapProcessState.Open); expect(aliceOffer.data.recipient).toEqual(bob.bnsAddress); expect(aliceOffer.data.amounts.length).toEqual(1); expect(aliceOffer.data.amounts[0]).toEqual({ quantity: "2000000000", fractionalDigits: 9, tokenTicker: CASH, }); const bobOfferId = await EthereumConnection.createErc20SwapId(); const bobOfferAmount = { quantity: "5000000", fractionalDigits: 12, tokenTicker: ASH, }; await bob.approveErc20Spend(bobOfferAmount); await bob.sendSwapCounterOnEthereum(aliceOffer, bobOfferId, alice.ethereumAddress, bobOfferAmount); // Bob's 0.000005 ASH are locked in the contract expect(bobInitialAsh.sub(await bob.getAshBalance()).eq(new BN("5000000"))).toEqual(true); // check correct counteroffer was made on BCP const bobOffer = await alice.getEthereumSwap(bobOfferId); expect(bobOffer.kind).toEqual(SwapProcessState.Open); expect(bobOffer.data.recipient).toEqual(alice.ethereumAddress); expect(bobOffer.data.amounts.length).toEqual(1); expect(bobOffer.data.amounts[0]).toEqual(bobOfferAmount); await alice.claimFromKnownPreimageOnEthereum(bobOffer); // Alice revealed her secret and should own 0.000005 ASH now expect((await alice.getAshBalance()).sub(aliceInitialAsh).eq(new BN("5000000"))).toEqual(true); // check claim was made on BCP const aliceClaim = await bob.getEthereumSwap(bobOfferId); expect(aliceClaim.kind).toEqual(SwapProcessState.Claimed); await bob.claimFromRevealedPreimageOnBns(aliceClaim, aliceOfferId); // check claim was made on BNS const bobClaim = await alice.getBnsSwap(aliceOfferId); expect(bobClaim.kind).toEqual(SwapProcessState.Claimed); // Bob used Alice's preimage to claim his 2 CASH expect((await bob.getCashBalance()).sub(bobInitialCash).toString()).toEqual("1990000000"); // Alice's CASH balance now down by 2 (plus fees) expect(aliceInitialCash.sub(await alice.getCashBalance()).toString()).toEqual("2010000000"); // Bob's ASH balance now down by 0.000005 expect(bobInitialAsh.sub(await bob.getAshBalance()).eq(new BN("5000000"))).toEqual(true); }, 30_000); });
the_stack
import { PuppetASTObject, PuppetASTContainerContext, Resolver, ResolveError, PuppetASTReturn, PuppetASTResourcesDeclaration, PuppetASTVariable, OrderedDictionary, PuppetASTValue, PuppetASTPrimitive, PuppetASTList, PuppetASTKeyedEntry} from "./ast"; import { isArray, isObject } from "util"; import { GlobalVariableResolverResults } from "./util" type BuiltinFunctionCallback = (caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) => Promise<any>; const BuiltInFunctions: any = { "alert": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]): Promise<any> { console.log(args[0]); }, "create_resources": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]): Promise<any> { // do nothing }, "ensure_packages": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]): Promise<any> { // do nothing }, "fail": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { throw new ResolveError(caller, args[0]); }, "defined": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { const obj: PuppetASTObject = args[0]; if (obj instanceof PuppetASTVariable) { const var_ = <PuppetASTVariable>obj; const def = await var_.defined(context, resolver); return def != GlobalVariableResolverResults.MISSING; } const def = await obj.resolve(context, resolver); return <boolean>(def); }, "fact": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { const obj: PuppetASTObject = args[0]; const factName = await obj.resolve(context, resolver); const facts = resolver.getGlobalVariable("facts"); return facts[factName]; }, "template": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { // can't do much return ""; }, "require": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { await resolver.resolveClass(args[0], true); }, "contain": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { await resolver.resolveClass(args[0], true); }, "include": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { const className = args[0]; await resolver.resolveClass(className, true); }, "hiera_include": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { const key = args[0]; const resolve = async (): Promise<number> => { const hierarchy = resolver.hasGlobalVariable(key); if (hierarchy == GlobalVariableResolverResults.MISSING) { return hierarchy; } const classes = resolver.getGlobalVariable(key); if (isArray(classes)) { for (const className of classes) { try { const resolved = await resolver.resolveClass(className, true); resolved.setOption("hiera_include", key); } catch (e) { console.log("Failed to resolve class " + className + " from hiera_include('" + key + "'): " + e.toString()); } } } return hierarchy; }; await resolver.resolveHieraSource("hiera_include", key, resolve); }, "hiera_resources": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { const key = args[0]; const resolve = async (): Promise<number> => { const hierarchy = resolver.hasGlobalVariable(key); if (hierarchy == GlobalVariableResolverResults.MISSING) { return hierarchy; } const resources = resolver.getGlobalVariable(key); if (isObject(resources)) { for (const definedTypeName in resources) { const titles = resources[definedTypeName]; // TODO // we declare resources by simulating valid PuppetASTResourcesEntry // later that sould be fixed by actually evaluating ruby scripts const bodies = new Array<PuppetASTObject>(); for (const title in titles) { const entry = new OrderedDictionary(); entry.put("title", new PuppetASTValue(title)); const ops = new Array<PuppetASTObject>(); entry.put("ops", new PuppetASTList(ops)); const properties = titles[title]; for (const propertyName in properties) { const value = properties[propertyName]; ops.push(new PuppetASTKeyedEntry([ new PuppetASTValue(propertyName), new PuppetASTValue(value) ])); } bodies.push(entry); } const options = new OrderedDictionary(); options.put("type", new PuppetASTPrimitive(definedTypeName)); options.put("bodies", new PuppetASTList(bodies)); const resourcesEntry = new PuppetASTResourcesDeclaration([options], true) resourcesEntry.hierarchy = hierarchy; try { await resourcesEntry.resolve(context, resolver); } catch (e) { console.log(e.toString()); continue; } for (const resource of resourcesEntry.entries.getValues()) { resource.setOption("hiera_resources", key); } } } return hierarchy; }; await resolver.resolveHieraSource("hiera_resources", key, resolve); }, "return": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { throw new PuppetASTReturn(args[0]); }, "all": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "annotate": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "any": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "assert_type": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "binary_file": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "break": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "call": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "convert_to": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "crit": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "debug": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "dig": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "digest": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "each": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "emerg": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "empty": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "epp": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "err": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "eyaml_lookup_key": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "file": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "filter": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "find_file": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "flatten": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "fqdn_rand": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "generate": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "hiera": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "hiera_array": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "hiera_hash": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "hocon_data": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "import": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "info": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "inline_epp": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "inline_template": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "join": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "json_data": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "keys": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "length": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "lest": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "lookup": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "map": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "match": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "md5": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "module_directory": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "new": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "next": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "notice": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "realize": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "reduce": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "regsubst": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "reverse_each": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "scanf": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "sha1": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "sha256": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "shellquote": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "slice": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "split": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "sprintf": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "step": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "strftime": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "tag": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "tagged": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "then": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "tree_each": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "type": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "unique": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "unwrap": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "values": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "versioncmp": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "warning": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "with": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented }, "yaml_data": async function(caller: PuppetASTObject, context: PuppetASTContainerContext, resolver: Resolver, args: any[]) { //not implemented } }; export function GetBuiltinFunction(name: string): BuiltinFunctionCallback { return BuiltInFunctions[name]; }
the_stack
import * as vscode from 'vscode'; import { v4 as uuid } from 'uuid'; import { Keychain } from './common/keychain'; import { GitHubEnterpriseServer, GitHubServer, IGitHubServer } from './githubServer'; import { arrayEquals } from './common/utils'; import { ExperimentationTelemetry } from './experimentationService'; import TelemetryReporter from '@vscode/extension-telemetry'; import { Log } from './common/logger'; interface SessionData { id: string; account?: { label?: string; displayName?: string; id: string; }; scopes: string[]; accessToken: string; } export enum AuthProviderType { github = 'github', githubEnterprise = 'github-enterprise' } export class GitHubAuthenticationProvider implements vscode.AuthenticationProvider, vscode.Disposable { private _sessionChangeEmitter = new vscode.EventEmitter<vscode.AuthenticationProviderAuthenticationSessionsChangeEvent>(); private _logger = new Log(this.type); private _githubServer: IGitHubServer; private _telemetryReporter: ExperimentationTelemetry; private _keychain: Keychain = new Keychain(this.context, `${this.type}.auth`, this._logger); private _sessionsPromise: Promise<vscode.AuthenticationSession[]>; private _accountsSeen = new Set<string>(); private _disposable: vscode.Disposable; constructor(private readonly context: vscode.ExtensionContext, private readonly type: AuthProviderType) { const { name, version, aiKey } = context.extension.packageJSON as { name: string; version: string; aiKey: string }; this._telemetryReporter = new ExperimentationTelemetry(context, new TelemetryReporter(name, version, aiKey)); if (this.type === AuthProviderType.github) { this._githubServer = new GitHubServer( // We only can use the Device Code flow when we have a full node environment because of CORS. context.extension.extensionKind === vscode.ExtensionKind.Workspace || vscode.env.uiKind === vscode.UIKind.Desktop, this._logger, this._telemetryReporter); } else { this._githubServer = new GitHubEnterpriseServer(this._logger, this._telemetryReporter); } // Contains the current state of the sessions we have available. this._sessionsPromise = this.readSessions().then((sessions) => { // fire telemetry after a second to allow the workbench to focus on loading setTimeout(() => sessions.forEach(s => this.afterSessionLoad(s)), 1000); return sessions; }); this._disposable = vscode.Disposable.from( this._telemetryReporter, this._githubServer, vscode.authentication.registerAuthenticationProvider(type, this._githubServer.friendlyName, this, { supportsMultipleAccounts: false }), this.context.secrets.onDidChange(() => this.checkForUpdates()) ); } dispose() { this._disposable.dispose(); } get onDidChangeSessions() { return this._sessionChangeEmitter.event; } async getSessions(scopes?: string[]): Promise<vscode.AuthenticationSession[]> { // For GitHub scope list, order doesn't matter so we immediately sort the scopes const sortedScopes = scopes?.sort() || []; this._logger.info(`Getting sessions for ${sortedScopes.length ? sortedScopes.join(',') : 'all scopes'}...`); const sessions = await this._sessionsPromise; const finalSessions = sortedScopes.length ? sessions.filter(session => arrayEquals([...session.scopes].sort(), sortedScopes)) : sessions; this._logger.info(`Got ${finalSessions.length} sessions for ${sortedScopes?.join(',') ?? 'all scopes'}...`); return finalSessions; } private async afterSessionLoad(session: vscode.AuthenticationSession): Promise<void> { // We only want to fire a telemetry if we haven't seen this account yet in this session. if (!this._accountsSeen.has(session.account.id)) { this._accountsSeen.add(session.account.id); this._githubServer.sendAdditionalTelemetryInfo(session.accessToken); } } private async checkForUpdates() { const previousSessions = await this._sessionsPromise; this._sessionsPromise = this.readSessions(); const storedSessions = await this._sessionsPromise; const added: vscode.AuthenticationSession[] = []; const removed: vscode.AuthenticationSession[] = []; storedSessions.forEach(session => { const matchesExisting = previousSessions.some(s => s.id === session.id); // Another window added a session to the keychain, add it to our state as well if (!matchesExisting) { this._logger.info('Adding session found in keychain'); added.push(session); } }); previousSessions.forEach(session => { const matchesExisting = storedSessions.some(s => s.id === session.id); // Another window has logged out, remove from our state if (!matchesExisting) { this._logger.info('Removing session no longer found in keychain'); removed.push(session); } }); if (added.length || removed.length) { this._sessionChangeEmitter.fire({ added, removed, changed: [] }); } } private async readSessions(): Promise<vscode.AuthenticationSession[]> { let sessionData: SessionData[]; try { this._logger.info('Reading sessions from keychain...'); const storedSessions = await this._keychain.getToken(); if (!storedSessions) { return []; } this._logger.info('Got stored sessions!'); try { sessionData = JSON.parse(storedSessions); } catch (e) { await this._keychain.deleteToken(); throw e; } } catch (e) { this._logger.error(`Error reading token: ${e}`); return []; } // TODO: eventually remove this Set because we should only have one session per set of scopes. const scopesSeen = new Set<string>(); const sessionPromises = sessionData.map(async (session: SessionData) => { // For GitHub scope list, order doesn't matter so we immediately sort the scopes const sortedScopes = session.scopes.sort(); const scopesStr = sortedScopes.join(' '); if (scopesSeen.has(scopesStr)) { return undefined; } let userInfo: { id: string; accountName: string } | undefined; if (!session.account) { try { userInfo = await this._githubServer.getUserInfo(session.accessToken); this._logger.info(`Verified session with the following scopes: ${scopesStr}`); } catch (e) { // Remove sessions that return unauthorized response if (e.message === 'Unauthorized') { return undefined; } } } this._logger.trace(`Read the following session from the keychain with the following scopes: ${scopesStr}`); scopesSeen.add(scopesStr); return { id: session.id, account: { label: session.account ? session.account.label ?? session.account.displayName ?? '<unknown>' : userInfo?.accountName ?? '<unknown>', id: session.account?.id ?? userInfo?.id ?? '<unknown>' }, scopes: sortedScopes, accessToken: session.accessToken }; }); const verifiedSessions = (await Promise.allSettled(sessionPromises)) .filter(p => p.status === 'fulfilled') .map(p => (p as PromiseFulfilledResult<vscode.AuthenticationSession | undefined>).value) .filter(<T>(p?: T): p is T => Boolean(p)); this._logger.info(`Got ${verifiedSessions.length} verified sessions.`); if (verifiedSessions.length !== sessionData.length) { await this.storeSessions(verifiedSessions); } return verifiedSessions; } private async storeSessions(sessions: vscode.AuthenticationSession[]): Promise<void> { this._logger.info(`Storing ${sessions.length} sessions...`); this._sessionsPromise = Promise.resolve(sessions); await this._keychain.setToken(JSON.stringify(sessions)); this._logger.info(`Stored ${sessions.length} sessions!`); } public async createSession(scopes: string[]): Promise<vscode.AuthenticationSession> { try { // For GitHub scope list, order doesn't matter so we immediately sort the scopes const sortedScopes = scopes.sort(); /* __GDPR__ "login" : { "scopes": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this._telemetryReporter?.sendTelemetryEvent('login', { scopes: JSON.stringify(sortedScopes), }); const scopeString = sortedScopes.join(' '); const token = await this._githubServer.login(scopeString); const session = await this.tokenToSession(token, sortedScopes); this.afterSessionLoad(session); const sessions = await this._sessionsPromise; const sessionIndex = sessions.findIndex(s => s.id === session.id || arrayEquals([...s.scopes].sort(), sortedScopes)); if (sessionIndex > -1) { sessions.splice(sessionIndex, 1, session); } else { sessions.push(session); } await this.storeSessions(sessions); this._sessionChangeEmitter.fire({ added: [session], removed: [], changed: [] }); this._logger.info('Login success!'); return session; } catch (e) { // If login was cancelled, do not notify user. if (e === 'Cancelled' || e.message === 'Cancelled') { /* __GDPR__ "loginCancelled" : { } */ this._telemetryReporter?.sendTelemetryEvent('loginCancelled'); throw e; } /* __GDPR__ "loginFailed" : { } */ this._telemetryReporter?.sendTelemetryEvent('loginFailed'); vscode.window.showErrorMessage(`Sign in failed: ${e}`); this._logger.error(e); throw e; } } private async tokenToSession(token: string, scopes: string[]): Promise<vscode.AuthenticationSession> { const userInfo = await this._githubServer.getUserInfo(token); return { id: uuid(), accessToken: token, account: { label: userInfo.accountName, id: userInfo.id }, scopes }; } public async removeSession(id: string) { try { /* __GDPR__ "logout" : { } */ this._telemetryReporter?.sendTelemetryEvent('logout'); this._logger.info(`Logging out of ${id}`); const sessions = await this._sessionsPromise; const sessionIndex = sessions.findIndex(session => session.id === id); if (sessionIndex > -1) { const session = sessions[sessionIndex]; sessions.splice(sessionIndex, 1); await this.storeSessions(sessions); this._sessionChangeEmitter.fire({ added: [], removed: [session], changed: [] }); } else { this._logger.error('Session not found'); } } catch (e) { /* __GDPR__ "logoutFailed" : { } */ this._telemetryReporter?.sendTelemetryEvent('logoutFailed'); vscode.window.showErrorMessage(`Sign out failed: ${e}`); this._logger.error(e); throw e; } } }
the_stack
import {createSelector} from 'reselect'; import * as Autocomplete from '@constants/autocomplete'; import {General} from '@mm-redux/constants'; import {getMyChannels, getOtherChannels} from '@mm-redux/selectors/entities/channels'; import {getConfig} from '@mm-redux/selectors/entities/general'; import { getCurrentUser, getProfilesInCurrentChannel, getProfilesNotInCurrentChannel, getProfilesInCurrentTeam, } from '@mm-redux/selectors/entities/users'; import {GlobalState} from '@mm-redux/types/store'; import {sortChannelsByDisplayName} from '@mm-redux/utils/channel_utils'; import {sortByUsername} from '@mm-redux/utils/user_utils'; import {getCurrentLocale} from '@selectors/i18n'; export const getMatchTermForAtMention = (() => { let lastMatchTerm: string | null = null; let lastValue: string; let lastIsSearch: boolean; return (value: string, isSearch: boolean) => { if (value !== lastValue || isSearch !== lastIsSearch) { const regex = isSearch ? Autocomplete.AT_MENTION_SEARCH_REGEX : Autocomplete.AT_MENTION_REGEX; let term = value; if (term.startsWith('from: @') || term.startsWith('from:@')) { term = term.replace('@', ''); } const match = term.match(regex); lastValue = value; lastIsSearch = isSearch; if (match) { lastMatchTerm = (isSearch ? match[1] : match[2]).toLowerCase(); } else { lastMatchTerm = null; } } return lastMatchTerm; }; })(); export const getMatchTermForChannelMention = (() => { let lastMatchTerm: string | null = null; let lastValue: string; let lastIsSearch: boolean; return (value: string, isSearch: boolean) => { if (value !== lastValue || isSearch !== lastIsSearch) { const regex = isSearch ? Autocomplete.CHANNEL_MENTION_SEARCH_REGEX : Autocomplete.CHANNEL_MENTION_REGEX; const match = value.match(regex); lastValue = value; lastIsSearch = isSearch; if (match) { if (isSearch) { lastMatchTerm = match[1].toLowerCase(); } else if (match.index && match.index > 0 && value[match.index - 1] === '~') { lastMatchTerm = null; } else { lastMatchTerm = match[2].toLowerCase(); } } else { lastMatchTerm = null; } } return lastMatchTerm; }; })(); export const filterMembersInChannel = createSelector( getProfilesInCurrentChannel, (state: GlobalState, matchTerm: string) => matchTerm, (profilesInChannel, matchTerm) => { if (matchTerm === null) { return null; } let profiles; if (matchTerm) { profiles = profilesInChannel.filter((p) => { const fullName = `${p.first_name.toLowerCase()} ${p.last_name.toLowerCase()}`; return (p.delete_at === 0 && ( p.username.toLowerCase().includes(matchTerm) || p.email.toLowerCase().includes(matchTerm) || p.first_name.toLowerCase().includes(matchTerm) || p.last_name.toLowerCase().includes(matchTerm) || fullName.includes(matchTerm) || p.nickname.toLowerCase().includes(matchTerm))); }); } else { profiles = profilesInChannel.filter((p) => p.delete_at === 0); } // already sorted return profiles.map((p) => p.id); }, ); export const filterMembersNotInChannel = createSelector( getProfilesNotInCurrentChannel, (state: GlobalState, matchTerm: string) => matchTerm, (profilesNotInChannel, matchTerm) => { if (matchTerm === null) { return null; } let profiles; if (matchTerm) { profiles = profilesNotInChannel.filter((p) => { const fullName = `${p.first_name.toLowerCase()} ${p.last_name.toLowerCase()}`; return ( p.username.toLowerCase().includes(matchTerm) || p.email.toLowerCase().includes(matchTerm) || p.first_name.toLowerCase().includes(matchTerm) || fullName.includes(matchTerm) || p.last_name.toLowerCase().includes(matchTerm) || p.nickname.toLowerCase().includes(matchTerm) ) && p.delete_at === 0; }); } else { profiles = profilesNotInChannel.filter((p) => p.delete_at === 0); } return profiles.map((p) => { return p.id; }); }, ); export const filterMembersInCurrentTeam = createSelector( getProfilesInCurrentTeam, getCurrentUser, (state: GlobalState, matchTerm: string) => matchTerm, (profilesInTeam, currentUser, matchTerm) => { if (matchTerm === null) { return null; } // FIXME: We need to include the currentUser here as is not in profilesInTeam on the redux store let profiles; if (matchTerm) { profiles = [...profilesInTeam, currentUser].filter((p) => { return (p.username.toLowerCase().includes(matchTerm) || p.email.toLowerCase().includes(matchTerm) || p.first_name.toLowerCase().includes(matchTerm) || p.last_name.toLowerCase().includes(matchTerm) || p.nickname.toLowerCase().includes(matchTerm)); }); } else { profiles = [...profilesInTeam, currentUser]; } return profiles.sort(sortByUsername).map((p) => p.id); }, ); export const filterMyChannels = createSelector( getMyChannels, (state: GlobalState, opts: any) => opts, (myChannels, matchTerm) => { if (matchTerm === null) { return null; } let channels; if (matchTerm) { channels = myChannels.filter((c) => { return (c.type === General.OPEN_CHANNEL || c.type === General.PRIVATE_CHANNEL) && (c.name.toLowerCase().startsWith(matchTerm) || c.display_name.toLowerCase().startsWith(matchTerm)); }); } else { channels = myChannels.filter((c) => { return (c.type === General.OPEN_CHANNEL || c.type === General.PRIVATE_CHANNEL); }); } return channels.map((c) => c.id); }, ); export const filterOtherChannels = createSelector( getOtherChannels, (state: GlobalState, matchTerm: string) => matchTerm, (otherChannels, matchTerm) => { if (matchTerm === null) { return null; } let channels; if (matchTerm) { channels = otherChannels.filter((c) => { return (c.name.toLowerCase().startsWith(matchTerm) || c.display_name.toLowerCase().startsWith(matchTerm)); }); } else { channels = otherChannels; } return channels.map((c) => c.id); }, ); export const filterPublicChannels = createSelector( getMyChannels, getOtherChannels, getCurrentLocale, (state: GlobalState, matchTerm: string) => matchTerm, getConfig, (myChannels, otherChannels, locale, matchTerm, config) => { if (matchTerm === null) { return null; } let channels; if (matchTerm) { channels = myChannels.filter((c) => { return c.type === General.OPEN_CHANNEL && (c.name.toLowerCase().startsWith(matchTerm) || c.display_name.toLowerCase().startsWith(matchTerm)); }).concat( otherChannels.filter((c) => c.name.toLowerCase().startsWith(matchTerm) || c.display_name.toLowerCase().startsWith(matchTerm)), ); } else { channels = myChannels.filter((c) => { return (c.type === General.OPEN_CHANNEL); }).concat(otherChannels); } const viewArchivedChannels = config.ExperimentalViewArchivedChannels === 'true'; if (!viewArchivedChannels) { channels = channels.filter((c) => c.delete_at === 0); } return channels.sort(sortChannelsByDisplayName.bind(null, locale)).map((c) => c.id); }, ); export const filterPrivateChannels = createSelector( getMyChannels, (state: GlobalState, matchTerm: string) => matchTerm, getConfig, (myChannels, matchTerm, config) => { if (matchTerm === null) { return null; } let channels; if (matchTerm) { channels = myChannels.filter((c) => { return c.type === General.PRIVATE_CHANNEL && (c.name.toLowerCase().startsWith(matchTerm) || c.display_name.toLowerCase().startsWith(matchTerm)); }); } else { channels = myChannels.filter((c) => { return c.type === General.PRIVATE_CHANNEL; }); } const viewArchivedChannels = config.ExperimentalViewArchivedChannels === 'true'; if (!viewArchivedChannels) { channels = channels.filter((c) => c.delete_at === 0); } return channels.map((c) => c.id); }, ); export const filterDirectAndGroupMessages = createSelector( getMyChannels, (state) => state.entities.channels.channels, (state: GlobalState, matchTerm: string) => matchTerm, (myChannels, originalChannels, matchTerm) => { if (matchTerm === null) { return null; } let mt = matchTerm; if (matchTerm.startsWith('@')) { mt = matchTerm.substr(1); } let channels; if (mt) { channels = myChannels.filter((c) => { if (c.type === General.DM_CHANNEL && (originalChannels[c.id].display_name.toLowerCase().startsWith(mt))) { return true; } if (c.type === General.GM_CHANNEL && (c.name.toLowerCase().startsWith(mt) || c.display_name.toLowerCase().replace(/ /g, '').startsWith(mt))) { return true; } return false; }); } else { channels = myChannels.filter((c) => { return c.type === General.DM_CHANNEL || c.type === General.GM_CHANNEL; }); } return channels.map((c) => c.id); }, ); export const makeGetMatchTermForDateMention = () => { let lastMatchTerm: string | null = null; let lastValue: string; return (value: string) => { if (value !== lastValue) { const regex = Autocomplete.DATE_MENTION_SEARCH_REGEX; const match = value.match(regex); lastValue = value; if (match) { lastMatchTerm = match[1]; } else { lastMatchTerm = null; } } return lastMatchTerm; }; };
the_stack
import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js'; import paintProfilerStyles from './paintProfiler.css.js'; import type * as Protocol from '../../generated/protocol.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as UI from '../../ui/legacy/legacy.js'; const UIStrings = { /** *@description Text to indicate the progress of a profile */ profiling: 'Profiling…', /** *@description Text in Paint Profiler View of the Layers panel */ shapes: 'Shapes', /** *@description Text in Paint Profiler View of the Layers panel */ bitmap: 'Bitmap', /** *@description Generic label for any text */ text: 'Text', /** *@description Text in Paint Profiler View of the Layers panel */ misc: 'Misc', /** *@description ARIA label for a pie chart that shows the results of the paint profiler */ profilingResults: 'Profiling results', /** *@description Label for command log tree in the Profiler tab */ commandLog: 'Command Log', }; const str_ = i18n.i18n.registerUIStrings('panels/layer_viewer/PaintProfilerView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); let categories: {[x: string]: PaintProfilerCategory}|null = null; let logItemCategoriesMap: {[x: string]: PaintProfilerCategory}|null = null; export class PaintProfilerView extends Common.ObjectWrapper.eventMixin<EventTypes, typeof UI.Widget.HBox>( UI.Widget.HBox) { private canvasContainer: HTMLElement; private readonly progressBanner: HTMLElement; private pieChart: PerfUI.PieChart.PieChart; private readonly showImageCallback: (arg0?: string|undefined) => void; private canvas: HTMLCanvasElement; private context: CanvasRenderingContext2D; private readonly selectionWindowInternal: PerfUI.OverviewGrid.Window; private readonly innerBarWidth: number; private minBarHeight: number; private readonly barPaddingWidth: number; private readonly outerBarWidth: number; private pendingScale: number; private scale: number; private samplesPerBar: number; private log: SDK.PaintProfiler.PaintProfilerLogItem[]; private snapshot?: SDK.PaintProfiler.PaintProfilerSnapshot|null; private logCategories?: PaintProfilerCategory[]; private profiles?: Protocol.LayerTree.PaintProfile[]|null; private updateImageTimer?: number; constructor(showImageCallback: (arg0?: string|undefined) => void) { super(true); this.contentElement.classList.add('paint-profiler-overview'); this.canvasContainer = this.contentElement.createChild('div', 'paint-profiler-canvas-container'); this.progressBanner = this.contentElement.createChild('div', 'full-widget-dimmed-banner hidden'); this.progressBanner.textContent = i18nString(UIStrings.profiling); this.pieChart = new PerfUI.PieChart.PieChart(); this.populatePieChart(0, []); this.pieChart.classList.add('paint-profiler-pie-chart'); this.contentElement.appendChild(this.pieChart); this.showImageCallback = showImageCallback; this.canvas = this.canvasContainer.createChild('canvas', 'fill') as HTMLCanvasElement; this.context = this.canvas.getContext('2d') as CanvasRenderingContext2D; this.selectionWindowInternal = new PerfUI.OverviewGrid.Window(this.canvasContainer); this.selectionWindowInternal.addEventListener(PerfUI.OverviewGrid.Events.WindowChanged, this.onWindowChanged, this); this.innerBarWidth = 4 * window.devicePixelRatio; this.minBarHeight = window.devicePixelRatio; this.barPaddingWidth = 2 * window.devicePixelRatio; this.outerBarWidth = this.innerBarWidth + this.barPaddingWidth; this.pendingScale = 1; this.scale = this.pendingScale; this.samplesPerBar = 0; this.log = []; this.reset(); } static categories(): {[x: string]: PaintProfilerCategory} { if (!categories) { categories = { shapes: new PaintProfilerCategory('shapes', i18nString(UIStrings.shapes), 'rgb(255, 161, 129)'), bitmap: new PaintProfilerCategory('bitmap', i18nString(UIStrings.bitmap), 'rgb(136, 196, 255)'), text: new PaintProfilerCategory('text', i18nString(UIStrings.text), 'rgb(180, 255, 137)'), misc: new PaintProfilerCategory('misc', i18nString(UIStrings.misc), 'rgb(206, 160, 255)'), }; } return categories; } private static initLogItemCategories(): {[x: string]: PaintProfilerCategory} { if (!logItemCategoriesMap) { const categories = PaintProfilerView.categories(); const logItemCategories: {[x: string]: PaintProfilerCategory} = {}; logItemCategories['Clear'] = categories['misc']; logItemCategories['DrawPaint'] = categories['misc']; logItemCategories['DrawData'] = categories['misc']; logItemCategories['SetMatrix'] = categories['misc']; logItemCategories['PushCull'] = categories['misc']; logItemCategories['PopCull'] = categories['misc']; logItemCategories['Translate'] = categories['misc']; logItemCategories['Scale'] = categories['misc']; logItemCategories['Concat'] = categories['misc']; logItemCategories['Restore'] = categories['misc']; logItemCategories['SaveLayer'] = categories['misc']; logItemCategories['Save'] = categories['misc']; logItemCategories['BeginCommentGroup'] = categories['misc']; logItemCategories['AddComment'] = categories['misc']; logItemCategories['EndCommentGroup'] = categories['misc']; logItemCategories['ClipRect'] = categories['misc']; logItemCategories['ClipRRect'] = categories['misc']; logItemCategories['ClipPath'] = categories['misc']; logItemCategories['ClipRegion'] = categories['misc']; logItemCategories['DrawPoints'] = categories['shapes']; logItemCategories['DrawRect'] = categories['shapes']; logItemCategories['DrawOval'] = categories['shapes']; logItemCategories['DrawRRect'] = categories['shapes']; logItemCategories['DrawPath'] = categories['shapes']; logItemCategories['DrawVertices'] = categories['shapes']; logItemCategories['DrawDRRect'] = categories['shapes']; logItemCategories['DrawBitmap'] = categories['bitmap']; logItemCategories['DrawBitmapRectToRect'] = categories['bitmap']; logItemCategories['DrawBitmapMatrix'] = categories['bitmap']; logItemCategories['DrawBitmapNine'] = categories['bitmap']; logItemCategories['DrawSprite'] = categories['bitmap']; logItemCategories['DrawPicture'] = categories['bitmap']; logItemCategories['DrawText'] = categories['text']; logItemCategories['DrawPosText'] = categories['text']; logItemCategories['DrawPosTextH'] = categories['text']; logItemCategories['DrawTextOnPath'] = categories['text']; logItemCategoriesMap = logItemCategories; } return logItemCategoriesMap; } private static categoryForLogItem(logItem: SDK.PaintProfiler.PaintProfilerLogItem): PaintProfilerCategory { const method = Platform.StringUtilities.toTitleCase(logItem.method); const logItemCategories = PaintProfilerView.initLogItemCategories(); let result: PaintProfilerCategory = logItemCategories[method]; if (!result) { result = PaintProfilerView.categories()['misc']; logItemCategories[method] = result; } return result; } onResize(): void { this.update(); } async setSnapshotAndLog( snapshot: SDK.PaintProfiler.PaintProfilerSnapshot|null, log: SDK.PaintProfiler.PaintProfilerLogItem[], clipRect: Protocol.DOM.Rect|null): Promise<void> { this.reset(); this.snapshot = snapshot; if (this.snapshot) { this.snapshot.addReference(); } this.log = log; this.logCategories = this.log.map(PaintProfilerView.categoryForLogItem); if (!snapshot) { this.update(); this.populatePieChart(0, []); this.selectionWindowInternal.setEnabled(false); return; } this.selectionWindowInternal.setEnabled(true); this.progressBanner.classList.remove('hidden'); this.updateImage(); const profiles = await snapshot.profile(clipRect); this.progressBanner.classList.add('hidden'); this.profiles = profiles; this.update(); this.updatePieChart(); } setScale(scale: number): void { const needsUpdate = scale > this.scale; const predictiveGrowthFactor = 2; this.pendingScale = Math.min(1, scale * predictiveGrowthFactor); if (needsUpdate && this.snapshot) { this.updateImage(); } } private update(): void { this.canvas.width = this.canvasContainer.clientWidth * window.devicePixelRatio; this.canvas.height = this.canvasContainer.clientHeight * window.devicePixelRatio; this.samplesPerBar = 0; if (!this.profiles || !this.profiles.length || !this.logCategories) { return; } const maxBars = Math.floor((this.canvas.width - 2 * this.barPaddingWidth) / this.outerBarWidth); const sampleCount = this.log.length; this.samplesPerBar = Math.ceil(sampleCount / maxBars); let maxBarTime = 0; const barTimes = []; const barHeightByCategory = []; let heightByCategory: {[category: string]: number} = {}; for (let i = 0, lastBarIndex = 0, lastBarTime = 0; i < sampleCount;) { let categoryName = (this.logCategories[i] && this.logCategories[i].name) || 'misc'; const sampleIndex = this.log[i].commandIndex; for (let row = 0; row < this.profiles.length; row++) { const sample = this.profiles[row][sampleIndex]; lastBarTime += sample; heightByCategory[categoryName] = (heightByCategory[categoryName] || 0) + sample; } ++i; if (i - lastBarIndex === this.samplesPerBar || i === sampleCount) { // Normalize by total number of samples accumulated. const factor = this.profiles.length * (i - lastBarIndex); lastBarTime /= factor; for (categoryName in heightByCategory) { heightByCategory[categoryName] /= factor; } barTimes.push(lastBarTime); barHeightByCategory.push(heightByCategory); if (lastBarTime > maxBarTime) { maxBarTime = lastBarTime; } lastBarTime = 0; heightByCategory = {}; lastBarIndex = i; } } const paddingHeight = 4 * window.devicePixelRatio; const scale = (this.canvas.height - paddingHeight - this.minBarHeight) / maxBarTime; for (let i = 0; i < barTimes.length; ++i) { for (const categoryName in barHeightByCategory[i]) { barHeightByCategory[i][categoryName] *= (barTimes[i] * scale + this.minBarHeight) / barTimes[i]; } this.renderBar(i, barHeightByCategory[i]); } } private renderBar(index: number, heightByCategory: {[x: string]: number}): void { const categories = PaintProfilerView.categories(); let currentHeight = 0; const x = this.barPaddingWidth + index * this.outerBarWidth; for (const categoryName in categories) { if (!heightByCategory[categoryName]) { continue; } currentHeight += heightByCategory[categoryName]; const y = this.canvas.height - currentHeight; this.context.fillStyle = categories[categoryName].color; this.context.fillRect(x, y, this.innerBarWidth, heightByCategory[categoryName]); } } private onWindowChanged(): void { this.dispatchEventToListeners(Events.WindowChanged); this.updatePieChart(); if (this.updateImageTimer) { return; } this.updateImageTimer = window.setTimeout(this.updateImage.bind(this), 100); } private updatePieChart(): void { const {total, slices} = this.calculatePieChart(); this.populatePieChart(total, slices); } private calculatePieChart(): {total: number, slices: Array<{value: number, color: string, title: string}>} { const window = this.selectionWindow(); if (!this.profiles || !this.profiles.length || !window) { return {total: 0, slices: []}; } let totalTime = 0; const timeByCategory: {[x: string]: number} = {}; for (let i = window.left; i < window.right; ++i) { const logEntry = this.log[i]; const category = PaintProfilerView.categoryForLogItem(logEntry); timeByCategory[category.color] = timeByCategory[category.color] || 0; for (let j = 0; j < this.profiles.length; ++j) { const time = this.profiles[j][logEntry.commandIndex]; totalTime += time; timeByCategory[category.color] += time; } } const slices: PerfUI.PieChart.Slice[] = []; for (const color in timeByCategory) { slices.push({value: timeByCategory[color] / this.profiles.length, color, title: ''}); } return {total: totalTime / this.profiles.length, slices}; } private populatePieChart(total: number, slices: PerfUI.PieChart.Slice[]): void { this.pieChart.data = { chartName: i18nString(UIStrings.profilingResults), size: 55, formatter: this.formatPieChartTime.bind(this), showLegend: false, total, slices, }; } private formatPieChartTime(value: number): string { return i18n.TimeUtilities.millisToString(value * 1000, true); } selectionWindow(): {left: number, right: number}|null { if (!this.log) { return null; } const screenLeft = (this.selectionWindowInternal.windowLeft || 0) * this.canvas.width; const screenRight = (this.selectionWindowInternal.windowRight || 0) * this.canvas.width; const barLeft = Math.floor(screenLeft / this.outerBarWidth); const barRight = Math.floor((screenRight + this.innerBarWidth - this.barPaddingWidth / 2) / this.outerBarWidth); const stepLeft = Platform.NumberUtilities.clamp(barLeft * this.samplesPerBar, 0, this.log.length - 1); const stepRight = Platform.NumberUtilities.clamp(barRight * this.samplesPerBar, 0, this.log.length); return {left: stepLeft, right: stepRight}; } private updateImage(): void { delete this.updateImageTimer; let left; let right; const window = this.selectionWindow(); if (this.profiles && this.profiles.length && window) { left = this.log[window.left].commandIndex; right = this.log[window.right - 1].commandIndex; } const scale = this.pendingScale; if (!this.snapshot) { return; } this.snapshot.replay(scale, left, right).then(image => { if (!image) { return; } this.scale = scale; this.showImageCallback(image); }); } private reset(): void { if (this.snapshot) { this.snapshot.release(); } this.snapshot = null; this.profiles = null; this.selectionWindowInternal.reset(); this.selectionWindowInternal.setEnabled(false); } wasShown(): void { super.wasShown(); this.registerCSSFiles([paintProfilerStyles]); } } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum Events { WindowChanged = 'WindowChanged', } export type EventTypes = { [Events.WindowChanged]: void, }; export class PaintProfilerCommandLogView extends UI.ThrottledWidget.ThrottledWidget { private readonly treeOutline: UI.TreeOutline.TreeOutlineInShadow; private log: SDK.PaintProfiler.PaintProfilerLogItem[]; private readonly treeItemCache: Map<SDK.PaintProfiler.PaintProfilerLogItem, LogTreeElement>; private selectionWindow?: {left: number, right: number}|null; constructor() { super(); this.setMinimumSize(100, 25); this.element.classList.add('overflow-auto'); this.treeOutline = new UI.TreeOutline.TreeOutlineInShadow(); UI.ARIAUtils.setAccessibleName(this.treeOutline.contentElement, i18nString(UIStrings.commandLog)); this.element.appendChild(this.treeOutline.element); this.setDefaultFocusedElement(this.treeOutline.contentElement); this.log = []; this.treeItemCache = new Map(); } setCommandLog(log: SDK.PaintProfiler.PaintProfilerLogItem[]): void { this.log = log; this.updateWindow({left: 0, right: this.log.length}); } private appendLogItem(logItem: SDK.PaintProfiler.PaintProfilerLogItem): void { let treeElement = this.treeItemCache.get(logItem); if (!treeElement) { treeElement = new LogTreeElement(this, logItem); this.treeItemCache.set(logItem, treeElement); } else if (treeElement.parent) { return; } this.treeOutline.appendChild(treeElement); } updateWindow(selectionWindow: {left: number, right: number}|null): void { this.selectionWindow = selectionWindow; this.update(); } doUpdate(): Promise<void> { if (!this.selectionWindow || !this.log.length) { this.treeOutline.removeChildren(); return Promise.resolve(); } const root = this.treeOutline.rootElement(); for (;;) { const child = root.firstChild() as LogTreeElement; if (!child || child.logItem.commandIndex >= this.selectionWindow.left) { break; } root.removeChildAtIndex(0); } for (;;) { const child = root.lastChild() as LogTreeElement; if (!child || child.logItem.commandIndex < this.selectionWindow.right) { break; } root.removeChildAtIndex(root.children().length - 1); } for (let i = this.selectionWindow.left, right = this.selectionWindow.right; i < right; ++i) { this.appendLogItem(this.log[i]); } return Promise.resolve(); } } export class LogTreeElement extends UI.TreeOutline.TreeElement { readonly logItem: SDK.PaintProfiler.PaintProfilerLogItem; private readonly ownerView: PaintProfilerCommandLogView; private readonly filled: boolean; constructor(ownerView: PaintProfilerCommandLogView, logItem: SDK.PaintProfiler.PaintProfilerLogItem) { super('', Boolean(logItem.params)); this.logItem = logItem; this.ownerView = ownerView; this.filled = false; } onattach(): void { this.update(); } async onpopulate(): Promise<void> { for (const param in this.logItem.params) { LogPropertyTreeElement.appendLogPropertyItem(this, param, this.logItem.params[param]); } } private paramToString(param: SDK.PaintProfiler.RawPaintProfilerLogItemParamValue, name: string): string { if (typeof param !== 'object') { return typeof param === 'string' && param.length > 100 ? name : JSON.stringify(param); } let str = ''; let keyCount = 0; for (const key in param) { if (++keyCount > 4 || typeof param[key] === 'object' || (typeof param[key] === 'string' && param[key].length > 100)) { return name; } if (str) { str += ', '; } str += param[key]; } return str; } private paramsToString(params: SDK.PaintProfiler.RawPaintProfilerLogItemParams|null): string { let str = ''; for (const key in params) { if (str) { str += ', '; } str += this.paramToString(params[key], key); } return str; } private update(): void { const title = document.createDocumentFragment(); UI.UIUtils.createTextChild(title, this.logItem.method + '(' + this.paramsToString(this.logItem.params) + ')'); this.title = title; } } export class LogPropertyTreeElement extends UI.TreeOutline.TreeElement { private property: {name: string, value: SDK.PaintProfiler.RawPaintProfilerLogItemParamValue}; constructor(property: {name: string, value: SDK.PaintProfiler.RawPaintProfilerLogItemParamValue}) { super(); this.property = property; } static appendLogPropertyItem( element: UI.TreeOutline.TreeElement, name: string, value: SDK.PaintProfiler.RawPaintProfilerLogItemParamValue): void { const treeElement = new LogPropertyTreeElement({name: name, value: value}); element.appendChild(treeElement); if (value && typeof value === 'object') { for (const property in value) { LogPropertyTreeElement.appendLogPropertyItem(treeElement, property, value[property]); } } } onattach(): void { const title = document.createDocumentFragment(); const nameElement = title.createChild('span', 'name'); nameElement.textContent = this.property.name; const separatorElement = title.createChild('span', 'separator'); separatorElement.textContent = ': '; if (this.property.value === null || typeof this.property.value !== 'object') { const valueElement = title.createChild('span', 'value'); valueElement.textContent = JSON.stringify(this.property.value); valueElement.classList.add('cm-js-' + (this.property.value === null ? 'null' : typeof this.property.value)); } this.title = title; } } export class PaintProfilerCategory { name: string; title: string; color: string; constructor(name: string, title: string, color: string) { this.name = name; this.title = title; this.color = color; } }
the_stack
interface Iban { alpha: string[]; formats: Array<{ bban: Array<{ type: string; count: number }>; country: string; format?: string; total?: number; }>; iso3166: string[]; mod97: (digitStr: string) => number; pattern10: string[]; pattern100: string[]; toDigitString: (str: string) => string; } const iban: Iban = { alpha: [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ], formats: [ { country: 'AL', total: 28, bban: [ { type: 'n', count: 8, }, { type: 'c', count: 16, }, ], format: 'ALkk bbbs sssx cccc cccc cccc cccc', }, { country: 'AD', total: 24, bban: [ { type: 'n', count: 8, }, { type: 'c', count: 12, }, ], format: 'ADkk bbbb ssss cccc cccc cccc', }, { country: 'AT', total: 20, bban: [ { type: 'n', count: 5, }, { type: 'n', count: 11, }, ], format: 'ATkk bbbb bccc cccc cccc', }, { // Azerbaijan // https://transferwise.com/fr/iban/azerbaijan // Length 28 // BBAN 2c,16n // GEkk bbbb cccc cccc cccc cccc cccc // b = National bank code (alpha) // c = Account number // example IBAN AZ21 NABZ 0000 0000 1370 1000 1944 country: 'AZ', total: 28, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 20, }, ], format: 'AZkk bbbb cccc cccc cccc cccc cccc', }, { country: 'BH', total: 22, bban: [ { type: 'a', count: 4, }, { type: 'c', count: 14, }, ], format: 'BHkk bbbb cccc cccc cccc cc', }, { country: 'BE', total: 16, bban: [ { type: 'n', count: 3, }, { type: 'n', count: 9, }, ], format: 'BEkk bbbc cccc ccxx', }, { country: 'BA', total: 20, bban: [ { type: 'n', count: 6, }, { type: 'n', count: 10, }, ], format: 'BAkk bbbs sscc cccc ccxx', }, { country: 'BR', total: 29, bban: [ { type: 'n', count: 13, }, { type: 'n', count: 10, }, { type: 'a', count: 1, }, { type: 'c', count: 1, }, ], format: 'BRkk bbbb bbbb ssss sccc cccc ccct n', }, { country: 'BG', total: 22, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 6, }, { type: 'c', count: 8, }, ], format: 'BGkk bbbb ssss ddcc cccc cc', }, { country: 'CR', total: 22, bban: [ { type: 'n', count: 1, }, { type: 'n', count: 3, }, { type: 'n', count: 14, }, ], format: 'CRkk xbbb cccc cccc cccc cc', }, { country: 'HR', total: 21, bban: [ { type: 'n', count: 7, }, { type: 'n', count: 10, }, ], format: 'HRkk bbbb bbbc cccc cccc c', }, { country: 'CY', total: 28, bban: [ { type: 'n', count: 8, }, { type: 'c', count: 16, }, ], format: 'CYkk bbbs ssss cccc cccc cccc cccc', }, { country: 'CZ', total: 24, bban: [ { type: 'n', count: 10, }, { type: 'n', count: 10, }, ], format: 'CZkk bbbb ssss sscc cccc cccc', }, { country: 'DK', total: 18, bban: [ { type: 'n', count: 4, }, { type: 'n', count: 10, }, ], format: 'DKkk bbbb cccc cccc cc', }, { country: 'DO', total: 28, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 20, }, ], format: 'DOkk bbbb cccc cccc cccc cccc cccc', }, { country: 'TL', total: 23, bban: [ { type: 'n', count: 3, }, { type: 'n', count: 16, }, ], format: 'TLkk bbbc cccc cccc cccc cxx', }, { country: 'EE', total: 20, bban: [ { type: 'n', count: 4, }, { type: 'n', count: 12, }, ], format: 'EEkk bbss cccc cccc cccx', }, { country: 'FO', total: 18, bban: [ { type: 'n', count: 4, }, { type: 'n', count: 10, }, ], format: 'FOkk bbbb cccc cccc cx', }, { country: 'FI', total: 18, bban: [ { type: 'n', count: 6, }, { type: 'n', count: 8, }, ], format: 'FIkk bbbb bbcc cccc cx', }, { country: 'FR', total: 27, bban: [ { type: 'n', count: 10, }, { type: 'c', count: 11, }, { type: 'n', count: 2, }, ], format: 'FRkk bbbb bggg ggcc cccc cccc cxx', }, { country: 'GE', total: 22, bban: [ { type: 'a', count: 2, }, { type: 'n', count: 16, }, ], format: 'GEkk bbcc cccc cccc cccc cc', }, { country: 'DE', total: 22, bban: [ { type: 'n', count: 8, }, { type: 'n', count: 10, }, ], format: 'DEkk bbbb bbbb cccc cccc cc', }, { country: 'GI', total: 23, bban: [ { type: 'a', count: 4, }, { type: 'c', count: 15, }, ], format: 'GIkk bbbb cccc cccc cccc ccc', }, { country: 'GR', total: 27, bban: [ { type: 'n', count: 7, }, { type: 'c', count: 16, }, ], format: 'GRkk bbbs sssc cccc cccc cccc ccc', }, { country: 'GL', total: 18, bban: [ { type: 'n', count: 4, }, { type: 'n', count: 10, }, ], format: 'GLkk bbbb cccc cccc cc', }, { country: 'GT', total: 28, bban: [ { type: 'c', count: 4, }, { type: 'c', count: 4, }, { type: 'c', count: 16, }, ], format: 'GTkk bbbb mmtt cccc cccc cccc cccc', }, { country: 'HU', total: 28, bban: [ { type: 'n', count: 8, }, { type: 'n', count: 16, }, ], format: 'HUkk bbbs sssk cccc cccc cccc cccx', }, { country: 'IS', total: 26, bban: [ { type: 'n', count: 6, }, { type: 'n', count: 16, }, ], format: 'ISkk bbbb sscc cccc iiii iiii ii', }, { country: 'IE', total: 22, bban: [ { type: 'c', count: 4, }, { type: 'n', count: 6, }, { type: 'n', count: 8, }, ], format: 'IEkk aaaa bbbb bbcc cccc cc', }, { country: 'IL', total: 23, bban: [ { type: 'n', count: 6, }, { type: 'n', count: 13, }, ], format: 'ILkk bbbn nncc cccc cccc ccc', }, { country: 'IT', total: 27, bban: [ { type: 'a', count: 1, }, { type: 'n', count: 10, }, { type: 'c', count: 12, }, ], format: 'ITkk xaaa aabb bbbc cccc cccc ccc', }, { country: 'JO', total: 30, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 4, }, { type: 'n', count: 18, }, ], format: 'JOkk bbbb nnnn cccc cccc cccc cccc cc', }, { country: 'KZ', total: 20, bban: [ { type: 'n', count: 3, }, { type: 'c', count: 13, }, ], format: 'KZkk bbbc cccc cccc cccc', }, { country: 'XK', total: 20, bban: [ { type: 'n', count: 4, }, { type: 'n', count: 12, }, ], format: 'XKkk bbbb cccc cccc cccc', }, { country: 'KW', total: 30, bban: [ { type: 'a', count: 4, }, { type: 'c', count: 22, }, ], format: 'KWkk bbbb cccc cccc cccc cccc cccc cc', }, { country: 'LV', total: 21, bban: [ { type: 'a', count: 4, }, { type: 'c', count: 13, }, ], format: 'LVkk bbbb cccc cccc cccc c', }, { country: 'LB', total: 28, bban: [ { type: 'n', count: 4, }, { type: 'c', count: 20, }, ], format: 'LBkk bbbb cccc cccc cccc cccc cccc', }, { country: 'LI', total: 21, bban: [ { type: 'n', count: 5, }, { type: 'c', count: 12, }, ], format: 'LIkk bbbb bccc cccc cccc c', }, { country: 'LT', total: 20, bban: [ { type: 'n', count: 5, }, { type: 'n', count: 11, }, ], format: 'LTkk bbbb bccc cccc cccc', }, { country: 'LU', total: 20, bban: [ { type: 'n', count: 3, }, { type: 'c', count: 13, }, ], format: 'LUkk bbbc cccc cccc cccc', }, { country: 'MK', total: 19, bban: [ { type: 'n', count: 3, }, { type: 'c', count: 10, }, { type: 'n', count: 2, }, ], format: 'MKkk bbbc cccc cccc cxx', }, { country: 'MT', total: 31, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 5, }, { type: 'c', count: 18, }, ], format: 'MTkk bbbb ssss sccc cccc cccc cccc ccc', }, { country: 'MR', total: 27, bban: [ { type: 'n', count: 10, }, { type: 'n', count: 13, }, ], format: 'MRkk bbbb bsss sscc cccc cccc cxx', }, { country: 'MU', total: 30, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 4, }, { type: 'n', count: 15, }, { type: 'a', count: 3, }, ], format: 'MUkk bbbb bbss cccc cccc cccc 000d dd', }, { country: 'MC', total: 27, bban: [ { type: 'n', count: 10, }, { type: 'c', count: 11, }, { type: 'n', count: 2, }, ], format: 'MCkk bbbb bsss sscc cccc cccc cxx', }, { country: 'MD', total: 24, bban: [ { type: 'c', count: 2, }, { type: 'c', count: 18, }, ], format: 'MDkk bbcc cccc cccc cccc cccc', }, { country: 'ME', total: 22, bban: [ { type: 'n', count: 3, }, { type: 'n', count: 15, }, ], format: 'MEkk bbbc cccc cccc cccc xx', }, { country: 'NL', total: 18, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 10, }, ], format: 'NLkk bbbb cccc cccc cc', }, { country: 'NO', total: 15, bban: [ { type: 'n', count: 4, }, { type: 'n', count: 7, }, ], format: 'NOkk bbbb cccc ccx', }, { country: 'PK', total: 24, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 16, }, ], format: 'PKkk bbbb cccc cccc cccc cccc', }, { country: 'PS', total: 29, bban: [ { type: 'c', count: 4, }, { type: 'n', count: 9, }, { type: 'n', count: 12, }, ], format: 'PSkk bbbb xxxx xxxx xccc cccc cccc c', }, { country: 'PL', total: 28, bban: [ { type: 'n', count: 8, }, { type: 'n', count: 16, }, ], format: 'PLkk bbbs sssx cccc cccc cccc cccc', }, { country: 'PT', total: 25, bban: [ { type: 'n', count: 8, }, { type: 'n', count: 13, }, ], format: 'PTkk bbbb ssss cccc cccc cccx x', }, { country: 'QA', total: 29, bban: [ { type: 'a', count: 4, }, { type: 'c', count: 21, }, ], format: 'QAkk bbbb cccc cccc cccc cccc cccc c', }, { country: 'RO', total: 24, bban: [ { type: 'a', count: 4, }, { type: 'c', count: 16, }, ], format: 'ROkk bbbb cccc cccc cccc cccc', }, { country: 'SM', total: 27, bban: [ { type: 'a', count: 1, }, { type: 'n', count: 10, }, { type: 'c', count: 12, }, ], format: 'SMkk xaaa aabb bbbc cccc cccc ccc', }, { country: 'SA', total: 24, bban: [ { type: 'n', count: 2, }, { type: 'c', count: 18, }, ], format: 'SAkk bbcc cccc cccc cccc cccc', }, { country: 'RS', total: 22, bban: [ { type: 'n', count: 3, }, { type: 'n', count: 15, }, ], format: 'RSkk bbbc cccc cccc cccc xx', }, { country: 'SK', total: 24, bban: [ { type: 'n', count: 10, }, { type: 'n', count: 10, }, ], format: 'SKkk bbbb ssss sscc cccc cccc', }, { country: 'SI', total: 19, bban: [ { type: 'n', count: 5, }, { type: 'n', count: 10, }, ], format: 'SIkk bbss sccc cccc cxx', }, { country: 'ES', total: 24, bban: [ { type: 'n', count: 10, }, { type: 'n', count: 10, }, ], format: 'ESkk bbbb gggg xxcc cccc cccc', }, { country: 'SE', total: 24, bban: [ { type: 'n', count: 3, }, { type: 'n', count: 17, }, ], format: 'SEkk bbbc cccc cccc cccc cccc', }, { country: 'CH', total: 21, bban: [ { type: 'n', count: 5, }, { type: 'c', count: 12, }, ], format: 'CHkk bbbb bccc cccc cccc c', }, { country: 'TN', total: 24, bban: [ { type: 'n', count: 5, }, { type: 'n', count: 15, }, ], format: 'TNkk bbss sccc cccc cccc cccc', }, { country: 'TR', total: 26, bban: [ { type: 'n', count: 5, }, { type: 'n', count: 1, }, { type: 'n', count: 16, }, ], format: 'TRkk bbbb bxcc cccc cccc cccc cc', }, { country: 'AE', total: 23, bban: [ { type: 'n', count: 3, }, { type: 'n', count: 16, }, ], format: 'AEkk bbbc cccc cccc cccc ccc', }, { country: 'GB', total: 22, bban: [ { type: 'a', count: 4, }, { type: 'n', count: 6, }, { type: 'n', count: 8, }, ], format: 'GBkk bbbb ssss sscc cccc cc', }, { country: 'VG', total: 24, bban: [ { type: 'c', count: 4, }, { type: 'n', count: 16, }, ], format: 'VGkk bbbb cccc cccc cccc cccc', }, ], iso3166: [ 'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'XK', 'YE', 'YT', 'ZA', 'ZM', 'ZW', ], mod97: (digitStr) => { let m = 0; for (let i = 0; i < digitStr.length; i++) { m = (m * 10 + +digitStr[i]) % 97; } return m; }, pattern10: ['01', '02', '03', '04', '05', '06', '07', '08', '09'], pattern100: ['001', '002', '003', '004', '005', '006', '007', '008', '009'], toDigitString: (str) => str.replace(/[A-Z]/gi, (match) => String(match.toUpperCase().charCodeAt(0) - 55) ), }; export default iban;
the_stack
import * as uuid from 'uuid'; export interface BundleType { type: 'bundle' | 'Bundle'; objects: Core[]; metadata?: Core[]; } export type SDO = Asset | AttackPattern | Campaign | CourseOfAction | Identity | Indicator | IntrusionSet | Malware | ObservedData | Report | ThreatActor | Tool | Vulnerability; export type SRO = Relationship | Sighting; export type StixObject = SDO | SRO; /** * Common properties and behavior across all STIX Domain Objects and STIX Relationship Objects. */ export interface Core { type: StixType; id: Identifier; id_?: Identifier; created_by_ref?: Identifier; /** * The labels property specifies a set of classifications. */ labels?: string[]; created: Timestamp; modified?: Timestamp; /** * The revoked property indicates whether the object has been revoked. */ revoked?: boolean; /** * A list of external references which refers to non-STIX information. */ external_references?: ExternalReference[]; /** * The list of marking-definition objects to be applied to this object. */ object_marking_refs?: Identifier[]; /** * The set of granular markings that apply to this object. */ granular_markings?: GranularMarking[]; } export class StixCore implements Core { public type: StixType; public id: Identifier; public created_by_ref?: Identifier; public labels?: string[]; public created: Timestamp; public modified?: Timestamp; public revoked?: boolean; public external_references?: ExternalReference[]; public object_marking_refs?: Identifier[]; public granular_markings?: GranularMarking[]; } export type ExternalReference = ({ /** * The source within which the external-reference is defined (system, registry, organization, etc.) */ source_name: string; /** * An identifier for the external reference content. */ external_id: string; [k: string]: any; } | { [k: string]: any; }); export type Id = string; export interface GranularMarking { /** * A list of selectors for content contained within the STIX object in which this property appears. */ selectors: string[]; marking_ref: (Identifier & { [k: string]: any; }); [k: string]: any; } export interface KillChainPhase { /** * The name of the kill chain. */ kill_chain_name: string; /** * The name of the phase in the kill chain. */ phase_name: string; [k: string]: any; } /** * The type property identifies the type of STIX Object (SDO, Relationship Object, etc). * The value of the type field MUST be one of the types defined by a STIX Object (e.g., indicator). */ export type StixType = string; /** * The id property universally and uniquely identifies this object. */ export type Identifier = string; export type Timestamp = string; export type Asset = (Core & { type: "asset"; id: Id; name: string; description?: string; category?: string; kind_of_asset?: string; category_ext: string[]; compromised?: boolean; owner_aware?: boolean; technical_characteristics?: Array<{ field: string, data: string }>; }); /** * Attack Patterns are a type of TTP that describe ways that adversaries attempt to compromise targets. */ export type AttackPattern = (Core & { /** * The type of this object, which MUST be the literal `attack-pattern`. */ type?: "attack-pattern"; id?: Id; /** * The name used to identify the Attack Pattern. */ name?: string; /** * A description that provides more details and context about the Attack Pattern, potentially including its purpose and its key characteristics. */ description?: string; /** * The list of kill chain phases for which this attack pattern is used. */ kill_chain_phases?: KillChainPhase[]; [k: string]: any; }); /** * A Campaign is a grouping of adversary behavior that describes a set of malicious activities or attacks that occur over a period of time against a specific set of targets. */ export type Campaign = (Core & { /** * The type of this object, which MUST be the literal `campaign`. */ type?: "campaign"; id?: Id; /** * The name used to identify the Campaign. */ name?: string; /** * A description that provides more details and context about the Campaign, potentially including its purpose and its key characteristics. */ description?: string; /** * Alternative names used to identify this campaign. */ aliases?: string[]; first_seen?: Timestamp; last_seen?: Timestamp; /** * This field defines the Campaign’s primary goal, objective, desired outcome, or intended effect. */ objective?: string; [k: string]: any; }); /** * A Course of Action is an action taken either to prevent an attack or to respond to an attack that is in progress. */ export type CourseOfAction = (Core & { /** * The type of this object, which MUST be the literal `course-of-action`. */ type?: "course-of-action"; id?: Id; /** * The name used to identify the Course of Action. */ name?: string; /** * A description that provides more details and context about this object, potentially including its purpose and its key characteristics. */ description?: string; [k: string]: any; }); /** * Identities can represent actual individuals, organizations, or groups (e.g., ACME, Inc.) as well as classes of individuals, organizations, or groups. */ export type Identity = (Core & { /** * The type of this object, which MUST be the literal `identity`. */ type?: "identity"; id?: Id; /** * The list of roles that this Identity performs (e.g., CEO, Domain Administrators, Doctors, Hospital, or Retailer). No open vocabulary is yet defined for this property. */ labels?: string[]; /** * The name of this Identity. */ name?: string; /** * A description that provides more details and context about the Identity. */ description?: string; /** * The type of entity that this Identity describes, e.g., an individual or organization. Open Vocab - identity-class-ov */ identity_class?: string; /** * The list of sectors that this Identity belongs to. Open Vocab - industry-sector-ov */ sectors?: string[]; /** * The contact information (e-mail, phone number, etc.) for this Identity. */ contact_information?: string; [k: string]: any; }); /** * Indicators contain a pattern that can be used to detect suspicious or malicious cyber activity. */ export type Indicator = (Core & { /** * The type of this object, which MUST be the literal `indicator`. */ type?: "indicator"; id?: Id; /** * This field is an Open Vocabulary that specifies the type of indicator. Open vocab - indicator-label-ov */ labels?: string[]; /** * The name used to identify the Indicator. */ name?: string; /** * A description that provides the recipient with context about this Indicator potentially including its purpose and its key characteristics. */ description?: string; /** * The detection pattern for this indicator. The default language is STIX Patterning. */ pattern?: string; valid_from?: Timestamp; valid_until?: Timestamp; /** * The phases of the kill chain that this indicator detects. */ kill_chain_phases?: KillChainPhase[]; [k: string]: any; }); /** * An Intrusion Set is a grouped set of adversary behavior and resources with common properties that is believed to be orchestrated by a single organization. */ export type IntrusionSet = (Core & { /** * The type of this object, which MUST be the literal `intrusion-set`. */ type?: "intrusion-set"; id?: Id; /** * The name used to identify the Intrusion Set. */ name?: string; /** * Provides more context and details about the Intrusion Set object. */ description?: string; /** * Alternative names used to identify this Intrusion Set. */ aliases?: string[]; first_seen?: Timestamp; last_seen?: Timestamp; /** * The high level goals of this Intrusion Set, namely, what are they trying to do. */ goals?: string[]; /** * This defines the organizational level at which this Intrusion Set typically works. Open Vocab - attack-resource-level-ov */ resource_level?: string; /** * The primary reason, motivation, or purpose behind this Intrusion Set. Open Vocab - attack-motivation-ov */ primary_motivation?: string; /** * The secondary reasons, motivations, or purposes behind this Intrusion Set. Open Vocab - attack-motivation-ov */ secondary_motivations?: string[]; [k: string]: any; }); /** * Malware is a type of TTP that is also known as malicious code and malicious software, refers to a program that is inserted into a system, usually covertly, with the intent of compromising the confidentiality, integrity, or availability of the victim's data, applications, or operating system (OS) or of otherwise annoying or disrupting the victim. */ export type Malware = (Core & { /** * The type of this object, which MUST be the literal `malware`. */ type?: "malware"; id?: Id; /** * The type of malware being described. Open Vocab - malware-label-ov */ labels?: string[]; /** * The name used to identify the Malware. */ name?: string; /** * Provides more context and details about the Malware object. */ description?: string; /** * The list of kill chain phases for which this Malware instance can be used. */ kill_chain_phases?: KillChainPhase[]; [k: string]: any; }); export type ObservedData = (Core & { /** * The type of this object, which MUST be the literal `observed-data`. */ type?: "observed-data"; id?: Id; first_observed?: Timestamp; last_observed?: Timestamp; /** * The number of times the data represented in the objects property was observed. This MUST be an integer between 1 and 999,999,999 inclusive. */ number_observed?: number; /** * A dictionary of Cyber Observable Objects that describes the single 'fact' that was observed. */ objects?: { [k: string]: any; }; [k: string]: any; }); /** * Reports are collections of threat intelligence focused on one or more topics, such as a description of a threat actor, malware, or attack technique, including context and related details. */ export type Report = (Core & { /** * The type of this object, which MUST be the literal `report`. */ type?: "report"; id?: Id; /** * This field is an Open Vocabulary that specifies the primary subject of this report. The suggested values for this field are in report-label-ov. */ labels?: string[]; /** * The name used to identify the Report. */ name?: string; /** * A description that provides more details and context about Report. */ description?: string; published?: Timestamp; /** * Specifies the STIX Objects that are referred to by this Report. */ object_refs?: Identifier[]; [k: string]: any; }); /** * Threat Actors are actual individuals, groups, or organizations believed to be operating with malicious intent. */ export type ThreatActor = (Core & { /** * The type of this object, which MUST be the literal `threat-actor`. */ type?: "threat-actor"; id?: Id; /** * This field specifies the type of threat actor. Open Vocab - threat-actor-label-ov */ labels?: string[]; /** * A name used to identify this Threat Actor or Threat Actor group. */ name?: string; /** * A description that provides more details and context about the Threat Actor. */ description?: string; /** * A list of other names that this Threat Actor is believed to use. */ aliases?: string[]; /** * This is a list of roles the Threat Actor plays. Open Vocab - threat-actor-role-ov */ roles?: string[]; /** * The high level goals of this Threat Actor, namely, what are they trying to do. */ goals?: string[]; /** * The skill, specific knowledge, special training, or expertise a Threat Actor must have to perform the attack. Open Vocab - threat-actor-sophistication-ov */ sophistication?: string; /** * This defines the organizational level at which this Threat Actor typically works. Open Vocab - attack-resource-level-ov */ resource_level?: string; /** * The primary reason, motivation, or purpose behind this Threat Actor. Open Vocab - attack-motivation-ov */ primary_motivation?: string; /** * The secondary reasons, motivations, or purposes behind this Threat Actor. Open Vocab - attack-motivation-ov */ secondary_motivations?: string[]; /** * The personal reasons, motivations, or purposes of the Threat Actor regardless of organizational goals. Open Vocab - attack-motivation-ov */ personal_motivations?: string[]; [k: string]: any; }); export type Tool = (Core & { /** * The type of this object, which MUST be the literal `tool`. */ type?: "tool"; id?: Id; /** * The kind(s) of tool(s) being described. Open Vocab - tool-label-ov */ labels?: string[]; /** * The name used to identify the Tool. */ name?: string; /** * Provides more context and details about the Tool object. */ description?: string; /** * The version identifier associated with the tool. */ tool_version?: string; /** * The list of kill chain phases for which this Tool instance can be used. */ kill_chain_phases?: KillChainPhase[]; [k: string]: any; }); /** * A Vulnerability is a mistake in software that can be directly used by a hacker to gain access to a system or network. */ export type Vulnerability = (Core & { /** * The type of this object, which MUST be the literal `vulnerability`. */ type?: "vulnerability"; id?: Id; /** * The name used to identify the Vulnerability. */ name?: string; /** * A description that provides more details and context about the Vulnerability. */ description?: string; [k: string]: any; }); /** * The Relationship object is used to link together two SDOs in order to describe how they are related to each other. */ export type Relationship = (Core & { /** * The type of this object, which MUST be the literal `relationship`. */ type?: "relationship"; id?: Id; /** * The name used to identify the type of relationship. */ relationship_type?: string; /** * A description that helps provide context about the relationship. */ description?: string; /** * The ID of the source (from) object. */ source_ref?: Identifier; /** * The ID of the target (to) object. */ target_ref?: Identifier; }); /** * A Sighting denotes the belief that something in CTI (e.g., an indicator, malware, tool, threat actor, etc.) was seen. */ export type Sighting = (Core & { /** * The type of this object, which MUST be the literal `sighting`. */ type?: "sighting"; id?: Id; first_seen?: Timestamp; last_seen?: Timestamp; /** * This is an integer between 0 and 999,999,999 inclusive and represents the number of times the object was sighted. */ count?: number; /** * An ID reference to the object that has been sighted. */ sighting_of_ref?: Identifier; /** * A list of ID references to the Observed Data objects that contain the raw cyber data for this Sighting. */ observed_data_refs?: Identifier[]; /** * The ID of the Victim Target objects of the entities that saw the sighting. */ where_sighted_refs?: Identifier[]; /** * The summary property indicates whether the Sighting should be considered summary data. */ summary?: boolean; }); export interface CyberObservableCore { /** * Indicates that this object is an Observable Object. The value of this property MUST be a valid Observable Object type name, but to allow for custom objects this has been removed from the schema. */ type: string; /** * Specifies a textual description of the Object. */ description?: string; extensions?: Dictionary; } /** * Specifies any extensions of the object, as a dictionary. */ export interface Dictionary { [key: string]: any; } /** * The Artifact Object permits capturing an array of bytes (8-bits), as a base64-encoded string string, or linking to a file-like payload. */ export type Artifact = (CyberObservableCore & { /** * The value of this property MUST be `artifact`. */ type?: "artifact"; /** * The value of this property MUST be a valid MIME type as specified in the IANA Media Types registry. */ mime_type?: string; [k: string]: any; }); /** * Common properties and behavior across all Cyber Observable Objects. */ /** * The AS object represents the properties of an Autonomous Systems (AS). */ export type AutonomousSystem = (CyberObservableCore & { /** * The value of this property MUST be `autonomous-system`. */ type?: "autonomous-system"; /** * Specifies the number assigned to the AS. Such assignments are typically performed by a Regional Internet Registries (RIR). */ number: number; /** * Specifies the name of the AS. */ name?: string; /** * Specifies the name of the Regional Internet Registry (RIR) that assigned the number to the AS. */ rir?: string; [k: string]: any; }); /** * The Directory Object represents the properties common to a file system directory. */ export type Directory = (CyberObservableCore & { /** * The value of this property MUST be `directory`. */ type?: "directory"; /** * Specifies the path, as originally observed, to the directory on the file system. */ path: string; /** * Specifies the observed encoding for the path. */ path_enc?: string; created?: Timestamp; modified?: Timestamp; accessed?: Timestamp; /** * Specifies a list of references to other File and/or Directory Objects contained within the directory. */ contains_refs?: string[]; [k: string]: any; }); /** * The Domain Name represents the properties of a network domain name. */ export type DomainName = (CyberObservableCore & { /** * The value of this property MUST be `domain-name`. */ type?: "domain-name"; /** * Specifies the value of the domain name. */ value: string; /** * Specifies a list of references to one or more IP addresses or domain names that the domain name resolves to. */ resolves_to_refs?: string[]; [k: string]: any; }); /** * The Email Address Object represents a single email address. */ export type EmailAddr = (CyberObservableCore & { /** * The value of this property MUST be `email-addr`. */ type?: "email-addr"; /** * Specifies a single email address. This MUST not include the display name. */ value: string; /** * Specifies a single email display name, i.e., the name that is displayed to the human user of a mail application. */ display_name?: string; /** * Specifies the user account that the email address belongs to, as a reference to a User Account Object. */ belongs_to_ref?: string; [k: string]: any; }); /** * The Email Message Object represents an instance of an email message. */ export type EmailMessage = (CyberObservableCore & { /** * The value of this property MUST be `email-message`. */ type?: "email-message"; date?: Timestamp; /** * Specifies the value of the 'Content-Type' header of the email message. */ content_type?: string; /** * Specifies the value of the 'From:' header of the email message. */ from_ref?: string; /** * Specifies the value of the 'From' field of the email message */ sender_ref?: string; /** * Specifies the mailboxes that are 'To:' recipients of the email message */ to_refs?: string[]; /** * Specifies the mailboxes that are 'CC:' recipients of the email message */ cc_refs?: string[]; /** * Specifies the mailboxes that are 'BCC:' recipients of the email message. */ bcc_refs?: string[]; /** * Specifies the subject of the email message. */ subject?: string; /** * Specifies one or more Received header fields that may be included in the email headers. */ received_lines?: string[]; /** * Specifies any other header fields found in the email message, as a dictionary. */ additional_header_fields?: { [k: string]: any; }; /** * Specifies the raw binary contents of the email message, including both the headers and body, as a reference to an Artifact Object. */ raw_email_ref?: string; [k: string]: any; }); /** * The File Object represents the properties of a file. */ export type File = (CyberObservableCore & { /** * The value of this property MUST be `file`. */ type?: "file"; /** * The File Object defines the following extensions. In addition to these, producers MAY create their own. Extensions: ntfs-ext, raster-image-ext, pdf-ext, archive-ext, windows-pebinary-ext */ extensions?: { [k: string]: Dictionary; }; hashes?: Dictionary; /** * Specifies the size of the file, in bytes, as a non-negative integer. */ size?: number; /** * Specifies the name of the file. */ name?: string; /** * Specifies the observed encoding for the name of the file. */ name_enc?: string; magic_number_hex?: Hex; /** * Specifies the MIME type name specified for the file, e.g., 'application/msword'. */ mime_type?: string; created?: Timestamp; modified?: Timestamp; accessed?: Timestamp; /** * Specifies the parent directory of the file, as a reference to a Directory Object. */ parent_directory_ref?: string; /** * Specifies a list of references to other Observable Objects contained within the file. */ contains_refs?: string[]; /** * Specifies the content of the file, represented as an Artifact Object. */ content_ref?: string; [k: string]: any; }); /** * Specifies the hexadecimal constant ('magic number') associated with a specific file format that corresponds to the file, if applicable. */ export type Hex = string; /** * The IPv4 Address Object represents one or more IPv4 addresses expressed using CIDR notation. */ export type Ipv4Addr = (CyberObservableCore & { /** * The value of this property MUST be `ipv4-addr`. */ type?: "ipv4-addr"; /** * Specifies one or more IPv4 addresses expressed using CIDR notation. */ value: string; /** * Specifies a list of references to one or more Layer 2 Media Access Control (MAC) addresses that the IPv4 address resolves to. */ resolves_to_refs?: string[]; /** * Specifies a reference to one or more autonomous systems (AS) that the IPv4 address belongs to. */ belongs_to_refs?: string[]; [k: string]: any; }); /** * The IPv6 Address Object represents one or more IPv6 addresses expressed using CIDR notation. */ export type Ipv6Addr = (CyberObservableCore & { /** * The value of this property MUST be `ipv6-addr`. */ type?: "ipv6-addr"; /** * Specifies one or more IPv6 addresses expressed using CIDR notation. */ value: string; /** * Specifies a list of references to one or more Layer 2 Media Access Control (MAC) addresses that the IPv6 address resolves to. */ resolves_to_refs?: string[]; /** * Specifies a reference to one or more autonomous systems (AS) that the IPv6 address belongs to. */ belongs_to_refs?: string[]; [k: string]: any; }); export interface MarkingDefinition { type: "marking definition"; id: Identifier; created_by_ref?: Identifier; created: Timestamp; definition_type: "statement"; definition: { statement: string; }; } export interface ObjectMarkingRelationship extends Relationship { type: "relationship"; relationship_type: 'applies-to'; id: Identifier; source_ref: Identifier; target_ref: Identifier; created: Timestamp; modified: Timestamp; description: string; } export class ObjectMarkingRelationship implements ObjectMarkingRelationship { public type: "relationship"; public relationship_type: 'applies-to'; public id: Identifier; public source_ref: Identifier; public target_ref: Identifier; public created: Timestamp; public modified: Timestamp; public description: string; constructor(source_ref: Identifier, target_ref: Identifier, created: Timestamp, modified: Timestamp) { this.source_ref = source_ref; this.target_ref = target_ref; this.created = created; this.modified = modified; this.id = 'applies-to--' + uuid.v4(); this.type = "relationship"; this.relationship_type = "applies-to"; } } export interface CreatedByRelationship extends Relationship { type: "relationship"; relationship_type: 'created-by'; source_ref: Id; target_ref: Id; id: Id; description: string; created: Timestamp; modified: Timestamp; } export function CreatedByRelationshipFactory(src_ref: Identifier, tgt_ref: Identifier, ceate_time: Timestamp, mod_time: Timestamp): CreatedByRelationship { const ret = { type: "relationship", relationship_type: 'created-by', source_ref: src_ref, target_ref: tgt_ref, id: 'created-by--' + uuid.v4(), description: '', created: ceate_time, modified: mod_time, }; return ret as CreatedByRelationship; }
the_stack
import { Accessor, Observable } from "../observation/observable"; import { DOM } from "../dom"; import type { Notifier } from "../observation/notifier"; /** * Represents objects that can convert values to and from * view or model representations. * @public */ export interface ValueConverter { /** * Converts a value from its representation in the model, to a representation for the view. * @param value - The value to convert to a view representation. */ toView(value: any): any; /** * Converts a value from its representation in the view, to a representation for the model. * @param value - The value to convert to a model representation. */ fromView(value: any): any; } /** * The mode that specifies the runtime behavior of the attribute. * @remarks * By default, attributes run in `reflect` mode, propagating their property * values to the DOM and DOM values to the property. The `boolean` mode also * reflects values, but uses the HTML standard boolean attribute behavior, * interpreting the presence of the attribute as `true` and the absence as * `false`. The `fromView` behavior only updates the property value based on * changes in the DOM, but does not reflect property changes back. * @public */ export type AttributeMode = "reflect" | "boolean" | "fromView"; /** * Metadata used to configure a custom attribute's behavior. * @public */ export type AttributeConfiguration = { property: string; attribute?: string; mode?: AttributeMode; converter?: ValueConverter; }; /** * Metadata used to configure a custom attribute's behavior through a decorator. * @public */ export type DecoratorAttributeConfiguration = Omit<AttributeConfiguration, "property">; /** * A {@link ValueConverter} that converts to and from `boolean` values. * @remarks * Used automatically when the `boolean` {@link AttributeMode} is selected. * @public */ export const booleanConverter: ValueConverter = { toView(value: any): string { return value ? "true" : "false"; }, fromView(value: any): any { if ( value === null || value === void 0 || value === "false" || value === false || value === 0 ) { return false; } return true; }, }; /** * A {@link ValueConverter} that converts to and from `number` values. * @remarks * This converter allows for nullable numbers, returning `null` if the * input was `null`, `undefined`, or `NaN`. * @public */ export const nullableNumberConverter: ValueConverter = { toView(value: any): string | null { if (value === null || value === undefined) { return null; } const number: number = value * 1; return isNaN(number) ? null : number.toString(); }, fromView(value: any): any { if (value === null || value === undefined) { return null; } const number: number = value * 1; return isNaN(number) ? null : number; }, }; /** * An implementation of {@link Accessor} that supports reactivity, * change callbacks, attribute reflection, and type conversion for * custom elements. * @public */ export class AttributeDefinition implements Accessor { private readonly fieldName: string; private readonly callbackName: string; private readonly hasCallback: boolean; private readonly guards: Set<unknown> = new Set(); /** * The class constructor that owns this attribute. */ public readonly Owner: Function; /** * The name of the property associated with the attribute. */ public readonly name: string; /** * The name of the attribute in HTML. */ public readonly attribute: string; /** * The {@link AttributeMode} that describes the behavior of this attribute. */ public readonly mode: AttributeMode; /** * A {@link ValueConverter} that integrates with the property getter/setter * to convert values to and from a DOM string. */ public readonly converter?: ValueConverter; /** * Creates an instance of AttributeDefinition. * @param Owner - The class constructor that owns this attribute. * @param name - The name of the property associated with the attribute. * @param attribute - The name of the attribute in HTML. * @param mode - The {@link AttributeMode} that describes the behavior of this attribute. * @param converter - A {@link ValueConverter} that integrates with the property getter/setter * to convert values to and from a DOM string. */ public constructor( Owner: Function, name: string, attribute: string = name.toLowerCase(), mode: AttributeMode = "reflect", converter?: ValueConverter ) { this.Owner = Owner; this.name = name; this.attribute = attribute; this.mode = mode; this.converter = converter; this.fieldName = `_${name}`; this.callbackName = `${name}Changed`; this.hasCallback = this.callbackName in Owner.prototype; if (mode === "boolean" && converter === void 0) { this.converter = booleanConverter; } } /** * Sets the value of the attribute/property on the source element. * @param source - The source element to access. * @param value - The value to set the attribute/property to. */ public setValue(source: HTMLElement, newValue: any): void { const oldValue = source[this.fieldName]; const converter = this.converter; if (converter !== void 0) { newValue = converter.fromView(newValue); } if (oldValue !== newValue) { source[this.fieldName] = newValue; this.tryReflectToAttribute(source); if (this.hasCallback) { source[this.callbackName](oldValue, newValue); } ((source as any).$fastController as Notifier).notify(this.name); } } /** * Gets the value of the attribute/property on the source element. * @param source - The source element to access. */ public getValue(source: HTMLElement): any { Observable.track(source, this.name); return source[this.fieldName]; } /** @internal */ public onAttributeChangedCallback(element: HTMLElement, value: any): void { if (this.guards.has(element)) { return; } this.guards.add(element); this.setValue(element, value); this.guards.delete(element); } private tryReflectToAttribute(element: HTMLElement): void { const mode = this.mode; const guards = this.guards; if (guards.has(element) || mode === "fromView") { return; } DOM.queueUpdate(() => { guards.add(element); const latestValue = element[this.fieldName]; switch (mode) { case "reflect": const converter = this.converter; DOM.setAttribute( element, this.attribute, converter !== void 0 ? converter.toView(latestValue) : latestValue ); break; case "boolean": DOM.setBooleanAttribute(element, this.attribute, latestValue); break; } guards.delete(element); }); } /** * Collects all attribute definitions associated with the owner. * @param Owner - The class constructor to collect attribute for. * @param attributeLists - Any existing attributes to collect and merge with those associated with the owner. * @internal */ public static collect( Owner: Function, ...attributeLists: (ReadonlyArray<string | AttributeConfiguration> | undefined)[] ): ReadonlyArray<AttributeDefinition> { const attributes: AttributeDefinition[] = []; attributeLists.push((Owner as any).attributes); for (let i = 0, ii = attributeLists.length; i < ii; ++i) { const list = attributeLists[i]; if (list === void 0) { continue; } for (let j = 0, jj = list.length; j < jj; ++j) { const config = list[j]; if (typeof config === "string") { attributes.push(new AttributeDefinition(Owner, config)); } else { attributes.push( new AttributeDefinition( Owner, config.property, config.attribute, config.mode, config.converter ) ); } } } return attributes; } } /** * Decorator: Specifies an HTML attribute. * @param config - The configuration for the attribute. * @public */ export function attr( config?: DecoratorAttributeConfiguration ): (target: {}, property: string) => void; /** * Decorator: Specifies an HTML attribute. * @param target - The class to define the attribute on. * @param prop - The property name to be associated with the attribute. * @public */ export function attr(target: {}, prop: string): void; export function attr( configOrTarget?: DecoratorAttributeConfiguration | {}, prop?: string ): void | ((target: {}, property: string) => void) { let config: AttributeConfiguration; function decorator($target: {}, $prop: string): void { if (arguments.length > 1) { // Non invocation: // - @attr // Invocation with or w/o opts: // - @attr() // - @attr({...opts}) config.property = $prop; } const attributes: AttributeConfiguration[] = ($target.constructor as any).attributes || (($target.constructor as any).attributes = []); attributes.push(config); } if (arguments.length > 1) { // Non invocation: // - @attr config = {} as any; decorator(configOrTarget!, prop!); return; } // Invocation with or w/o opts: // - @attr() // - @attr({...opts}) config = configOrTarget === void 0 ? ({} as any) : configOrTarget; return decorator; }
the_stack
import React, { forwardRef, useContext, useRef, useState, useImperativeHandle, useEffect, useCallback, useMemo, } from 'react'; import { CSSTransition } from 'react-transition-group'; import { findDOMNode } from 'react-dom'; import cs from '../_util/classNames'; import { on, off, isServerRendering } from '../_util/dom'; import ResizeObserver from '../_util/resizeObserver'; import IconLoading from '../../icon/react-icon/IconLoading'; import IconZoomOut from '../../icon/react-icon/IconZoomOut'; import IconZoomIn from '../../icon/react-icon/IconZoomIn'; import IconFullscreen from '../../icon/react-icon/IconFullscreen'; import IconClose from '../../icon/react-icon/IconClose'; import IconRotateLeft from '../../icon/react-icon/IconRotateLeft'; import IconRotateRight from '../../icon/react-icon/IconRotateRight'; import IconOriginalSize from '../../icon/react-icon/IconOriginalSize'; import ConfigProvider, { ConfigContext } from '../ConfigProvider'; import { ImagePreviewProps } from './interface'; import useImageStatus from './utils/hooks/useImageStatus'; import PreviewScales, { defaultScales } from './utils/getScale'; import getFixTranslate from './utils/getFixTranslate'; import ImagePreviewToolbar from './image-preview-toolbar'; import useMergeValue from '../_util/hooks/useMergeValue'; import Portal from '../Portal'; import { PreviewGroupContext } from './previewGroupContext'; import ImagePreviewArrow from './image-preview-arrow'; import useOverflowHidden from '../_util/hooks/useOverflowHidden'; import { Esc } from '../_util/keycode'; import useUpdate from '../_util/hooks/useUpdate'; const ROTATE_STEP = 90; export type ImagePreviewHandle = { reset: () => void; }; function Preview(props: ImagePreviewProps, ref) { const { className, style, src, defaultVisible, maskClosable = true, closable = true, breakPoint = 316, actions, actionsLayout = [ 'fullScreen', 'rotateRight', 'rotateLeft', 'zoomIn', 'zoomOut', 'originalSize', 'extra', ], getPopupContainer = () => document.body, onVisibleChange, scales = defaultScales, escToExit = true, } = props; const { previewGroup, previewUrlMap, currentIndex, setCurrentIndex, infinite } = useContext(PreviewGroupContext); const mergedSrc = previewGroup ? previewUrlMap.get(currentIndex) : src; const [previewImgSrc, setPreviewImgSrc] = useState(mergedSrc); const [visible, setVisible] = useMergeValue(false, { defaultValue: defaultVisible, value: props.visible, }); const globalContext = useContext(ConfigContext); const { getPrefixCls, locale } = globalContext; const prefixCls = getPrefixCls('image'); const previewPrefixCls = `${prefixCls}-preview`; const classNames = cs( previewPrefixCls, { [`${previewPrefixCls}-hide`]: !visible, }, className ); const refImage = useRef<HTMLImageElement>(); const refImageContainer = useRef<HTMLDivElement>(); const refWrapper = useRef<HTMLDivElement>(); const keyboardEventOn = useRef<boolean>(false); const refMoveData = useRef({ pageX: 0, pageY: 0, originX: 0, originY: 0, }); const { isLoading, isLoaded, setStatus } = useImageStatus('loading'); const [toolbarSimple, setToolbarSimple] = useState(false); const [translate, setTranslate] = useState({ x: 0, y: 0 }); const [scale, setScale] = useState(1); const [scaleValueVisible, setScaleValueVisible] = useState(false); const [rotate, setRotate] = useState(0); const [moving, setMoving] = useState(false); const previewScales = useMemo(() => { return new PreviewScales(scales); }, []); // Reset image params function reset() { setTranslate({ x: 0, y: 0 }); setScale(1); setRotate(0); } useImperativeHandle<ImagePreviewHandle, ImagePreviewHandle>(ref, () => ({ reset, })); const [container, setContainer] = useState<HTMLElement>(); const getContainer = useCallback(() => container, [container]); useEffect(() => { const container = getPopupContainer && getPopupContainer(); const containerDom = (findDOMNode(container) || document.body) as HTMLElement; setContainer(containerDom); }, [getPopupContainer]); useOverflowHidden(getContainer, { hidden: visible }); const isFixed = useMemo(() => !isServerRendering && container === document.body, [container]); // Jump to image at the specified index function jumpTo(index: number) { const previewListLen = previewUrlMap.size; if (infinite) { index %= previewListLen; if (index < 0) index = previewListLen - Math.abs(index); } if (index !== currentIndex && index >= 0 && index <= previewListLen - 1) { setCurrentIndex(index); } } function onPrev() { jumpTo(currentIndex - 1); } function onNext() { jumpTo(currentIndex + 1); } // Anticlockwise rotation function onRotateLeft() { setRotate(rotate === 0 ? 360 - ROTATE_STEP : rotate - ROTATE_STEP); } // Clockwise rotation function onRotateRight() { setRotate((rotate + ROTATE_STEP) % 360); } // Scale const hideScaleTimer = useRef(null); const showScaleValue = () => { !scaleValueVisible && setScaleValueVisible(true); hideScaleTimer.current && clearTimeout(hideScaleTimer.current); hideScaleTimer.current = setTimeout(() => { setScaleValueVisible(false); }, 1000); }; const onScaleChange = (newScale) => { if (scale !== newScale) { setScale(newScale); showScaleValue(); } }; function onZoomIn() { const newScale = previewScales.getNextScale(scale, 'zoomIn'); onScaleChange(newScale); } function onZoomOut() { const newScale = previewScales.getNextScale(scale, 'zoomOut'); onScaleChange(newScale); } function onResetScale() { onScaleChange(1); } function onFullScreen() { const wrapperRect = refWrapper.current.getBoundingClientRect(); const imgRect = refImage.current.getBoundingClientRect(); const newHeightScale = wrapperRect.height / (imgRect.height / scale); const newWidthScale = wrapperRect.width / (imgRect.width / scale); const newScale = Math.max(newHeightScale, newWidthScale); onScaleChange(newScale); } // Image container is clicked function onOutsideImgClick(e) { if (e.target === e.currentTarget && maskClosable) { close(); } } // Close button is clicked. function onCloseClick() { close(); } function close() { if (visible) { onVisibleChange && onVisibleChange(false, visible); setVisible(false); } } function onWrapperResize(entry) { if (entry && entry.length) { const wrapperRect = entry[0].contentRect; const nextSimple = wrapperRect.width < breakPoint; setToolbarSimple(nextSimple); } } // Check the translate and correct it if needed const checkAndFixTranslate = () => { if (!refWrapper.current || !refImage.current) return; const wrapperRect = refWrapper.current.getBoundingClientRect(); const imgRect = refImage.current.getBoundingClientRect(); const [x, y] = getFixTranslate(wrapperRect, imgRect, translate.x, translate.y, scale); if (x !== translate.x || y !== translate.y) { setTranslate({ x, y, }); } }; // Update position on moving if needed const onMoving = (e) => { if (visible && moving) { e.preventDefault && e.preventDefault(); const { originX, originY, pageX, pageY } = refMoveData.current; const nextX = originX + (e.pageX - pageX) / scale; const nextY = originY + (e.pageY - pageY) / scale; setTranslate({ x: nextX, y: nextY, }); } }; const onMoveEnd = (e) => { e.preventDefault && e.preventDefault(); setMoving(false); }; // Record position data on move start const onMoveStart = (e) => { e.preventDefault && e.preventDefault(); setMoving(true); const ev = e.type === 'touchstart' ? e.touches[0] : e; refMoveData.current.pageX = ev.pageX; refMoveData.current.pageY = ev.pageY; refMoveData.current.originX = translate.x; refMoveData.current.originY = translate.y; }; useEffect(() => { if (visible && moving) { on(document, 'mousemove', onMoving, false); on(document, 'mouseup', onMoveEnd, false); } return () => { off(document, 'mousemove', onMoving, false); off(document, 'mouseup', onMoveEnd, false); }; }, [visible, moving]); // Correct translate after moved useEffect(() => { if (!moving) { checkAndFixTranslate(); } }, [moving, translate]); // Correct translate when scale changes useEffect(() => { checkAndFixTranslate(); }, [scale]); // Reset when preview is opened useEffect(() => { if (visible) { reset(); } }, [visible]); // Reset on first mount or image switches useEffect(() => { setPreviewImgSrc(mergedSrc); setStatus(mergedSrc ? 'loading' : 'loaded'); reset(); }, [mergedSrc]); useUpdate(() => { previewScales.updateScale(scales); setScale(1); }, [scales]); // Close when pressing esc useEffect(() => { const onKeyDown = (e) => { if (escToExit && e && e.key === Esc.key) { close(); } }; if (visible && !moving && !keyboardEventOn.current) { keyboardEventOn.current = true; on(document, 'keydown', onKeyDown); } return () => { keyboardEventOn.current = false; off(document, 'keydown', onKeyDown); }; }, [visible, escToExit, moving]); const defaultActions = [ { key: 'fullScreen', name: locale.ImagePreview.fullScreen, content: <IconFullscreen />, onClick: onFullScreen, }, { key: 'rotateRight', name: locale.ImagePreview.rotateRight, content: <IconRotateRight />, onClick: onRotateRight, }, { key: 'rotateLeft', name: locale.ImagePreview.rotateLeft, content: <IconRotateLeft />, onClick: onRotateLeft, }, { key: 'zoomIn', name: locale.ImagePreview.zoomIn, content: <IconZoomIn />, onClick: onZoomIn, disabled: scale === previewScales.maxScale, }, { key: 'zoomOut', name: locale.ImagePreview.zoomOut, content: <IconZoomOut />, onClick: onZoomOut, disabled: scale === previewScales.minScale, }, { key: 'originalSize', name: locale.ImagePreview.originalSize, content: <IconOriginalSize />, onClick: onResetScale, }, ]; return ( <Portal visible={visible} forceRender={false} getContainer={getContainer}> {/* ConfigProvider need to inherit the outermost Context. https://github.com/arco-design/arco-design/issues/387 */} <ConfigProvider {...globalContext} getPopupContainer={() => refWrapper.current}> <div className={classNames} style={{ ...(style || {}), ...(isFixed ? {} : { zIndex: 'inherit', position: 'absolute' }), }} > <CSSTransition in={visible} timeout={400} appear classNames="fadeImage" mountOnEnter unmountOnExit={false} onEnter={(e) => { e.parentNode.style.display = 'block'; e.style.display = 'block'; }} onExited={(e) => { e.parentNode.style.display = ''; e.style.display = 'none'; }} > <div className={`${previewPrefixCls}-mask`} /> </CSSTransition> {visible && ( <ResizeObserver onResize={onWrapperResize}> <div ref={refWrapper} className={`${previewPrefixCls}-wrapper`} onClick={onOutsideImgClick} > <div ref={refImageContainer} className={`${previewPrefixCls}-img-container`} style={{ transform: `scale(${scale}, ${scale})` }} onClick={onOutsideImgClick} > <img ref={refImage} className={cs(`${previewPrefixCls}-img`, { [`${previewPrefixCls}-img-moving`]: moving, })} style={{ transform: `translate(${translate.x}px, ${translate.y}px) rotate(${rotate}deg)`, }} onLoad={() => { setStatus('loaded'); }} onError={() => { setStatus('error'); }} onMouseDown={onMoveStart} key={previewImgSrc} src={previewImgSrc} /> {isLoading && ( <div className={`${previewPrefixCls}-loading`}> <IconLoading /> </div> )} </div> <CSSTransition in={scaleValueVisible} timeout={400} appear classNames="fadeImage" unmountOnExit > <div className={`${previewPrefixCls}-scale-value`}> {(scale * 100).toFixed(0)}% </div> </CSSTransition> {isLoaded && ( <ImagePreviewToolbar prefixCls={prefixCls} previewPrefixCls={previewPrefixCls} actions={actions} actionsLayout={actionsLayout} defaultActions={defaultActions} simple={toolbarSimple} /> )} {closable && ( <div className={`${previewPrefixCls}-close-btn`} onClick={onCloseClick}> <IconClose /> </div> )} {previewGroup && ( <ImagePreviewArrow previewCount={previewUrlMap.size} current={currentIndex} infinite={infinite} onPrev={onPrev} onNext={onNext} /> )} </div> </ResizeObserver> )} </div> </ConfigProvider> </Portal> ); } const PreviewComponent = forwardRef<ImagePreviewHandle, ImagePreviewProps>(Preview); PreviewComponent.displayName = 'ImagePreview'; export default PreviewComponent;
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CompleteSnapshotCommand, CompleteSnapshotCommandInput, CompleteSnapshotCommandOutput, } from "./commands/CompleteSnapshotCommand"; import { GetSnapshotBlockCommand, GetSnapshotBlockCommandInput, GetSnapshotBlockCommandOutput, } from "./commands/GetSnapshotBlockCommand"; import { ListChangedBlocksCommand, ListChangedBlocksCommandInput, ListChangedBlocksCommandOutput, } from "./commands/ListChangedBlocksCommand"; import { ListSnapshotBlocksCommand, ListSnapshotBlocksCommandInput, ListSnapshotBlocksCommandOutput, } from "./commands/ListSnapshotBlocksCommand"; import { PutSnapshotBlockCommand, PutSnapshotBlockCommandInput, PutSnapshotBlockCommandOutput, } from "./commands/PutSnapshotBlockCommand"; import { StartSnapshotCommand, StartSnapshotCommandInput, StartSnapshotCommandOutput, } from "./commands/StartSnapshotCommand"; import { EBSClient } from "./EBSClient"; /** * <p>You can use the Amazon Elastic Block Store (Amazon EBS) direct APIs to create Amazon EBS snapshots, write data directly to * your snapshots, read data on your snapshots, and identify the differences or changes between * two snapshots. If you’re an independent software vendor (ISV) who offers backup services for * Amazon EBS, the EBS direct APIs make it more efficient and cost-effective to track incremental changes on * your Amazon EBS volumes through snapshots. This can be done without having to create new volumes * from snapshots, and then use Amazon Elastic Compute Cloud (Amazon EC2) instances to compare the differences.</p> * * <p>You can create incremental snapshots directly from data on-premises into volumes and the * cloud to use for quick disaster recovery. With the ability to write and read snapshots, you can * write your on-premises data to an snapshot during a disaster. Then after recovery, you can * restore it back to Amazon Web Services or on-premises from the snapshot. You no longer need to build and * maintain complex mechanisms to copy data to and from Amazon EBS.</p> * * * <p>This API reference provides detailed information about the actions, data types, * parameters, and errors of the EBS direct APIs. For more information about the elements that * make up the EBS direct APIs, and examples of how to use them effectively, see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-accessing-snapshot.html">Accessing the Contents of an Amazon EBS Snapshot</a> in the <i>Amazon Elastic Compute Cloud User * Guide</i>. For more information about the supported Amazon Web Services Regions, endpoints, * and service quotas for the EBS direct APIs, see <a href="https://docs.aws.amazon.com/general/latest/gr/ebs-service.html">Amazon Elastic Block Store Endpoints and Quotas</a> in * the <i>Amazon Web Services General Reference</i>.</p> */ export class EBS extends EBSClient { /** * <p>Seals and completes the snapshot after all of the required blocks of data have been * written to it. Completing the snapshot changes the status to <code>completed</code>. You * cannot write new blocks to a snapshot after it has been completed.</p> */ public completeSnapshot( args: CompleteSnapshotCommandInput, options?: __HttpHandlerOptions ): Promise<CompleteSnapshotCommandOutput>; public completeSnapshot( args: CompleteSnapshotCommandInput, cb: (err: any, data?: CompleteSnapshotCommandOutput) => void ): void; public completeSnapshot( args: CompleteSnapshotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CompleteSnapshotCommandOutput) => void ): void; public completeSnapshot( args: CompleteSnapshotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CompleteSnapshotCommandOutput) => void), cb?: (err: any, data?: CompleteSnapshotCommandOutput) => void ): Promise<CompleteSnapshotCommandOutput> | void { const command = new CompleteSnapshotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the data in a block in an Amazon Elastic Block Store snapshot.</p> */ public getSnapshotBlock( args: GetSnapshotBlockCommandInput, options?: __HttpHandlerOptions ): Promise<GetSnapshotBlockCommandOutput>; public getSnapshotBlock( args: GetSnapshotBlockCommandInput, cb: (err: any, data?: GetSnapshotBlockCommandOutput) => void ): void; public getSnapshotBlock( args: GetSnapshotBlockCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetSnapshotBlockCommandOutput) => void ): void; public getSnapshotBlock( args: GetSnapshotBlockCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSnapshotBlockCommandOutput) => void), cb?: (err: any, data?: GetSnapshotBlockCommandOutput) => void ): Promise<GetSnapshotBlockCommandOutput> | void { const command = new GetSnapshotBlockCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the blocks that are different between two * Amazon Elastic Block Store snapshots of the same volume/snapshot lineage.</p> */ public listChangedBlocks( args: ListChangedBlocksCommandInput, options?: __HttpHandlerOptions ): Promise<ListChangedBlocksCommandOutput>; public listChangedBlocks( args: ListChangedBlocksCommandInput, cb: (err: any, data?: ListChangedBlocksCommandOutput) => void ): void; public listChangedBlocks( args: ListChangedBlocksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListChangedBlocksCommandOutput) => void ): void; public listChangedBlocks( args: ListChangedBlocksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListChangedBlocksCommandOutput) => void), cb?: (err: any, data?: ListChangedBlocksCommandOutput) => void ): Promise<ListChangedBlocksCommandOutput> | void { const command = new ListChangedBlocksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the blocks in an Amazon Elastic Block Store snapshot.</p> */ public listSnapshotBlocks( args: ListSnapshotBlocksCommandInput, options?: __HttpHandlerOptions ): Promise<ListSnapshotBlocksCommandOutput>; public listSnapshotBlocks( args: ListSnapshotBlocksCommandInput, cb: (err: any, data?: ListSnapshotBlocksCommandOutput) => void ): void; public listSnapshotBlocks( args: ListSnapshotBlocksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListSnapshotBlocksCommandOutput) => void ): void; public listSnapshotBlocks( args: ListSnapshotBlocksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListSnapshotBlocksCommandOutput) => void), cb?: (err: any, data?: ListSnapshotBlocksCommandOutput) => void ): Promise<ListSnapshotBlocksCommandOutput> | void { const command = new ListSnapshotBlocksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Writes a block of data to a snapshot. If the specified block contains * data, the existing data is overwritten. The target snapshot must be in the * <code>pending</code> state.</p> * <p>Data written to a snapshot must be aligned with 512-KiB sectors.</p> */ public putSnapshotBlock( args: PutSnapshotBlockCommandInput, options?: __HttpHandlerOptions ): Promise<PutSnapshotBlockCommandOutput>; public putSnapshotBlock( args: PutSnapshotBlockCommandInput, cb: (err: any, data?: PutSnapshotBlockCommandOutput) => void ): void; public putSnapshotBlock( args: PutSnapshotBlockCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutSnapshotBlockCommandOutput) => void ): void; public putSnapshotBlock( args: PutSnapshotBlockCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutSnapshotBlockCommandOutput) => void), cb?: (err: any, data?: PutSnapshotBlockCommandOutput) => void ): Promise<PutSnapshotBlockCommandOutput> | void { const command = new PutSnapshotBlockCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new Amazon EBS snapshot. The new snapshot enters the <code>pending</code> state * after the request completes. </p> * <p>After creating the snapshot, use <a href="https://docs.aws.amazon.com/ebs/latest/APIReference/API_PutSnapshotBlock.html"> PutSnapshotBlock</a> to * write blocks of data to the snapshot.</p> */ public startSnapshot( args: StartSnapshotCommandInput, options?: __HttpHandlerOptions ): Promise<StartSnapshotCommandOutput>; public startSnapshot( args: StartSnapshotCommandInput, cb: (err: any, data?: StartSnapshotCommandOutput) => void ): void; public startSnapshot( args: StartSnapshotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartSnapshotCommandOutput) => void ): void; public startSnapshot( args: StartSnapshotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartSnapshotCommandOutput) => void), cb?: (err: any, data?: StartSnapshotCommandOutput) => void ): Promise<StartSnapshotCommandOutput> | void { const command = new StartSnapshotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import * as assert from 'assert'; import {before, beforeEach, afterEach, describe, it} from 'mocha'; import {EventEmitter} from 'events'; import * as extend from 'extend'; import {ApiError, util} from '@google-cloud/common'; import * as proxyquire from 'proxyquire'; import * as sinon from 'sinon'; import {Transform, Duplex} from 'stream'; import * as through from 'through2'; import * as pfy from '@google-cloud/promisify'; import {grpc} from 'google-gax'; import * as db from '../src/database'; import {Instance} from '../src'; import {MockError} from './mockserver/mockspanner'; import {IOperation} from '../src/instance'; import {CLOUD_RESOURCE_HEADER} from '../src/common'; import {google} from '../protos/protos'; import RequestOptions = google.spanner.v1.RequestOptions; import EncryptionType = google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType; let promisified = false; const fakePfy = extend({}, pfy, { promisifyAll(klass, options) { if (klass.name !== 'Database') { return; } promisified = true; assert.deepStrictEqual(options.exclude, [ 'batchTransaction', 'getRestoreInfo', 'getState', 'getOperations', 'runTransaction', 'runTransactionAsync', 'table', 'session', ]); }, }); class FakeBatchTransaction { calledWith_: IArguments; id?: string; readTimestamp?: {seconds: number; nanos: number}; constructor() { this.calledWith_ = arguments; } } class FakeGrpcServiceObject extends EventEmitter { calledWith_: IArguments; constructor() { super(); this.calledWith_ = arguments; } } function fakePartialResultStream(this: Function & {calledWith_: IArguments}) { this.calledWith_ = arguments; return this; } class FakeSession { calledWith_: IArguments; constructor() { this.calledWith_ = arguments; } partitionedDml(): FakeTransaction { return new FakeTransaction(); } snapshot(): FakeTransaction { return new FakeTransaction(); } } interface ReadSessionCallback { (err: Error, session?: null): void; (err: null, session: FakeSession): void; } interface WriteSessionCallback { (err: Error, session?: null, transaction?: null): void; (err: null, session: FakeSession, transaction: FakeTransaction): void; } class FakeSessionPool extends EventEmitter { calledWith_: IArguments; constructor() { super(); this.calledWith_ = arguments; } open() {} getReadSession() {} getWriteSession() {} release() {} } class FakeTable { calledWith_: IArguments; constructor() { this.calledWith_ = arguments; } } class FakeTransaction extends EventEmitter { calledWith_: IArguments; constructor() { super(); this.calledWith_ = arguments; } begin() {} end() {} runStream(): Transform { return through.obj(); } runUpdate() {} } let fakeTransactionRunner: FakeTransactionRunner; class FakeTransactionRunner { calledWith_: IArguments; constructor() { this.calledWith_ = arguments; fakeTransactionRunner = this; } async run(): Promise<void> {} } let fakeAsyncTransactionRunner: FakeAsyncTransactionRunner<{}>; class FakeAsyncTransactionRunner<T> { calledWith_: IArguments; constructor() { this.calledWith_ = arguments; fakeAsyncTransactionRunner = this; } async run(): Promise<T> { return {} as T; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any const fakeCodec: any = { encode: util.noop, Int() {}, Float() {}, SpannerDate() {}, }; class FakeAbortError { error; constructor(err) { this.error = err; } } const fakeRetry = fn => { return fn(); }; fakeRetry.AbortError = FakeAbortError; describe('Database', () => { const sandbox = sinon.createSandbox(); // tslint:disable-next-line variable-name let Database: typeof db.Database; // tslint:disable-next-line variable-name let DatabaseCached: typeof db.Database; const INSTANCE = { request: util.noop, requestStream: util.noop, formattedName_: 'instance-name', databases_: new Map(), } as {} as Instance; const NAME = 'table-name'; const DATABASE_FORMATTED_NAME = INSTANCE.formattedName_ + '/databases/' + NAME; const POOL_OPTIONS = {}; let database; before(() => { Database = proxyquire('../src/database.js', { './common-grpc/service-object': { GrpcServiceObject: FakeGrpcServiceObject, }, '@google-cloud/promisify': fakePfy, 'p-retry': fakeRetry, './batch-transaction': {BatchTransaction: FakeBatchTransaction}, './codec': {codec: fakeCodec}, './partial-result-stream': {partialResultStream: fakePartialResultStream}, './session-pool': {SessionPool: FakeSessionPool}, './session': {Session: FakeSession}, './table': {Table: FakeTable}, './transaction-runner': { TransactionRunner: FakeTransactionRunner, AsyncTransactionRunner: FakeAsyncTransactionRunner, }, }).Database; // The following commented out line is the one that will trigger the error. // DatabaseCached = extend({}, Database); DatabaseCached = Object.assign({}, Database); }); beforeEach(() => { fakeCodec.encode = util.noop; extend(Database, DatabaseCached); database = new Database(INSTANCE, NAME, POOL_OPTIONS); database.parent = INSTANCE; }); afterEach(() => sandbox.restore()); describe('instantiation', () => { it('should promisify all the things', () => { assert(promisified); }); it('should localize the request function', () => { assert.strictEqual(database.request, INSTANCE.request); }); it('should localize the requestStream function', () => { assert.strictEqual(database.requestStream, INSTANCE.requestStream); }); it('should format the name', () => { const formatName_ = Database.formatName_; const formattedName = 'formatted-name'; Database.formatName_ = (instanceName, name) => { Database.formatName_ = formatName_; assert.strictEqual(instanceName, INSTANCE.formattedName_); assert.strictEqual(name, NAME); return formattedName; }; const database = new Database(INSTANCE, NAME); assert(database.formattedName_, formattedName); }); it('should create a SessionPool object', () => { assert(database.pool_ instanceof FakeSessionPool); assert.strictEqual(database.pool_.calledWith_[0], database); assert.strictEqual(database.pool_.calledWith_[1], POOL_OPTIONS); }); it('should accept a custom Pool class', () => { function FakePool() {} FakePool.prototype.on = util.noop; FakePool.prototype.open = util.noop; const database = new Database( INSTANCE, NAME, FakePool as {} as db.SessionPoolConstructor ); assert(database.pool_ instanceof FakePool); }); it('should re-emit SessionPool errors', done => { const error = new Error('err'); database.on('error', err => { assert.strictEqual(err, error); done(); }); database.pool_.emit('error', error); }); it('should open the pool', done => { FakeSessionPool.prototype.open = () => { FakeSessionPool.prototype.open = util.noop; done(); }; new Database(INSTANCE, NAME); }); it('should inherit from ServiceObject', done => { const options = {}; const instanceInstance = extend({}, INSTANCE, { createDatabase(name, options_, callback) { assert.strictEqual(name, database.formattedName_); assert.strictEqual(options_, options); callback(); // done() }, }); // eslint-disable-next-line @typescript-eslint/no-explicit-any const database: any = new Database(instanceInstance, NAME); assert(database instanceof FakeGrpcServiceObject); const calledWith = database.calledWith_[0]; assert.strictEqual(calledWith.parent, instanceInstance); assert.strictEqual(calledWith.id, NAME); assert.deepStrictEqual(calledWith.methods, {create: true}); calledWith.createMethod(null, options, done); }); it('should set the resourceHeader_', () => { assert.deepStrictEqual(database.resourceHeader_, { [CLOUD_RESOURCE_HEADER]: database.formattedName_, }); }); }); describe('formatName_', () => { it('should return the name if already formatted', () => { assert.strictEqual( Database.formatName_(INSTANCE.formattedName_, DATABASE_FORMATTED_NAME), DATABASE_FORMATTED_NAME ); }); it('should format the name', () => { const formattedName_ = Database.formatName_( INSTANCE.formattedName_, NAME ); assert.strictEqual(formattedName_, DATABASE_FORMATTED_NAME); }); }); describe('batchCreateSessions', () => { it('should make the correct request', () => { const stub = sandbox.stub(database, 'request'); const count = 10; database.batchCreateSessions({count}, assert.ifError); const {client, method, reqOpts, gaxOpts, headers} = stub.lastCall.args[0]; assert.strictEqual(client, 'SpannerClient'); assert.strictEqual(method, 'batchCreateSessions'); assert.strictEqual(reqOpts.database, DATABASE_FORMATTED_NAME); assert.strictEqual(reqOpts.sessionCount, count); assert.strictEqual(gaxOpts, undefined); assert.deepStrictEqual(headers, database.resourceHeader_); }); it('should accept just a count number', () => { const stub = sandbox.stub(database, 'request'); const count = 10; database.batchCreateSessions(count, assert.ifError); const {reqOpts} = stub.lastCall.args[0]; assert.strictEqual(reqOpts.sessionCount, count); }); it('should accept session labels', () => { const stub = sandbox.stub(database, 'request'); const labels = {foo: 'bar'}; database.batchCreateSessions({count: 10, labels}, assert.ifError); const {reqOpts} = stub.lastCall.args[0]; assert.deepStrictEqual(reqOpts.sessionTemplate, {labels}); }); it('should accept gaxOptions', () => { const stub = sandbox.stub(database, 'request'); const gaxOptions = {timeout: 1000}; database.batchCreateSessions({count: 10, gaxOptions}, assert.ifError); const {gaxOpts} = stub.lastCall.args[0]; assert.strictEqual(gaxOpts, gaxOptions); }); it('should return any request errors', done => { const error = new Error('err'); const response = {}; sandbox.stub(database, 'request').callsFake((_, cb) => { cb(error, response); }); database.batchCreateSessions({count: 10}, (err, sessions, resp) => { assert.strictEqual(err, error); assert.strictEqual(sessions, null); assert.strictEqual(resp, response); done(); }); }); it('should create session objects from the response', done => { const stub = sandbox.stub(database, 'session'); const fakeSessions = [{}, {}, {}]; const response = { session: [{name: 'a'}, {name: 'b'}, {name: 'c'}], }; response.session.forEach((session, i) => { stub.withArgs(session.name).returns(fakeSessions[i]); }); sandbox.stub(database, 'request').callsFake((_, cb) => { cb(null, response); }); database.batchCreateSessions({count: 10}, (err, sessions, resp) => { assert.strictEqual(err, null); assert.deepStrictEqual(sessions, fakeSessions); assert.strictEqual(resp, response); done(); }); }); }); describe('batchTransaction', () => { const SESSION = {id: 'hijklmnop'}; const ID = 'abcdefg'; const READ_TIMESTAMP = {seconds: 0, nanos: 0}; it('should create a transaction object', () => { const identifier = { session: SESSION, transaction: ID, timestamp: READ_TIMESTAMP, }; const transaction = database.batchTransaction(identifier); assert(transaction instanceof FakeBatchTransaction); assert.deepStrictEqual(transaction.calledWith_[0], SESSION); assert.strictEqual(transaction.id, ID); assert.strictEqual(transaction.readTimestamp, READ_TIMESTAMP); }); it('should optionally accept a session id', () => { const identifier = { session: SESSION.id, transaction: ID, timestamp: READ_TIMESTAMP, }; database.session = id => { assert.strictEqual(id, SESSION.id); return SESSION; }; const transaction = database.batchTransaction(identifier); assert.deepStrictEqual(transaction.calledWith_[0], SESSION); }); }); describe('close', () => { const FAKE_ID = 'a/c/b/d'; beforeEach(() => { database.id = FAKE_ID; }); describe('success', () => { beforeEach(() => { database.parent = INSTANCE; database.pool_ = { close(callback) { callback(null); }, }; }); it('should close the database', done => { database.close(done); }); it('should remove the database cache', done => { const cache = INSTANCE.databases_; const cacheId = FAKE_ID.split('/').pop()!; cache.set(cacheId, database); assert(cache.has(cacheId)); database.close(err => { assert.ifError(err); assert.strictEqual(cache.has(cacheId), false); done(); }); }); }); describe('error', () => { it('should return the closing error', done => { const error = new Error('err.'); database.pool_ = { close(callback) { callback(error); }, }; database.close(err => { assert.strictEqual(err, error); done(); }); }); }); }); describe('createBatchTransaction', () => { const SESSION = {}; const RESPONSE = {a: 'b'}; beforeEach(() => { database.pool_ = { getReadSession(callback) { callback(null, SESSION); }, }; }); it('should return any get session errors', done => { const error = new Error('err'); database.pool_ = { getReadSession(callback) { callback(error); }, }; database.createBatchTransaction((err, transaction, resp) => { assert.strictEqual(err, error); assert.strictEqual(transaction, null); assert.strictEqual(resp, undefined); done(); }); }); it('should create a transaction', done => { const opts = {a: 'b'}; const fakeTransaction = { begin(callback) { callback(null, RESPONSE); }, once() {}, }; database.batchTransaction = (identifier, options) => { assert.deepStrictEqual(identifier, {session: SESSION}); assert.strictEqual(options, opts); return fakeTransaction; }; database.createBatchTransaction(opts, (err, transaction, resp) => { assert.strictEqual(err, null); assert.strictEqual(transaction, fakeTransaction); assert.strictEqual(resp, RESPONSE); done(); }); }); it('should return any transaction errors', done => { const error = new Error('err'); const fakeTransaction = { begin(callback) { callback(error, RESPONSE); }, once() {}, }; database.batchTransaction = () => { return fakeTransaction; }; database.createBatchTransaction((err, transaction, resp) => { assert.strictEqual(err, error); assert.strictEqual(transaction, null); assert.strictEqual(resp, RESPONSE); done(); }); }); }); describe('createTable', () => { const TABLE_NAME = 'table-name'; const SCHEMA = 'CREATE TABLE `' + TABLE_NAME + '`'; it('should call updateSchema', done => { database.updateSchema = schema => { assert.strictEqual(schema, SCHEMA); done(); }; database.createTable(SCHEMA, assert.ifError); }); it('should accept and pass gaxOptions to updateSchema', done => { const gaxOptions = {}; database.updateSchema = (schema, options) => { assert.strictEqual(options, gaxOptions); done(); }; database.createTable(SCHEMA, gaxOptions, assert.ifError); }); describe('error', () => { const ERROR = new Error('Error.'); const API_RESPONSE = {}; beforeEach(() => { database.updateSchema = (name, options, callback) => { callback(ERROR, null, API_RESPONSE); }; }); it('should execute callback with error & API response', done => { database.createTable(SCHEMA, (err, table, op, apiResponse) => { assert.strictEqual(err, ERROR); assert.strictEqual(table, null); assert.strictEqual(op, null); assert.strictEqual(apiResponse, API_RESPONSE); done(); }); }); }); describe('success', () => { const OPERATION = {}; const API_RESPONSE = {}; beforeEach(() => { database.updateSchema = (name, options, callback) => { callback(null, OPERATION, API_RESPONSE); }; }); describe('table name parsing', () => { it('should recognize an escaped name', done => { database.table = name => { assert.strictEqual(name, TABLE_NAME); done(); }; database.createTable(SCHEMA, assert.ifError); }); it('should recognize a non-escaped name', done => { database.table = name => { assert.strictEqual(name, TABLE_NAME); done(); }; database.createTable('CREATE TABLE ' + TABLE_NAME, assert.ifError); }); }); it('should exec callback with Table, op & API response', done => { const tableInstance = {}; database.table = name => { assert.strictEqual(name, TABLE_NAME); return tableInstance; }; database.createTable(SCHEMA, (err, table, op, apiResponse) => { assert.ifError(err); assert.strictEqual(table, tableInstance); assert.strictEqual(op, OPERATION); assert.strictEqual(apiResponse, API_RESPONSE); done(); }); }); }); }); describe('delete', () => { beforeEach(() => { database.close = callback => { callback(); }; }); it('should close the database', done => { database.close = () => { done(); }; database.delete(); }); it('should make the correct request', () => { database.request = (config, callback) => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'dropDatabase'); assert.deepStrictEqual(config.reqOpts, { database: database.formattedName_, }); assert.deepStrictEqual(config.gaxOpts, {}); assert.deepStrictEqual(config.headers, database.resourceHeader_); assert.strictEqual(callback, assert.ifError); }; database.delete(assert.ifError); }); it('should accept gaxOptions', done => { const gaxOptions = {}; database.request = config => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; database.delete(gaxOptions, assert.ifError); }); }); describe('exists', () => { it('should return any non-404 like errors', done => { const error = {code: 3}; database.getMetadata = (options, callback) => { callback(error); }; database.exists((err, exists) => { assert.strictEqual(err, error); assert.strictEqual(exists, undefined); done(); }); }); it('should return true if error is absent', done => { database.getMetadata = (options, callback) => { callback(null); }; database.exists((err, exists) => { assert.ifError(err); assert.strictEqual(exists, true); done(); }); }); it('should return false if not found error if present', done => { const error = {code: 5}; database.getMetadata = (options, callback) => { callback(error); }; database.exists((err, exists) => { assert.ifError(err); assert.strictEqual(exists, false); done(); }); }); it('should accept and pass gaxOptions to getMetadata', done => { const gaxOptions = {}; database.getMetadata = options => { assert.strictEqual(options, gaxOptions); done(); }; database.exists(gaxOptions, assert.ifError); }); }); describe('get', () => { it('should call getMetadata', done => { const options = {}; database.getMetadata = () => { done(); }; database.get(options, assert.ifError); }); it('should accept and pass gaxOptions to getMetadata', done => { const gaxOptions = {}; database.getMetadata = options => { assert.strictEqual(options, gaxOptions); done(); }; database.get({gaxOptions}); }); it('should not require an options object', done => { database.getMetadata = () => { done(); }; database.get(assert.ifError); }); describe('autoCreate', () => { const error = new Error('Error.'); (error as ApiError).code = 5; const OPTIONS = { autoCreate: true, }; const OPERATION = { listeners: {}, on(eventName, callback) { OPERATION.listeners[eventName] = callback; return OPERATION; }, }; beforeEach(() => { OPERATION.listeners = {}; database.getMetadata = (options, callback) => { callback(error); }; database.create = (options, callback) => { callback(null, null, OPERATION); }; }); it('should call create', done => { database.create = options => { assert.strictEqual(options, OPTIONS); done(); }; database.get(OPTIONS, assert.ifError); }); it('should pass gaxOptions to create', done => { const gaxOptions = {}; const options = Object.assign({}, OPTIONS, {gaxOptions}); database.create = opts => { assert.strictEqual(opts.gaxOptions, options.gaxOptions); done(); }; database.get(options, assert.ifError); }); it('should return error if create failed', done => { const error = new Error('Error.'); database.create = (options, callback) => { callback(error); }; database.get(OPTIONS, err => { assert.strictEqual(err, error); done(); }); }); it('should return operation error', done => { const error = new Error('Error.'); setImmediate(() => { OPERATION.listeners['error'](error); }); database.get(OPTIONS, err => { assert.strictEqual(err, error); done(); }); }); it('should execute callback if opereation succeeded', done => { const metadata = {}; setImmediate(() => { OPERATION.listeners['complete'](metadata); }); database.get(OPTIONS, (err, database_, apiResponse) => { assert.ifError(err); assert.strictEqual(database_, database); assert.strictEqual(database.metadata, metadata); assert.strictEqual(metadata, apiResponse); done(); }); }); }); it('should not auto create without error code 5', done => { const error = new Error('Error.'); // eslint-disable-next-line @typescript-eslint/no-explicit-any (error as any).code = 'NOT-5'; const options = { autoCreate: true, }; database.getMetadata = (options, callback) => { callback(error); }; database.create = () => { throw new Error('Should not create.'); }; database.get(options, err => { assert.strictEqual(err, error); done(); }); }); it('should not auto create unless requested', done => { const error = new ApiError('Error.'); error.code = 5; database.getMetadata = (options, callback) => { callback(error); }; database.create = () => { throw new Error('Should not create.'); }; database.get(err => { assert.strictEqual(err, error); done(); }); }); it('should return an error from getMetadata', done => { const error = new Error('Error.'); database.getMetadata = (options, callback) => { callback(error); }; database.get(err => { assert.strictEqual(err, error); done(); }); }); it('should return self and API response', done => { const apiResponse = {}; database.getMetadata = (options, callback) => { callback(null, apiResponse); }; database.get((err, database_, apiResponse_) => { assert.ifError(err); assert.strictEqual(database_, database); assert.strictEqual(apiResponse_, apiResponse); done(); }); }); }); describe('getMetadata', () => { it('should call and return the request', () => { const requestReturnValue = {}; database.request = config => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'getDatabase'); assert.deepStrictEqual(config.reqOpts, { name: database.formattedName_, }); assert.deepStrictEqual(config.gaxOpts, {}); assert.deepStrictEqual(config.headers, database.resourceHeader_); return requestReturnValue; }; const returnValue = database.getMetadata(assert.ifError); assert.strictEqual(returnValue, requestReturnValue); }); it('should accept gaxOptions', done => { const gaxOptions = {}; database.request = config => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; database.getMetadata(gaxOptions, assert.ifError); }); }); describe('getSchema', () => { it('should make the correct request', done => { database.request = config => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'getDatabaseDdl'); assert.deepStrictEqual(config.reqOpts, { database: database.formattedName_, }); assert.deepStrictEqual(config.gaxOpts, {}); assert.deepStrictEqual(config.headers, database.resourceHeader_); done(); }; database.getSchema(assert.ifError); }); it('should accept gaxOptions', done => { const gaxOptions = {}; database.request = config => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; database.getSchema(gaxOptions, assert.ifError); }); describe('error', () => { const ARG_1 = {}; const STATEMENTS_ARG = null; const ARG_3 = {}; const ARG_4 = {}; const ARG_5 = {}; beforeEach(() => { database.request = (config, callback) => { callback(ARG_1, STATEMENTS_ARG, ARG_3, ARG_4, ARG_5); }; }); it('should return the arguments from the request', done => { database.getSchema((arg1, arg2, arg3, arg4, arg5) => { assert.strictEqual(arg1, ARG_1); assert.strictEqual(arg2, STATEMENTS_ARG); assert.strictEqual(arg3, ARG_3); assert.strictEqual(arg4, ARG_4); assert.strictEqual(arg5, ARG_5); done(); }); }); }); describe('success', () => { const ARG_1 = {}; const ARG_3 = {}; const ARG_4 = {}; const ARG_5 = {}; const STATEMENTS_ARG = { statements: {}, }; beforeEach(() => { database.request = (config, callback) => { callback(ARG_1, STATEMENTS_ARG, ARG_3, ARG_4, ARG_5); }; }); it('should return just the statements property', done => { database.getSchema((arg1, statements, arg3, arg4, arg5) => { assert.strictEqual(arg1, ARG_1); assert.strictEqual(statements, STATEMENTS_ARG.statements); assert.strictEqual(arg3, ARG_3); assert.strictEqual(arg4, ARG_4); assert.strictEqual(arg5, ARG_5); done(); }); }); it('should update metadata', done => { const metadata = {}; database.request = (config: {}, callback: Function) => { callback(null, metadata); }; database.getMetadata(() => { assert.strictEqual(database.metadata, metadata); done(); }); }); it('should call callback with error', done => { const error = new Error('Error'); database.request = (config: {}, callback: Function) => { callback(error); }; database.getMetadata(err => { assert.strictEqual(err, error); done(); }); }); }); }); describe('makePooledRequest_', () => { let CONFIG; const SESSION = { formattedName_: 'formatted-name', }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const POOL: any = {}; beforeEach(() => { CONFIG = { reqOpts: {}, }; database.pool_ = POOL; POOL.getReadSession = callback => { callback(null, SESSION); }; POOL.release = util.noop; }); it('should get a session', done => { POOL.getReadSession = () => { done(); }; database.makePooledRequest_(CONFIG, assert.ifError); }); it('should return error if it cannot get a session', done => { const error = new Error('Error.'); POOL.getReadSession = callback => { callback(error); }; database.makePooledRequest_(CONFIG, err => { assert.strictEqual(err, error); done(); }); }); it('should call the method with the session', done => { CONFIG.reqOpts = { a: 'b', }; database.request = config => { assert.deepStrictEqual( config.reqOpts, extend({}, CONFIG.reqOpts, { session: SESSION.formattedName_, }) ); done(); }; database.makePooledRequest_(CONFIG, assert.ifError); }); it('should release the session after calling the method', done => { POOL.release = session => { assert.deepStrictEqual(session, SESSION); done(); }; database.request = (config, callback) => { callback(); }; database.makePooledRequest_(CONFIG, assert.ifError); }); it('should execute the callback with original arguments', done => { const originalArgs = ['a', 'b', 'c']; database.request = (config, callback) => { callback(...originalArgs); }; database.makePooledRequest_(CONFIG, (...args) => { assert.deepStrictEqual(args, originalArgs); done(); }); }); }); describe('makePooledStreamingRequest_', () => { let CONFIG; let REQUEST_STREAM; const SESSION = { formattedName_: 'formatted-name', }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const POOL: any = {}; beforeEach(() => { REQUEST_STREAM = through(); CONFIG = { reqOpts: {}, }; database.pool_ = POOL; database.requestStream = () => { return REQUEST_STREAM; }; POOL.getReadSession = callback => { callback(null, SESSION); }; POOL.release = util.noop; }); it('should get a session when stream opens', done => { POOL.getReadSession = () => { done(); }; database.makePooledStreamingRequest_(CONFIG).emit('reading'); }); describe('could not get session', () => { const ERROR = new Error('Error.'); beforeEach(() => { POOL.getReadSession = callback => { callback(ERROR); }; }); it('should destroy the stream', done => { database .makePooledStreamingRequest_(CONFIG) .on('error', err => { assert.strictEqual(err, ERROR); done(); }) .emit('reading'); }); }); describe('session retrieved successfully', () => { beforeEach(() => { POOL.getReadSession = callback => { callback(null, SESSION); }; }); it('should assign session to request options', done => { database.requestStream = config => { assert.strictEqual(config.reqOpts.session, SESSION.formattedName_); setImmediate(done); return through.obj(); }; database.makePooledStreamingRequest_(CONFIG).emit('reading'); }); it('should make request and pipe to the stream', done => { const responseData = Buffer.from('response-data'); database.makePooledStreamingRequest_(CONFIG).on('data', data => { assert.deepStrictEqual(data, responseData); done(); }); REQUEST_STREAM.end(responseData); }); it('should release session when request stream ends', done => { POOL.release = session => { assert.strictEqual(session, SESSION); done(); }; database.makePooledStreamingRequest_(CONFIG).emit('reading'); REQUEST_STREAM.end(); }); it('should release session when request stream errors', done => { POOL.release = session => { assert.strictEqual(session, SESSION); done(); }; database.makePooledStreamingRequest_(CONFIG).emit('reading'); setImmediate(() => { REQUEST_STREAM.emit('error'); }); }); it('should error user stream when request stream errors', done => { const error = new Error('Error.'); database .makePooledStreamingRequest_(CONFIG) .on('error', err => { assert.strictEqual(err, error); done(); }) .emit('reading'); setImmediate(() => { REQUEST_STREAM.destroy(error); }); }); }); describe('abort', () => { let SESSION; beforeEach(() => { REQUEST_STREAM.cancel = util.noop; SESSION = { cancel: util.noop, }; POOL.getReadSession = callback => { callback(null, SESSION); }; }); it('should release the session', done => { POOL.release = session => { assert.strictEqual(session, SESSION); done(); }; const requestStream = database.makePooledStreamingRequest_(CONFIG); requestStream.emit('reading'); setImmediate(() => { requestStream.abort(); }); }); it('should not release the session more than once', done => { let numTimesReleased = 0; POOL.release = session => { numTimesReleased++; assert.strictEqual(session, SESSION); }; const requestStream = database.makePooledStreamingRequest_(CONFIG); requestStream.emit('reading'); setImmediate(() => { requestStream.abort(); assert.strictEqual(numTimesReleased, 1); requestStream.abort(); assert.strictEqual(numTimesReleased, 1); done(); }); }); it('should cancel the request stream', done => { REQUEST_STREAM.cancel = done; const requestStream = database.makePooledStreamingRequest_(CONFIG); requestStream.emit('reading'); setImmediate(() => { requestStream.abort(); }); }); }); }); describe('run', () => { const QUERY = 'SELECT query FROM query'; let QUERY_STREAM; const ROW_1 = {}; const ROW_2 = {}; const ROW_3 = {}; beforeEach(() => { QUERY_STREAM = through.obj(); QUERY_STREAM.push(ROW_1); QUERY_STREAM.push(ROW_2); QUERY_STREAM.push(ROW_3); database.runStream = () => { return QUERY_STREAM; }; }); it('should correctly call runStream', done => { database.runStream = (query, options) => { assert.strictEqual(query, QUERY); assert.deepStrictEqual(options, {}); setImmediate(done); return QUERY_STREAM; }; database.run(QUERY, assert.ifError); }); it('should optionally accept options', done => { const OPTIONS = {}; database.runStream = (query, options) => { assert.strictEqual(options, OPTIONS); setImmediate(done); return QUERY_STREAM; }; database.run(QUERY, OPTIONS, assert.ifError); }); it('should return rows from the stream to the callback', done => { QUERY_STREAM.end(); database.run(QUERY, (err, rows) => { assert.ifError(err); assert.deepStrictEqual(rows, [ROW_1, ROW_2, ROW_3]); done(); }); }); it('should execute callback with error from stream', done => { const error = new Error('Error.'); QUERY_STREAM.destroy(error); database.run(QUERY, err => { assert.strictEqual(err, error); done(); }); }); }); describe('runStream', () => { const QUERY = { sql: 'SELECT * FROM table', a: 'b', c: 'd', }; let fakePool: FakeSessionPool; let fakeSession: FakeSession; let fakeSession2: FakeSession; let fakeSnapshot: FakeTransaction; let fakeSnapshot2: FakeTransaction; let fakeStream: Transform; let fakeStream2: Transform; let getReadSessionStub: sinon.SinonStub; let snapshotStub: sinon.SinonStub; let runStreamStub: sinon.SinonStub; beforeEach(() => { fakePool = database.pool_; fakeSession = new FakeSession(); fakeSession2 = new FakeSession(); fakeSnapshot = new FakeTransaction(); fakeSnapshot2 = new FakeTransaction(); fakeStream = through.obj(); fakeStream2 = through.obj(); getReadSessionStub = ( sandbox.stub(fakePool, 'getReadSession') as sinon.SinonStub ) .onFirstCall() .callsFake(callback => callback(null, fakeSession)) .onSecondCall() .callsFake(callback => callback(null, fakeSession2)); snapshotStub = sandbox .stub(fakeSession, 'snapshot') .returns(fakeSnapshot); sandbox.stub(fakeSession2, 'snapshot').returns(fakeSnapshot2); runStreamStub = sandbox .stub(fakeSnapshot, 'runStream') .returns(fakeStream); sandbox.stub(fakeSnapshot2, 'runStream').returns(fakeStream2); }); it('should get a read session via `getReadSession`', () => { getReadSessionStub.callsFake(() => {}); database.runStream(QUERY); assert.strictEqual(getReadSessionStub.callCount, 1); }); it('should destroy the stream if `getReadSession` errors', done => { const fakeError = new Error('err'); getReadSessionStub .onFirstCall() .callsFake(callback => callback(fakeError)); database.runStream(QUERY).on('error', err => { assert.strictEqual(err, fakeError); done(); }); }); it('should pass through timestamp bounds', () => { const fakeOptions = {strong: false}; database.runStream(QUERY, fakeOptions); const options = snapshotStub.lastCall.args[0]; assert.strictEqual(options, fakeOptions); }); it('should call through to `snapshot.runStream`', () => { const pipeStub = sandbox.stub(fakeStream, 'pipe'); const proxyStream = database.runStream(QUERY); const query = runStreamStub.lastCall.args[0]; assert.strictEqual(query, QUERY); const stream = pipeStub.lastCall.args[0]; assert.strictEqual(stream, proxyStream); }); it('should end the snapshot on stream end', done => { const endStub = sandbox.stub(fakeSnapshot, 'end'); database .runStream(QUERY) .on('data', done) .on('end', () => { assert.strictEqual(endStub.callCount, 1); done(); }); fakeStream.push(null); }); it('should clean up the stream/transaction on error', done => { const fakeError = new Error('err'); const endStub = sandbox.stub(fakeSnapshot, 'end'); database.runStream(QUERY).on('error', err => { assert.strictEqual(err, fakeError); assert.strictEqual(endStub.callCount, 1); done(); }); fakeStream.destroy(fakeError); }); it('should release the session on transaction end', () => { const releaseStub = sandbox.stub(fakePool, 'release') as sinon.SinonStub; database.runStream(QUERY); fakeSnapshot.emit('end'); const session = releaseStub.lastCall.args[0]; assert.strictEqual(session, fakeSession); }); it('should retry "Session not found" error', done => { const sessionNotFoundError = { code: grpc.status.NOT_FOUND, message: 'Session not found', } as grpc.ServiceError; const endStub = sandbox.stub(fakeSnapshot, 'end'); const endStub2 = sandbox.stub(fakeSnapshot2, 'end'); let rows = 0; database .runStream(QUERY) .on('data', () => rows++) .on('error', err => { assert.fail(err); }) .on('end', () => { assert.strictEqual(endStub.callCount, 1); assert.strictEqual(endStub2.callCount, 1); assert.strictEqual(rows, 1); done(); }); fakeStream.emit('error', sessionNotFoundError); fakeStream2.push('row1'); fakeStream2.push(null); }); }); describe('table', () => { const NAME = 'table-name'; it('should throw if a name is not provided', () => { assert.throws(() => { database.table(); }, /A name is required to access a Table object\./); }); it('should return an instance of Tession', () => { const table = database.table(NAME); assert(table instanceof FakeTable); assert.strictEqual(table.calledWith_[0], database); assert.strictEqual(table.calledWith_[1], NAME); }); }); describe('updateSchema', () => { const STATEMENTS = ['statement-1', 'statement-2']; it('should call and return the request', () => { const requestReturnValue = {}; database.request = (config, callback) => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'updateDatabaseDdl'); assert.deepStrictEqual(config.reqOpts, { database: database.formattedName_, statements: STATEMENTS, }); assert.deepStrictEqual(config.gaxOpts, {}); assert.deepStrictEqual(config.headers, database.resourceHeader_); assert.strictEqual(callback, assert.ifError); return requestReturnValue; }; const returnValue = database.updateSchema(STATEMENTS, assert.ifError); assert.strictEqual(returnValue, requestReturnValue); }); it('should arrify a string statement', done => { database.request = config => { assert.deepStrictEqual(config.reqOpts.statements, [STATEMENTS[0]]); done(); }; database.updateSchema(STATEMENTS[0], assert.ifError); }); it('should accept an object', done => { const config = { statements: STATEMENTS, otherConfiguration: {}, }; const expectedReqOpts = extend({}, config, { database: database.formattedName_, }); database.request = config => { assert.deepStrictEqual(config.reqOpts, expectedReqOpts); done(); }; database.updateSchema(config, assert.ifError); }); it('should accept gaxOptions', done => { const gaxOptions = {}; database.request = config => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; database.updateSchema(STATEMENTS, gaxOptions, assert.ifError); }); }); describe('createSession', () => { const gaxOptions = {}; const OPTIONS = {gaxOptions}; it('should make the correct request', done => { database.request = config => { assert.strictEqual(config.client, 'SpannerClient'); assert.strictEqual(config.method, 'createSession'); assert.deepStrictEqual(config.reqOpts, { database: database.formattedName_, }); assert.strictEqual(config.gaxOpts, gaxOptions); assert.deepStrictEqual(config.headers, database.resourceHeader_); done(); }; database.createSession(OPTIONS, assert.ifError); }); it('should not require options', done => { database.request = config => { assert.deepStrictEqual(config.reqOpts, { database: database.formattedName_, }); assert.strictEqual(config.gaxOpts, undefined); done(); }; database.createSession(assert.ifError); }); it('should send labels correctly', done => { const labels = {a: 'b'}; const options = {a: 'b', labels}; const originalOptions = extend(true, {}, options); database.request = config => { assert.deepStrictEqual(config.reqOpts.session, {labels}); assert.deepStrictEqual(options, originalOptions); done(); }; database.createSession({labels}, assert.ifError); }); describe('error', () => { const ERROR = new Error('Error.'); const API_RESPONSE = {}; beforeEach(() => { database.request = (config, callback) => { callback(ERROR, API_RESPONSE); }; }); it('should execute callback with error & API response', done => { database.createSession((err, session, apiResponse) => { assert.strictEqual(err, ERROR); assert.strictEqual(session, null); assert.strictEqual(apiResponse, API_RESPONSE); done(); }); }); }); describe('success', () => { const API_RESPONSE = { name: 'session-name', }; beforeEach(() => { database.request = (config, callback) => { callback(null, API_RESPONSE); }; }); it('should execute callback with session & API response', done => { const sessionInstance = {}; database.session = name => { assert.strictEqual(name, API_RESPONSE.name); return sessionInstance; }; database.createSession((err, session, apiResponse) => { assert.ifError(err); assert.strictEqual(session, sessionInstance); // eslint-disable-next-line @typescript-eslint/no-explicit-any assert.strictEqual((session as any).metadata, API_RESPONSE); assert.strictEqual(apiResponse, API_RESPONSE); done(); }); }); }); }); describe('getSnapshot', () => { let fakePool: FakeSessionPool; let fakeSession: FakeSession; let fakeSnapshot: FakeTransaction; let beginSnapshotStub: sinon.SinonStub; let getReadSessionStub: sinon.SinonStub; let snapshotStub: sinon.SinonStub; beforeEach(() => { fakePool = database.pool_; fakeSession = new FakeSession(); fakeSnapshot = new FakeTransaction(); beginSnapshotStub = ( sandbox.stub(fakeSnapshot, 'begin') as sinon.SinonStub ).callsFake(callback => callback(null)); getReadSessionStub = ( sandbox.stub(fakePool, 'getReadSession') as sinon.SinonStub ).callsFake(callback => callback(null, fakeSession)); snapshotStub = sandbox .stub(fakeSession, 'snapshot') .returns(fakeSnapshot); }); it('should call through to `SessionPool#getReadSession`', () => { getReadSessionStub.callsFake(() => {}); database.getSnapshot(assert.ifError); assert.strictEqual(getReadSessionStub.callCount, 1); }); it('should return any pool errors', done => { const fakeError = new Error('err'); getReadSessionStub.callsFake(callback => callback(fakeError)); database.getSnapshot(err => { assert.strictEqual(err, fakeError); done(); }); }); it('should pass the timestamp bounds to the snapshot', () => { const fakeTimestampBounds = {}; database.getSnapshot(fakeTimestampBounds, assert.ifError); const bounds = snapshotStub.lastCall.args[0]; assert.strictEqual(bounds, fakeTimestampBounds); }); it('should begin a snapshot', () => { beginSnapshotStub.callsFake(() => {}); database.getSnapshot(assert.ifError); assert.strictEqual(beginSnapshotStub.callCount, 1); }); it('should release the session if `begin` errors', done => { const fakeError = new Error('err'); beginSnapshotStub.callsFake(callback => callback(fakeError)); const releaseStub = ( sandbox.stub(fakePool, 'release') as sinon.SinonStub ).withArgs(fakeSession); database.getSnapshot(err => { assert.strictEqual(err, fakeError); assert.strictEqual(releaseStub.callCount, 1); done(); }); }); it('should retry if `begin` errors with `Session not found`', done => { const fakeError = { code: grpc.status.NOT_FOUND, message: 'Session not found', } as MockError; const fakeSession2 = new FakeSession(); const fakeSnapshot2 = new FakeTransaction(); (sandbox.stub(fakeSnapshot2, 'begin') as sinon.SinonStub).callsFake( callback => callback(null) ); sandbox.stub(fakeSession2, 'snapshot').returns(fakeSnapshot2); getReadSessionStub .onFirstCall() .callsFake(callback => callback(null, fakeSession)) .onSecondCall() .callsFake(callback => callback(null, fakeSession2)); beginSnapshotStub.callsFake(callback => callback(fakeError)); // The first session that was not found should be released back into the // pool, so that the pool can remove it from its inventory. const releaseStub = sandbox.stub(fakePool, 'release'); database.getSnapshot((err, snapshot) => { assert.ifError(err); assert.strictEqual(snapshot, fakeSnapshot2); // The first session that error should already have been released back // to the pool. assert.strictEqual(releaseStub.callCount, 1); // Ending the valid snapshot will release its session back into the // pool. snapshot.emit('end'); assert.strictEqual(releaseStub.callCount, 2); done(); }); }); it('should return the `snapshot`', done => { database.getSnapshot((err, snapshot) => { assert.ifError(err); assert.strictEqual(snapshot, fakeSnapshot); done(); }); }); it('should release the snapshot on `end`', done => { const releaseStub = ( sandbox.stub(fakePool, 'release') as sinon.SinonStub ).withArgs(fakeSession); database.getSnapshot(err => { assert.ifError(err); fakeSnapshot.emit('end'); assert.strictEqual(releaseStub.callCount, 1); done(); }); }); }); describe('getTransaction', () => { let fakePool: FakeSessionPool; let fakeSession: FakeSession; let fakeTransaction: FakeTransaction; let getWriteSessionStub: sinon.SinonStub; beforeEach(() => { fakePool = database.pool_; fakeSession = new FakeSession(); fakeTransaction = new FakeTransaction(); getWriteSessionStub = ( sandbox.stub(fakePool, 'getWriteSession') as sinon.SinonStub ).callsFake(callback => { callback(null, fakeSession, fakeTransaction); }); }); it('should get a read/write transaction', () => { getWriteSessionStub.callsFake(() => {}); database.getTransaction(assert.ifError); assert.strictEqual(getWriteSessionStub.callCount, 1); }); it('should return any pool errors', done => { const fakeError = new Error('err'); getWriteSessionStub.callsFake(callback => callback(fakeError)); database.getTransaction(err => { assert.strictEqual(err, fakeError); done(); }); }); it('should return the read/write transaction', done => { database.getTransaction((err, transaction) => { assert.ifError(err); assert.strictEqual(transaction, fakeTransaction); done(); }); }); it('should propagate an error', done => { const error = new Error('resource'); (sandbox.stub(fakePool, 'release') as sinon.SinonStub) .withArgs(fakeSession) .throws(error); database.on('error', err => { assert.deepStrictEqual(err, error); done(); }); database.getTransaction((err, transaction) => { assert.ifError(err); transaction.emit('end'); }); }); it('should release the session on transaction end', done => { const releaseStub = ( sandbox.stub(fakePool, 'release') as sinon.SinonStub ).withArgs(fakeSession); database.getTransaction((err, transaction) => { assert.ifError(err); transaction.emit('end'); assert.strictEqual(releaseStub.callCount, 1); done(); }); }); }); describe('getSessions', () => { it('should make the correct request', done => { const gaxOpts = {}; const options = {a: 'a', gaxOptions: gaxOpts}; const expectedReqOpts = extend({}, options, { database: database.formattedName_, }); delete expectedReqOpts.gaxOptions; database.request = config => { assert.strictEqual(config.client, 'SpannerClient'); assert.strictEqual(config.method, 'listSessions'); assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.deepStrictEqual(config.gaxOpts, gaxOpts); assert.deepStrictEqual(config.headers, database.resourceHeader_); done(); }; database.getSessions(options, assert.ifError); }); it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { const pageSize = 3; const pageToken = 'token'; const gaxOptions = {pageSize, pageToken, timeout: 1000}; const expectedGaxOpts = {timeout: 1000}; const options = {a: 'a', gaxOptions: gaxOptions}; const expectedReqOpts = extend( {}, options, { database: database.formattedName_, }, {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken} ); delete expectedReqOpts.gaxOptions; database.request = config => { assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.gaxOpts, gaxOptions); assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); done(); }; database.getSessions(options, assert.ifError); }); it('pageSize and pageToken in options should take precedence over gaxOptions', done => { const pageSize = 3; const pageToken = 'token'; const gaxOptions = {pageSize, pageToken, timeout: 1000}; const expectedGaxOpts = {timeout: 1000}; const optionsPageSize = 5; const optionsPageToken = 'optionsToken'; const options = Object.assign( {}, { pageSize: optionsPageSize, pageToken: optionsPageToken, gaxOptions, } ); const expectedReqOpts = extend( {}, options, { database: database.formattedName_, }, {pageSize: optionsPageSize, pageToken: optionsPageToken} ); delete expectedReqOpts.gaxOptions; database.request = config => { assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.gaxOpts, gaxOptions); assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); done(); }; database.getSessions(options, assert.ifError); }); it('should not require options', done => { database.request = config => { assert.deepStrictEqual(config.reqOpts, { database: database.formattedName_, }); assert.deepStrictEqual(config.gaxOpts, {}); done(); }; database.getSessions(assert.ifError); }); it('should return all arguments on error', done => { const ARGS = [new Error('err'), null, {}]; database.request = (config, callback) => { callback(...ARGS); }; database.getSessions((...args) => { assert.deepStrictEqual(args, ARGS); done(); }); }); it('should create and return Session objects', done => { const ERR = null; const SESSIONS = [{name: 'abc'}]; const NEXTPAGEREQUEST = null; const FULLAPIRESPONSE = {}; const SESSION_INSTANCE = {}; const RESPONSE = [ERR, SESSIONS, NEXTPAGEREQUEST, FULLAPIRESPONSE]; database.request = (config, callback) => { callback(...RESPONSE); }; database.session = name => { assert.strictEqual(name, SESSIONS[0].name); return SESSION_INSTANCE; }; database.getSessions((err, sessions, nextQuery, resp) => { assert.ifError(err); assert.strictEqual(sessions[0], SESSION_INSTANCE); assert.strictEqual(resp, FULLAPIRESPONSE); done(); }); }); it('should return a complete nexQuery object', done => { const pageSize = 1; const filter = 'filter'; const NEXTPAGEREQUEST = { database: database.formattedName_, pageSize, filter, pageToken: 'pageToken', }; const RESPONSE = [null, [], NEXTPAGEREQUEST, {}]; const GETSESSIONOPTIONS = { pageSize, filter, gaxOptions: {timeout: 1000, autoPaginate: false}, }; const EXPECTEDNEXTQUERY = extend({}, GETSESSIONOPTIONS, NEXTPAGEREQUEST); database.request = (config, callback) => { callback(...RESPONSE); }; function callback(err, sessions, nextQuery) { assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); done(); } database.getSessions(GETSESSIONOPTIONS, callback); }); }); describe('getSessionsStream', () => { const OPTIONS = { gaxOptions: {autoPaginate: false}, } as db.GetSessionsOptions; const returnValue = {} as Duplex; it('should make and return the correct gax API call', () => { const expectedReqOpts = extend({}, OPTIONS, { database: database.formattedName_, }); delete expectedReqOpts.gaxOptions; database.requestStream = config => { assert.strictEqual(config.client, 'SpannerClient'); assert.strictEqual(config.method, 'listSessionsStream'); assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.reqOpts, OPTIONS); assert.deepStrictEqual(config.gaxOpts, OPTIONS.gaxOptions); assert.deepStrictEqual(config.headers, database.resourceHeader_); return returnValue; }; const returnedValue = database.getSessionsStream(OPTIONS); assert.strictEqual(returnedValue, returnValue); }); it('should pass pageSize and pageToken from gaxOptions into reqOpts', () => { const pageSize = 3; const pageToken = 'token'; const gaxOptions = {pageSize, pageToken, timeout: 1000}; const expectedGaxOpts = {timeout: 1000}; const options = {gaxOptions}; const expectedReqOpts = extend( {}, { database: database.formattedName_, }, {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken} ); database.requestStream = config => { assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.gaxOpts, gaxOptions); assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); return returnValue; }; const returnedValue = database.getSessionsStream(options); assert.strictEqual(returnedValue, returnValue); }); it('pageSize and pageToken in options should take precedence over gaxOptions', () => { const pageSize = 3; const pageToken = 'token'; const gaxOptions = {pageSize, pageToken, timeout: 1000}; const expectedGaxOpts = {timeout: 1000}; const optionsPageSize = 5; const optionsPageToken = 'optionsToken'; const options = { pageSize: optionsPageSize, pageToken: optionsPageToken, gaxOptions, }; const expectedReqOpts = extend( {}, { database: database.formattedName_, }, {pageSize: optionsPageSize, pageToken: optionsPageToken} ); database.requestStream = config => { assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.gaxOpts, gaxOptions); assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); return returnValue; }; const returnedValue = database.getSessionsStream(options); assert.strictEqual(returnedValue, returnValue); }); it('should not require options', () => { database.requestStream = config => { assert.deepStrictEqual(config.reqOpts, { database: database.formattedName_, }); assert.deepStrictEqual(config.gaxOpts, {}); return returnValue; }; const returnedValue = database.getSessionsStream(); assert.strictEqual(returnedValue, returnValue); }); }); describe('runPartitionedUpdate', () => { const QUERY = { sql: 'INSERT INTO `MyTable` (Key, Thing) VALUES(@key, @thing)', params: { key: 'k999', thing: 'abc', }, }; let fakePool: FakeSessionPool; let fakeSession: FakeSession; let fakePartitionedDml: FakeTransaction; let getReadSessionStub; let beginStub; let runUpdateStub; beforeEach(() => { fakePool = database.pool_; fakeSession = new FakeSession(); fakePartitionedDml = new FakeTransaction(); getReadSessionStub = ( sandbox.stub(fakePool, 'getReadSession') as sinon.SinonStub ).callsFake(callback => { callback(null, fakeSession); }); sandbox.stub(fakeSession, 'partitionedDml').returns(fakePartitionedDml); beginStub = ( sandbox.stub(fakePartitionedDml, 'begin') as sinon.SinonStub ).callsFake(callback => callback(null)); runUpdateStub = ( sandbox.stub(fakePartitionedDml, 'runUpdate') as sinon.SinonStub ).callsFake((_, callback) => callback(null)); }); it('should get a read only session from the pool', () => { getReadSessionStub.callsFake(() => {}); database.runPartitionedUpdate(QUERY, assert.ifError); assert.strictEqual(getReadSessionStub.callCount, 1); }); it('should return any pool errors', () => { const fakeError = new Error('err'); const fakeCallback = sandbox.spy(); getReadSessionStub.callsFake(callback => callback(fakeError)); database.runPartitionedUpdate(QUERY, fakeCallback); const [err, rowCount] = fakeCallback.lastCall.args; assert.strictEqual(err, fakeError); assert.strictEqual(rowCount, 0); }); it('should call transaction begin', () => { beginStub.callsFake(() => {}); database.runPartitionedUpdate(QUERY, assert.ifError); assert.strictEqual(beginStub.callCount, 1); }); it('should return any begin errors', done => { const fakeError = new Error('err'); beginStub.callsFake(callback => callback(fakeError)); const releaseStub = ( sandbox.stub(fakePool, 'release') as sinon.SinonStub ).withArgs(fakeSession); database.runPartitionedUpdate(QUERY, (err, rowCount) => { assert.strictEqual(err, fakeError); assert.strictEqual(rowCount, 0); assert.strictEqual(releaseStub.callCount, 1); done(); }); }); it('call `runUpdate` on the transaction', () => { const fakeCallback = sandbox.spy(); database.runPartitionedUpdate(QUERY, fakeCallback); const [query] = runUpdateStub.lastCall.args; assert.strictEqual(query, QUERY); assert.ok(fakeCallback.calledOnce); }); it('should release the session on transaction end', () => { const releaseStub = ( sandbox.stub(fakePool, 'release') as sinon.SinonStub ).withArgs(fakeSession); database.runPartitionedUpdate(QUERY, assert.ifError); fakePartitionedDml.emit('end'); assert.strictEqual(releaseStub.callCount, 1); }); it('should accept requestOptions', () => { const fakeCallback = sandbox.spy(); database.runPartitionedUpdate( { sql: QUERY.sql, params: QUERY.params, requestOptions: {priority: RequestOptions.Priority.PRIORITY_LOW}, }, fakeCallback ); const [query] = runUpdateStub.lastCall.args; assert.deepStrictEqual(query, { sql: QUERY.sql, params: QUERY.params, requestOptions: {priority: RequestOptions.Priority.PRIORITY_LOW}, }); assert.ok(fakeCallback.calledOnce); }); }); describe('runTransaction', () => { const SESSION = new FakeSession(); const TRANSACTION = new FakeTransaction(); let pool: FakeSessionPool; beforeEach(() => { pool = database.pool_; (sandbox.stub(pool, 'getWriteSession') as sinon.SinonStub).callsFake( callback => { callback(null, SESSION, TRANSACTION); } ); }); it('should return any errors getting a session', done => { const fakeErr = new Error('err'); (pool.getWriteSession as sinon.SinonStub).callsFake(callback => callback(fakeErr) ); database.runTransaction(err => { assert.strictEqual(err, fakeErr); done(); }); }); it('should create a `TransactionRunner`', () => { const fakeRunFn = sandbox.spy(); database.runTransaction(fakeRunFn); const [session, transaction, runFn, options] = fakeTransactionRunner.calledWith_; assert.strictEqual(session, SESSION); assert.strictEqual(transaction, TRANSACTION); assert.strictEqual(runFn, fakeRunFn); assert.deepStrictEqual(options, {}); }); it('should optionally accept runner `options`', () => { const fakeOptions = {timeout: 1}; database.runTransaction(fakeOptions, assert.ifError); const options = fakeTransactionRunner.calledWith_[3]; assert.strictEqual(options, fakeOptions); }); it('should release the session when finished', done => { const releaseStub = ( sandbox.stub(pool, 'release') as sinon.SinonStub ).withArgs(SESSION); sandbox.stub(FakeTransactionRunner.prototype, 'run').resolves(); database.runTransaction(assert.ifError); setImmediate(() => { assert.strictEqual(releaseStub.callCount, 1); done(); }); }); it('should catch any run errors and return them', done => { const releaseStub = ( sandbox.stub(pool, 'release') as sinon.SinonStub ).withArgs(SESSION); const fakeError = new Error('err'); sandbox.stub(FakeTransactionRunner.prototype, 'run').rejects(fakeError); database.runTransaction(err => { assert.strictEqual(err, fakeError); assert.strictEqual(releaseStub.callCount, 1); done(); }); }); }); describe('runTransactionAsync', () => { const SESSION = new FakeSession(); const TRANSACTION = new FakeTransaction(); let pool: FakeSessionPool; beforeEach(() => { pool = database.pool_; (sandbox.stub(pool, 'getWriteSession') as sinon.SinonStub).callsFake( callback => { callback(null, SESSION, TRANSACTION); } ); }); it('should create an `AsyncTransactionRunner`', async () => { const fakeRunFn = sandbox.spy(); await database.runTransactionAsync(fakeRunFn); const [session, transaction, runFn, options] = fakeAsyncTransactionRunner.calledWith_; assert.strictEqual(session, SESSION); assert.strictEqual(transaction, TRANSACTION); assert.strictEqual(runFn, fakeRunFn); assert.deepStrictEqual(options, {}); }); it('should optionally accept runner `options`', async () => { const fakeOptions = {timeout: 1}; await database.runTransactionAsync(fakeOptions, assert.ifError); const options = fakeAsyncTransactionRunner.calledWith_[3]; assert.strictEqual(options, fakeOptions); }); it('should return the runners resolved value', async () => { const fakeValue = {}; sandbox .stub(FakeAsyncTransactionRunner.prototype, 'run') .resolves(fakeValue); const value = await database.runTransactionAsync(assert.ifError); assert.strictEqual(value, fakeValue); }); it('should release the session when finished', async () => { const releaseStub = ( sandbox.stub(pool, 'release') as sinon.SinonStub ).withArgs(SESSION); sandbox.stub(FakeAsyncTransactionRunner.prototype, 'run').resolves(); await database.runTransactionAsync(assert.ifError); assert.strictEqual(releaseStub.callCount, 1); }); }); describe('session', () => { const NAME = 'session-name'; it('should return an instance of Session', () => { const session = database.session(NAME); assert(session instanceof FakeSession); assert.strictEqual(session.calledWith_[0], database); assert.strictEqual(session.calledWith_[1], NAME); }); }); describe('getState', () => { it('should get state from database metadata', async () => { database.getMetadata = async () => [{state: 'READY'}]; const result = await database.getState(); assert.strictEqual(result, 'READY'); }); it('should accept and pass gaxOptions to getMetadata', async () => { const options = {}; database.getMetadata = async gaxOptions => { assert.strictEqual(gaxOptions, options); return [{}]; }; await database.getState(options); }); it('should accept callback and return state', done => { const state = 'READY'; database.getMetadata = async () => [{state}]; database.getState((err, result) => { assert.ifError(err); assert.strictEqual(result, state); done(); }); }); }); describe('getRestoreInfo', () => { it('should get restore info from database metadata', async () => { const restoreInfo = {sourceType: 'BACKUP'}; database.getMetadata = async () => [{restoreInfo}]; const result = await database.getRestoreInfo(); assert.deepStrictEqual(result, restoreInfo); }); it('should accept and pass gaxOptions to getMetadata', async () => { const options = {}; database.getMetadata = async gaxOptions => { assert.strictEqual(gaxOptions, options); return [{}]; }; await database.getRestoreInfo(options); }); it('should accept callback and return info', done => { const restoreInfo = {sourceType: 'BACKUP'}; database.getMetadata = async () => [{restoreInfo}]; database.getRestoreInfo((err, result) => { assert.ifError(err); assert.strictEqual(result, restoreInfo); done(); }); }); }); describe('getOperations', () => { it('should create filter for querying the database', async () => { const operations: IOperation[] = [{name: 'my-operation'}]; database.instance.getDatabaseOperations = async options => { assert.strictEqual(options.filter, `name:${DATABASE_FORMATTED_NAME}`); return [operations, {}]; }; const [results] = await database.getOperations(); assert.deepStrictEqual(results, operations); }); it('should create filter for querying the database in combination with user supplied filter', async () => { const operations: IOperation[] = [{name: 'my-operation'}]; database.instance.getDatabaseOperations = async options => { assert.strictEqual( options.filter, `(name:${DATABASE_FORMATTED_NAME}) AND (someOtherAttribute: aValue)` ); return [operations, {}]; }; const [results] = await database.getOperations({ filter: 'someOtherAttribute: aValue', }); assert.deepStrictEqual(results, operations); }); it('should accept options with given gaxOptions', async () => { const operations: IOperation[] = [{name: 'my-operation'}]; const gaxOpts = { timeout: 1000, }; database.instance.getDatabaseOperations = async options => { assert.strictEqual(options.gaxOptions, gaxOpts); return [operations, {}]; }; const [results] = await database.getOperations({ filter: 'someOtherAttribute: aValue', gaxOptions: gaxOpts, }); assert.deepStrictEqual(results, operations); }); it('should accept callback', done => { const operations: IOperation[] = [{name: 'my-operation'}]; database.instance.getDatabaseOperations = async () => [operations, {}]; database.getOperations((err, results) => { assert.ifError(err); assert.deepStrictEqual(results, operations); done(); }); }); }); describe('restore', () => { const BACKUP_NAME = 'backup-name'; const BACKUP_FORMATTED_NAME = INSTANCE.formattedName_ + '/backups/' + BACKUP_NAME; it('should make the correct request', done => { const QUERY = {}; const ORIGINAL_QUERY = extend({}, QUERY); const expectedReqOpts = extend({}, QUERY, { databaseId: NAME, parent: INSTANCE.formattedName_, backup: BACKUP_FORMATTED_NAME, }); database.id = NAME; database.request = config => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'restoreDatabase'); assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.reqOpts, QUERY); assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); assert.deepStrictEqual(config.gaxOpts, {}); assert.deepStrictEqual(config.headers, database.resourceHeader_); done(); }; database.restore(BACKUP_FORMATTED_NAME, assert.ifError); }); it('should accept a backup name', done => { const QUERY = {}; const expectedReqOpts = extend({}, QUERY, { databaseId: NAME, parent: INSTANCE.formattedName_, backup: BACKUP_FORMATTED_NAME, }); database.id = NAME; database.request = config => { assert.deepStrictEqual(config.reqOpts, expectedReqOpts); done(); }; database.restore(BACKUP_NAME, assert.ifError); }); it('should accept restore options', done => { const encryptionConfig = { encryptionType: EncryptionType.CUSTOMER_MANAGED_ENCRYPTION, kmsKeyName: 'some/key/path', }; const options = {encryptionConfig}; database.request = config => { assert.deepStrictEqual( config.reqOpts.encryptionConfig, encryptionConfig ); done(); }; database.restore(BACKUP_NAME, options, assert.ifError); }); it('should accept gaxOpts as CallOptions', done => { const gaxOptions = {timeout: 1000}; database.request = config => { assert.deepStrictEqual(config.gaxOpts, gaxOptions); done(); }; database.restore(BACKUP_NAME, gaxOptions, assert.ifError); }); it('should accept restore and gax options', done => { const encryptionConfig = { encryptionType: EncryptionType.CUSTOMER_MANAGED_ENCRYPTION, kmsKeyName: 'some/key/path', }; const gaxOptions = {timeout: 1000}; const options = {gaxOptions, encryptionConfig}; database.request = config => { assert.deepStrictEqual( config.reqOpts.encryptionConfig, encryptionConfig ); assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); done(); }; database.restore(BACKUP_NAME, options, assert.ifError); }); describe('error', () => { const ERROR = new Error('Error.'); const API_RESPONSE = {}; beforeEach(() => { database.request = (config, callback: Function) => { callback(ERROR, null, API_RESPONSE); }; }); it('should execute callback with error & API response', done => { database.restore(BACKUP_FORMATTED_NAME, (err, db, op, resp) => { assert.strictEqual(err, ERROR); assert.strictEqual(db, null); assert.strictEqual(op, null); assert.strictEqual(resp, API_RESPONSE); done(); }); }); }); describe('success', () => { const OPERATION = {}; const API_RESPONSE = {}; beforeEach(() => { database.request = (config, callback: Function) => { callback(null, OPERATION, API_RESPONSE); }; }); it('should execute callback with a Database and Operation', done => { database.restore(BACKUP_FORMATTED_NAME, (err, db, op, resp) => { assert.ifError(err); assert.strictEqual(db, database); assert.strictEqual(op, OPERATION); assert.strictEqual(resp, API_RESPONSE); done(); }); }); }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormMarketing_List { interface Header extends DevKit.Controls.IHeader { /** Shows the date and time when the marketing list was last used in a campaign or in the creation of activities or opportunities. */ LastUsedOn: DevKit.Controls.Date; /** Select whether the marketing list is locked. If Yes is selected, no additional members can be added to the marketing list. */ LockStatus: DevKit.Controls.Boolean; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab_members_Sections { listoperationssection: DevKit.Controls.Section; members: DevKit.Controls.Section; } interface tab_notes_Sections { notes: DevKit.Controls.Section; } interface tab_Summary_Sections { campaigns: DevKit.Controls.Section; information: DevKit.Controls.Section; quickcampaigns: DevKit.Controls.Section; } interface tab_members extends DevKit.Controls.ITab { Section: tab_members_Sections; } interface tab_notes extends DevKit.Controls.ITab { Section: tab_notes_Sections; } interface tab_Summary extends DevKit.Controls.ITab { Section: tab_Summary_Sections; } interface Tabs { members: tab_members; notes: tab_notes; Summary: tab_Summary; } interface Body { Tab: Tabs; /** Type the cost of obtaining the marketing list. */ Cost: DevKit.Controls.Money; /** Select the type of members that this marketing list will contain: accounts, contacts, or leads. Each list can have only one member type and this value can't be changed after the marketing list is created. */ CreatedFromCode: DevKit.Controls.OptionSet; /** Type additional information to describe the marketing list, such as the intended use or date of the last update. */ Description: DevKit.Controls.String; /** Shows the date and time when the marketing list was last used in a campaign or in the creation of activities or opportunities. */ LastUsedOn: DevKit.Controls.Date; /** Type a name for the marketing list so that it is identified correctly in lists. */ ListName: DevKit.Controls.String; /** Select whether the marketing list is locked. If Yes is selected, no additional members can be added to the marketing list. */ LockStatus: DevKit.Controls.Boolean; /** Type of the members that can be stored in the marketing list. Please do not remove from form! */ MemberType: DevKit.Controls.Integer; /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Type the intended use of the marketing list to identify its key segments, target offers, or business group. */ Purpose: DevKit.Controls.String; /** Query used for retrieving members of marketing list. */ Query: DevKit.Controls.String; /** Type the source of the marketing list, such as a third-party supplier or internal database. */ Source: DevKit.Controls.String; /** Shows whether the marketing list is active or inactive. Inactive marketing lists are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.Controls.OptionSet; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Select whether you want the marketing list to be static or dynamic. The members in a static marketing list are unchanging. A dynamic marketing list is based on a dynamic query that retrieves the updated list of members */ Type: DevKit.Controls.Boolean; } interface Grid { Campaigns: DevKit.Controls.Grid; QuickCampaigns: DevKit.Controls.Grid; accountsUCI: DevKit.Controls.Grid; contacts: DevKit.Controls.Grid; accounts: DevKit.Controls.Grid; leads: DevKit.Controls.Grid; contactsUCI: DevKit.Controls.Grid; leadsUCI: DevKit.Controls.Grid; dynamic_accounts: DevKit.Controls.Grid; dynamic_contacts: DevKit.Controls.Grid; dynamic_leads: DevKit.Controls.Grid; ListOperationsSubGrid: DevKit.Controls.Grid; } } class FormMarketing_List extends DevKit.IForm { /** * DynamicsCrm.DevKit form Marketing_List * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Marketing_List */ Body: DevKit.FormMarketing_List.Body; /** The Header section of form Marketing_List */ Header: DevKit.FormMarketing_List.Header; /** The Grid of form Marketing_List */ Grid: DevKit.FormMarketing_List.Grid; } namespace FormMarketing_List_Light { interface Header extends DevKit.Controls.IHeader { /** Shows the date and time when the marketing list was last used in a campaign or in the creation of activities or opportunities. */ LastUsedOn: DevKit.Controls.Date; /** Select whether the marketing list is locked. If Yes is selected, no additional members can be added to the marketing list. */ LockStatus: DevKit.Controls.Boolean; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab_notes_Sections { notes: DevKit.Controls.Section; } interface tab_Summary_Sections { campaigns: DevKit.Controls.Section; information: DevKit.Controls.Section; members: DevKit.Controls.Section; quickcampaigns: DevKit.Controls.Section; Summary_section_4: DevKit.Controls.Section; Summary_section_5: DevKit.Controls.Section; } interface tab_notes extends DevKit.Controls.ITab { Section: tab_notes_Sections; } interface tab_Summary extends DevKit.Controls.ITab { Section: tab_Summary_Sections; } interface Tabs { notes: tab_notes; Summary: tab_Summary; } interface Body { Tab: Tabs; /** Type the cost of obtaining the marketing list. */ Cost: DevKit.Controls.Money; /** Select the type of members that this marketing list will contain: accounts, contacts, or leads. Each list can have only one member type and this value can't be changed after the marketing list is created. */ CreatedFromCode: DevKit.Controls.OptionSet; /** Type additional information to describe the marketing list, such as the intended use or date of the last update. */ Description: DevKit.Controls.String; /** Shows the date and time when the marketing list was last used in a campaign or in the creation of activities or opportunities. */ LastUsedOn: DevKit.Controls.Date; /** Type a name for the marketing list so that it is identified correctly in lists. */ ListName: DevKit.Controls.String; /** Select whether the marketing list is locked. If Yes is selected, no additional members can be added to the marketing list. */ LockStatus: DevKit.Controls.Boolean; /** Type of the members that can be stored in the marketing list. Please do not remove from form! */ MemberType: DevKit.Controls.Integer; /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Type the intended use of the marketing list to identify its key segments, target offers, or business group. */ Purpose: DevKit.Controls.String; /** Query used for retrieving members of marketing list. */ Query: DevKit.Controls.String; /** Type the source of the marketing list, such as a third-party supplier or internal database. */ Source: DevKit.Controls.String; /** Shows whether the marketing list is active or inactive. Inactive marketing lists are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.Controls.OptionSet; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Select whether you want the marketing list to be static or dynamic. The members in a static marketing list are unchanging. A dynamic marketing list is based on a dynamic query that retrieves the updated list of members */ Type: DevKit.Controls.Boolean; } interface Grid { accountsUCI: DevKit.Controls.Grid; contactsUCI: DevKit.Controls.Grid; leadsUCI: DevKit.Controls.Grid; contacts: DevKit.Controls.Grid; accounts: DevKit.Controls.Grid; leads: DevKit.Controls.Grid; dynamic_accounts: DevKit.Controls.Grid; dynamic_contacts: DevKit.Controls.Grid; dynamic_leads: DevKit.Controls.Grid; Campaigns: DevKit.Controls.Grid; QuickCampaigns: DevKit.Controls.Grid; } } class FormMarketing_List_Light extends DevKit.IForm { /** * DynamicsCrm.DevKit form Marketing_List_Light * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Marketing_List_Light */ Body: DevKit.FormMarketing_List_Light.Body; /** The Header section of form Marketing_List_Light */ Header: DevKit.FormMarketing_List_Light.Header; /** The Grid of form Marketing_List_Light */ Grid: DevKit.FormMarketing_List_Light.Grid; } class ListApi { /** * DynamicsCrm.DevKit ListApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Type the cost of obtaining the marketing list. */ Cost: DevKit.WebApi.MoneyValue; /** Value of the Cost in base currency. */ Cost_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Select the type of members that this marketing list will contain: accounts, contacts, or leads. Each list can have only one member type and this value can't be changed after the marketing list is created. */ CreatedFromCode: DevKit.WebApi.OptionSetValue; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type additional information to describe the marketing list, such as the intended use or date of the last update. */ Description: DevKit.WebApi.StringValue; /** Select whether to override the opt-out settings on leads, contacts, and accounts for the members of the target marketing lists of the campaign activity. If No is selected, those who have chosen to opt out won't be excluded from the list. This means they will receive marketing materials. */ DoNotSendOnOptOut: DevKit.WebApi.BooleanValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Select whether inactive accounts, contacts, or leads should be excluded from the campaign activity distribution when the marketing list is included in a campaign. */ IgnoreInactiveListMembers: DevKit.WebApi.BooleanValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Shows the date and time when the marketing list was last used in a campaign or in the creation of activities or opportunities. */ LastUsedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the marketing list. */ ListId: DevKit.WebApi.GuidValue; /** Type a name for the marketing list so that it is identified correctly in lists. */ ListName: DevKit.WebApi.StringValue; /** Select whether the marketing list is locked. If Yes is selected, no additional members can be added to the marketing list. */ LockStatus: DevKit.WebApi.BooleanValue; /** Shows the sum of all members in the marketing list. */ MemberCount: DevKit.WebApi.IntegerValue; /** Type of the members that can be stored in the marketing list. Please do not remove from form! */ MemberType: DevKit.WebApi.IntegerValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; processedMemberCount: DevKit.WebApi.IntegerValue; processFetchXML: DevKit.WebApi.StringValue; /** Contains the id of the process associated with the entity. */ ProcessId: DevKit.WebApi.GuidValue; /** Type the intended use of the marketing list to identify its key segments, target offers, or business group. */ Purpose: DevKit.WebApi.StringValue; /** Query used for retrieving members of marketing list. */ Query: DevKit.WebApi.StringValue; /** Type the source of the marketing list, such as a third-party supplier or internal database. */ Source: DevKit.WebApi.StringValue; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the marketing list is active or inactive. Inactive marketing lists are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the marketing list's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ TraversedPath: DevKit.WebApi.StringValue; /** Select whether you want the marketing list to be static or dynamic. The members in a static marketing list are unchanging. A dynamic marketing list is based on a dynamic query that retrieves the updated list of members */ Type: DevKit.WebApi.BooleanValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace List { enum CreatedFromCode { /** 1 */ Account, /** 2 */ Contact, /** 4 */ Lead } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 0 */ Active, /** 1 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Marketing List','Marketing List Light'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
//////////////////////////////////////////////////////////////////////////////// // // General utility types // //////////////////////////////////////////////////////////////////////////////// declare type StringDict = { [key: string]: string }; //////////////////////////////////////////////////////////////////////////////// // // gmail.tracker // //////////////////////////////////////////////////////////////////////////////// interface GmailTracker { globals: any[]; view_data: any[]; ik: string; hangouts: any; events: {}[]; actions: {}[]; watchdog: { before: {}, on: {}, after: {}, dom: {} }; } //////////////////////////////////////////////////////////////////////////////// // // gmail.get // //////////////////////////////////////////////////////////////////////////////// declare type GmailPageType = 'sent' | 'inbox' | 'starred' | 'drafts' | 'imp' | 'chats' | 'all' | 'spam' | 'trash' | 'settings' | 'label' | 'category' | 'circle' | 'search'; /** First element is name. Second element is smtp-address. */ declare type GmailEmailAddress = string[]; declare type GmailDomComposeRecipients = { to: string[]; cc: string[]; bcc: string[]; } declare type GmailAttachmentDetails = { attachment_id: string, name: string, type: string, size: number, url: string }; declare type GmailEmailDetails = { is_deleted: boolean, reply_to: string, reply_to_id: string, from: string, from_email: string, timestamp: number, datetime: string, attachments: string[], attachments_details: GmailAttachmentDetails[], subject: string, content_html: string, content_plain: string, to: string[], cc: string[], bcc: string[] }; declare type GmailEmailData = { thread_id: string, first_email: string, last_email: string, total_emails: number, total_threads: string[], people_involved: GmailEmailAddress[]; subject: string; threads: { [id: string]: GmailEmailDetails }; }; declare type GmailLastActive = { time: string, ip: string, mac_address: string, time_relative: string }; declare type GmailLoggedInAccount = { name: string, email: string, index: number }; declare type GmailStorageInfo = { used: string, total: string, percent: number }; interface GmailGet { /** Gets user's account activity data */ last_active(): GmailLastActive; /** Returns a list of signed-in accounts (multiple user accounts setup in gmail) */ loggedin_accounts(): GmailLoggedInAccount[]; /** Returns the current user's email address */ user_email(): string; /** Returns the email address of the user currently managing the account (if the inbox is used by the owner, this function returns the same value as gmail.get.user_email()) */ manager_email(): string; /** Returns the email address of the user the account is currently delegated to (if the inbox is used by the owner, this function returns null) */ delegated_to_email(): string; /** Returns the Gmail localization, e.g. 'US'. */ localization(): string; /** Returns current user's file storage stats */ storage_info(): GmailStorageInfo; email_ids(): string[]; /** Returns the latest/last email id of emails that have been saved as drafts (currently open) */ compose_ids(): string[]; /** Gets current email-thread's ID */ thread_id(): string; /** Gets current email-thread's ID */ email_id(): string; /** Returns the opened email's subject from the DOM */ email_subject(): string; /** Returns the search bar data */ search_query(): string; unread_inbox_emails(): number; unread_draft_emails(): number; unread_spam_emails(): number; unread_forum_emails(): number; unread_update_emails(): number; unread_promotion_emails(): number; unread_social_emails(): number; /** Although hand picked, this method returns the checks on beta features and deployments */ beta(): { [feature: string]: boolean; }; /** Returns a count of total unread emails for the current account. You can also request the data individually using: gmail.get.unread_inbox_emails() gmail.get.unread_draft_emails() gmail.get.unread_spam_emails() gmail.get.unread_forum_emails() gmail.get.unread_update_emails() gmail.get.unread_promotion_emails() gmail.get.unread_social_emails() */ unread_emails(): { inbox: boolean; drafts: boolean; spam: boolean; forum: boolean; update: boolean; promotions: boolean; social: boolean; }; /** Returns a list of emails from the server that are currently visible in the inbox view. The data does not come from the DOM */ visible_emails(): string[]; /** Does the same as visible_emails, but with a callback instead. */ visible_emails_async(callback: (emails: string[]) => void): void; /** Returns a list of object representation from emails that are currently selected in the inbox view. The data does not come from the DOM */ selected_emails_data(): GmailEmailData[]; /** Returns what page of gmail the user is currently on. */ current_page(): GmailPageType; /** Returns an object representation of the opened email contents and metadata. It takes the optional thread_id parameter where the data for the specified id is returned instead of the email currently visible in the dom. thread_id is added for updated gmail thread behaviour which adds support for emails created in inbox. first_email remains as the first message in the thread. */ email_data(thread_id?: string): GmailEmailData; /** Does the same as email_data but accepts a callback function */ email_data_async(email_id: string, callback: (email_data: GmailEmailData) => void): void; /** Deprecated function. Migrate to `email_source_async` or `email_source_promise`! */ email_source(identifier: GmailEmailIdentifier): string; /** Retrieves raw MIME message source from the gmail server for the specified email id. It takes the optional email_id parameter where the data for the specified id is returned instead of the email currently visible in the dom. The `callback` is invoked with the resulting data in either string or binary format depending on the value of the `preferBinary`-parameter. */ email_source_async(identifier: GmailEmailIdentifier, callback: (email_source: string | Uint8Array) => void, error_callback?: (jqxhr: JQueryXHR, textStatus: string, errorThrown: string) => void, preferBinary?: boolean): void; /** Does the same as email_source_async, but uses ES6 promises. */ email_source_promise(identifier: GmailEmailIdentifier): Promise<string>; email_source_promise(identifier: GmailEmailIdentifier, preferBinary: boolean): Promise<Uint8Array>; /** Retrieves the a email/thread data from the server that is currently visible. The data does not come from the DOM. */ displayed_email_data(): GmailEmailData; /** Does the same as displayed_email_data, but with a callback instead. */ displayed_email_data_async(callback: (gmailEmailData: GmailEmailData) => void): void; } //////////////////////////////////////////////////////////////////////////////// // // gmail.check // //////////////////////////////////////////////////////////////////////////////// interface GmailCheck { /** Returns True if the user is running Gmail with the new 2018 data-layer */ is_new_data_layer(): boolean; /** Returns True if the user is running Gmail with the new 2018 GUI */ is_new_gui(): boolean; /** Returns True if the conversation is threaded False otherwise */ is_thread(): boolean; /** Returns True if gmail is in split pane mode (vertical or horizontal) False otherwise */ is_preview_pane(): boolean; /** Returns True if user has multiple inbox lab enabled, False otherwise */ is_multiple_inbox(): boolean; /** Returns True if the pane split mode is horiontal False otherwise */ is_horizontal_split(): boolean; /** Returns True if the pane mode is vertical False otherwise */ is_vertical_split(): boolean; /** Returns True if tabbed inbox view is enabled False otherwise */ is_tabbed_inbox(): boolean; /** Returns True if chat is on the right sidebar False otherwise */ is_right_side_chat(): boolean; /** Returns True if compose is in fullscreen mode False otherwise */ should_compose_fullscreen(): boolean; /** Returns True if the current user is google apps user (email not ending in gmail.com) False otherwise gmail.check.is_inside_email() */ is_google_apps_user(): boolean; /** Returns True if you are currently inside an email conversation False otherwise */ is_inside_email(): boolean; /** Returns True if compose is in plain text mode, False if in rich text mode */ is_plain_text(): boolean; /** Returns True if priority inbox is enabled False otherwise */ is_priority_inbox(): boolean; /** Returns True if rapportive chrome extension is installed False otherwise */ is_rapportive_installed(): boolean; /** Returns True if streak chrome extension is installed False otherwise */ is_streak_installed(): boolean; /** Returns True if any.do chrome extension is installed False otherwise */ is_anydo_installed(): boolean; /** Returns True if boomerang chrome extension is installed False otherwise */ is_boomerang_installed(): boolean; /** Returns True if xobni chrome extension is installed False otherwise */ is_xobni_installed(): boolean; /** Returns True if Signal chrome extension is installed False otherwise */ is_signal_installed(): boolean; /** Returns True if user has enabled mail action shortcuts, False otherwise */ are_shortcuts_enabled(): boolean; /** Returns True if emails are displayed as threads, False otherwise (i.e. displayed individually) */ is_conversation_view(): boolean; data: { is_email_id(email_id: string): boolean; is_thread_id(email_id: string): boolean; is_legacy_email_id(email_id: string): boolean; } } //////////////////////////////////////////////////////////////////////////////// // // gmail.dom // //////////////////////////////////////////////////////////////////////////////// interface GmailDomEmailEntry { el?: JQuery, email: string, name: string } declare type GmailDomThreadLookup = "opened_email" | "subject" | "labels"; interface GmailDomThread { $el: JQuery, /** Retrieve preconfigured dom elements for this email */ dom(lookup: GmailDomThreadLookup): JQuery, } interface GmailDomAttachment { $el: JQuery, type?: string, name: string, size: string, url?: string } declare type GmailDomEmailLookup = "body" | "from" | "to" | "to_wrapper" | "timestamp" | "star" | "reply_button" | "menu_button" | "details_button" | "attachments"; interface GmailDomEmail { $el: JQuery, id: string, id_element: JQuery, /** Get/Set the full email body as it sits in the DOM If you want the actual DOM element use .dom('body'); Note: This gets & sets the body html after it has been parsed & marked up by GMAIL. To retrieve it as it exists in the email message source, use a call to .data(); */ body(body?: string): string; /** Get/Set the sender Optionally receives email and name properties. If received updates the values in the DOM Returns an object containing email & name of the sender and dom element */ from(email?: string, name?: string): GmailDomEmailEntry; /** Get/Set who the email is showing as To Optionally receives an object containing email and/or name properties. If received updates the values in the DOM. Optionally receives an array of these objects if multiple recipients Returns an array of objects containing email & name of who is showing in the DOM as the email is to */ to(to_array: GmailDomEmailEntry | GmailDomEmailEntry[]): GmailDomEmailEntry[]; /** Retries the DOM elements which represents the emails attachments Returns undefined if UI-elements are not yet ready for parsing. */ attachments(): GmailDomAttachment[]; /** Retrieve relevant email from the Gmail servers for this email Makes use of the gmail.get.email_data() method Returns an object */ data(): GmailEmailData, /** Retrieve email source for this email from the Gmail servers Makes use of the gmail.get.email_source() method Returns string of email raw source */ source(): string, /** Retrieve preconfigured dom elements for this email */ dom(lookup: GmailDomEmailLookup): JQuery; /** An object for interacting with an email currently present in the DOM. Represents a conversation thread Provides a number of methods and properties to access & interact with it Expects a jQuery DOM element for the thread wrapper div (div.if as returned by the 'view_thread' observer) */ thread(element: JQuery): GmailDomThread; } declare type GmailDomComposeLookup = 'to' | 'cc' | 'bcc' | 'id' | 'draft' | 'subject' | 'subjectbox' | 'all_subjects' | 'body' | 'quoted_reply' |'reply' | 'forward' | 'from' | 'send_button'; interface GmailMessageRow { summary: string; from: { name: string, email: string, }; $el: JQuery; thread_id: string; legacy_email_id: string | undefined; } declare type GmailDomCompose = { $el: JQuery, /** Retrieve the compose id */ id(): string, /** Retrieve the draft email id */ email_id(): string, /** Retrieve the draft email id */ thread_id(): string /** Is this compose instance inline (as with reply & forwards) or a popup (as with a new compose) */ is_inline(): boolean, /** Retrieves to, cc, bcc and returns them in a hash of arrays Parameters: options.type string to, cc, or bcc to check a specific one options.flat boolean if true will just return an array of all recipients instead of splitting out into to, cc, and bcc */ recipients(options?: { type: 'to' | 'cc' | 'bcc', flat: boolean }): GmailDomComposeRecipients | string[]; /** Retrieve the current 'to' recipients */ to(): JQuery; /** Retrieve the current 'cc' recipients */ cc(): JQuery; /** Retrieve the current 'bcc' recipients */ bcc(): JQuery; /** Get/Set the current subject Parameters: subject string set as new subject */ subject(subject?: string): string; /** Get the from email if user only has one email account they can send from, returns that email address */ from(): string; /** Get/Set the email html body */ body(body?: string): string; /* Triggers the same action as clicking the "send" button would do. */ send(): void; /** Map find through to jquery element */ find(selector: string): JQuery; /** Close compose window */ close(): void; /** Retrieve preconfigured dom elements for this compose window */ dom(lookup: GmailDomComposeLookup): JQuery; } interface GmailDom { /** * Gets a jQuery object representing the inbox contents. */ inbox_content(): JQuery; /** * Gets a jQuery object representing the inbox contents. */ inboxes(): JQuery; /** * Gets a jQuery object representing the inboxes. */ email_subject(): JQuery; /** * Gets a jQuery object representing the email-subject. */ email_body(): JQuery; /** * Gets the DOM element representing the email body. */ toolbar(): HTMLElement[]; /** * Gets a jQuery object representing the toolbar. */ email_contents(): HTMLElement[]; /** * Gets a jQuery object representing the email contents. */ get_left_sidebar_links(): JQuery; /** * Gets a jQuery object representing the main header. */ header(): JQuery; /** * Gets a jQuery object representing the Search input from main header. */ search_bar(): JQuery; /** * Get's all the visible email threads in the current folder. */ visible_messages(): GmailMessageRow[]; /** * Returns all known compose DOM elements. */ composes(): GmailDomCompose[]; /** A compose object. Represents a compose window in the DOM and provides a bunch of methods and properties to access & interact with the window Expects a jQuery DOM element for the compose div */ compose(element: JQuery | HTMLElement | string): GmailDomCompose; /** An object for interacting with an email currently present in the DOM. Represents an individual email message within a thread Provides a number of methods and properties to access & interact with it Expects a jQuery DOM element for the email div (div.adn as returned by the 'view_email' observer), or an email_id */ email(element: string | HTMLElement | JQuery): GmailDomEmail; /** An object for interacting with an email currently present in the DOM. Represents a conversation thread Provides a number of methods and properties to access & interact with it Expects a jQuery DOM element for the thread wrapper div (div.if as returned by the 'view_thread' observer) */ thread(element: JQuery): GmailDomThread; } //////////////////////////////////////////////////////////////////////////////// // // gmail.tools // //////////////////////////////////////////////////////////////////////////////// declare type GmailHttpRequestMethod = "GET" | "POST"; interface GmailTools { error(str: string): void; parse_url(url: string): StringDict; sleep(milliseconds: number): void; multitry(delay: number, tries: number, func: Function, check: Function, counter?: number, retval?: any): any; deparam(params: string, coerce: boolean): StringDict; parse_actions(params: any, xhr: XMLHttpRequest): {}; parse_response(response: any): any[]; parse_request(params: any, xhr: XMLHttpRequest): {}; xhr_watcher(): any; /** observes every element inserted into the DOM by Gmail and looks at the classes on those elements, checking for any configured observers related to those classes */ insertion_observer(target: HTMLElement | string, dom_observers: any, dom_observer_map: any, sub: any): void; make_request(link: string, method: GmailHttpRequestMethod, disable_cache: boolean): string; make_request_async(link: string, method: GmailHttpRequestMethod, callback: (data: string) => void, disable_cache: boolean): void; /** Creates a request to download user-content from Gmail. This can be used to download email_source or attachments. Set `preferBinary` to receive data as an Uint8Array which is unaffected by string-parsing or resolving of text-encoding. This is required in order to correctly download attachments! */ make_request_download_promise(link: string, preferBinary?: boolean): Promise<string> | Promise<Uint8Array>; parse_view_data(view_data: any[]): any[]; /** Adds the yellow info box on top of gmail with the given message */ infobox(message: string, time?: number, html?: string): void; /** * Re-renders the UI using the available data. * * This method does _not_ cause Gmail to fetch new data. This method is useful * in circumstances where Gmail has data available but does not immediately * render it. `observe.after` may be used to detect when Gmail has fetched the * relevant data. For instance, to refresh a conversation after Gmail fetches * its data: * * gmail.observe.after('refresh', function(url, body, data, xhr) { * if (url.view === 'cv') { * gmail.tools.rerender(); * } * }); * * If a callback is passed, it will be invoked after re-rendering is complete. */ rerender(callback?: Function): void; get_reply_to(ms13: any[]): string[] | null; parse_email_data(email_data: any): GmailEmailData; extract_email_address(str: string): string; extract_name(str: string): string; i18n(label: string): string; add_toolbar_button(content_html: string, onClickFunction: Function, styleClass: string): JQuery; add_right_toolbar_button(content_html: string, onClickFunction: Function, styleClass: string): JQuery; add_compose_button(composeWindow: GmailDomCompose, content_html: string, onClickFunction: Function, styleClass: string): JQuery; /** adds a button to an email attachment. 'attachment'-parameter must be the object returned from api.dom.email().attachments(). 'contentHtml' should represent a 21x21 image of some kind. optional. 'customCssClass' styling used on the buttons central area. optional. 'tooltip' will be shown on hover. return-value is jQuery-instance representing the created button. */ add_attachment_button(attachment: GmailDomAttachment, contentHtml: string | null, customCssClas: string | null, tooltip: string, onClickFunction: Function): JQuery; remove_modal_window(): void; add_modal_window(title: string, content_html: string, onClickOk: Function, onClickCancel?: Function, onClickClose?: Function, okText?: string, cancelText?: string): void; /** * Show/Hide compose window */ toggle_minimize(): void; } //////////////////////////////////////////////////////////////////////////////// // // gmail.observe // //////////////////////////////////////////////////////////////////////////////// declare type GmailComposeType = "reply" | "forward" | "compose"; declare type GmailBindType = 'on' | 'before' | 'after'; declare type GmailBindAction = 'http_event' | 'unread' | 'read' | 'delete' | 'mark_as_spam' | 'mark_as_not_spam' | 'label' | 'archive' | 'move_to_inbox' | 'delete_forver' | 'delete_message_in_thread' | 'restore_message_in_thread' | 'star' | 'unstar' | 'mark_as_important' | "load" | 'mark_as_not_important' | 'filter_messages_like_these' | 'mute' | 'unmute' | 'add_to_tasks' | 'move_label' | 'save_draft' | 'discard_draft' | 'send_message' | 'send_scheduled_message' | 'expand_categories' | 'delete_label' | 'show_newly_arrived_message' | 'poll' | 'new_email' | 'refresh' | 'open_email' | 'upload_attachment' | 'compose' | 'compose_cancelled' | 'recipient_change' | 'view_thread' | 'view_email' | 'load_email_menu'; interface GmailObserve { /** After an observer has been bound through gmail.observe.bind() (via a call to events gmail.observe.before(), gmail.observe.on(), or gmail.observe.after()), this method keeps track of the last 50 http events. The items contain the sent requested parameterized data */ http_requests(): {}[]; /** Similar to gmail.observe.http_requests() this keeps track of the last 10 gmail actions (vs all http requests). Actions here correspond to things like clicking refres, archiving, deleting, starring etc. */ actions(): {}[]; /** Bind a specified callback to an array of callbacks against a specified type & action */ bind(type: GmailBindType, action: Function, callback: Function): void; /** an on event is observed just after gmail sends an xhr request */ on(action: "view_thread", callback: (obj: GmailDomThread) => void): void; on(action: "view_email", callback: (obj: GmailDomEmail) => void): void; on(action: "load_email_menu", callback: (obj: JQuery) => void): void; on(action: "compose", callback: (obj: GmailDomCompose, type: GmailComposeType) => void): void; on(action: "load", callback: () => void): void; /** This is the key feature of gmail.js. This method allows you to add triggers to all of these actions so you can build your custom extension/tool with this library. You simply specify the action name and your function that the method will return data to when the actions are triggered and it does the rest. You can have multiple triggers Your callback will be fired directly after Gmail's XMLHttpRequest has been sent off the the Gmail servers. */ on(action: GmailBindAction, callback: Function, response_callback?: Function): void; /** an before event is observed just prior to the gmail xhr request being sent before events have the ability to modify the xhr request before it is sent */ before(action: GmailBindAction, callback: Function): void; /** an after event is observed when the gmail xhr request returns from the server with the server response */ after(action: "send_message", callback: (url: string, body: string, data: any, xhr: XMLHttpRequest) => void): void; after(action: GmailBindAction, callback: Function): void; /** Checks if a specified action & type has anything bound to it If type is null, will check for this action bound on any type If action is null, will check for any actions bound to a type */ bound(action: GmailBindAction, type: GmailBindType): boolean; /** Clear all callbacks for a specific type (before, on, after, dom) and action If action is null, all actions will be cleared If type is null, all types will be cleared */ off(action: GmailBindAction, type: GmailBindType): void; /** Trigger any specified events bound to the passed type Returns true or false depending if any events were fired */ trigger(type: GmailBindType, events: any, xhr: XMLHttpRequest): boolean; /** Trigger any specified DOM events passing a specified element & optional handler */ trigger_dom(observer: any, element: HTMLElement, handler?: Function): void; initialize_dom_observers(): void; /** Allow an application to register a custom DOM observer specific to their app. Adds it to the configured DOM observers and is supported by the dom insertion observer This method can be called two different ways: Args: action - the name of the new DOM observer className / args - for a simple observer, this arg can simply be the class on an inserted DOM element that identifies this event should be triggered. For a more complicated observer, this can be an object containing properties for each of the supported DOM observer config arguments */ register(action: string, args: string | StringDict): void; /** Observe DOM nodes being inserted. When a node with a class defined in api.tracker.dom_observers is inserted, trigger the related event and fire off any relevant bound callbacks This function should return true if a dom observer is found for the specified action */ on_dom(action: GmailBindAction, callback: Function): void; } //////////////////////////////////////////////////////////////////////////////// // // gmail.helper // //////////////////////////////////////////////////////////////////////////////// type GmailEmailIdentifier = string | GmailNewEmailData | GmailDomEmail | HTMLElement; type GmailThreadIdentifier = string | GmailNewEmailData | GmailDomEmail | GmailDomThread; interface GmailHelper { /** * Dispatch mousedown and mouseup event on passed element */ trigger_mouse_click(element: HTMLElement): boolean; clean_thread_id(thread_id: string): string; get: { is_delegated_inbox(): boolean; visible_emails_pre(): string; visible_emails_post(get_data?: string): string[]; email_data_pre(email_id?: string): string; email_data_post(get_data: string): GmailEmailData; email_source_pre(email_id?: string): string; email_legacy_id(identifier: GmailEmailIdentifier): string | null; email_new_id(identifier: GmailEmailIdentifier): string | null; thread_id(identifier: GmailThreadIdentifier): string | null; } } //////////////////////////////////////////////////////////////////////////////// // // gmail.chat // //////////////////////////////////////////////////////////////////////////////// interface GmailChat { /** Returns True if the account supports the new hangout UI for chat False otherwise (native chat window) */ is_hangouts(): boolean | undefined; } //////////////////////////////////////////////////////////////////////////////// // // gmail.compose // //////////////////////////////////////////////////////////////////////////////// interface GmailCompose { /** * Show a compose window * (Clicks on the compose button making the inbox compose view to popup) */ start_compose(): boolean; } //////////////////////////////////////////////////////////////////////////////// // // gmail.new.* - new gmail only! // //////////////////////////////////////////////////////////////////////////////// interface GmailNewEmailAddress { name: string; address: string; } interface GmailNewEmailData { id: string; legacy_email_id: string; thread_id: string; smtp_id: string; is_draft: boolean, subject: string; timestamp: number; date: Date; from: GmailNewEmailAddress; to: GmailNewEmailAddress[]; cc: GmailNewEmailAddress[]; bcc: GmailNewEmailAddress[]; attachments: GmailAttachmentDetails[]; content_html: string; $email_node?: any; $thread_node?: any; } interface GmailSentEmailData { 1: string; id: string; subject: string; timestamp: number; date: Date; from: GmailNewEmailAddress; to: GmailNewEmailAddress[]; cc: GmailNewEmailAddress[]; bcc: GmailNewEmailAddress[]; attachments: GmailAttachmentDetails[]; content_html: string; ishtml: boolean; $email_node?: any; } interface GmailNewThreadData { thread_id: string; emails: GmailNewEmailData[]; } interface GmailNewGet { /** * Returns the new-style email_id of the latest email visible in the DOM, * or for the provided email-node if provided. * * @param emailElem: Node to extract email-id from or DomEmail. Optional. */ email_id(emailElem?: HTMLElement | GmailDomEmail): string; /** * Returns the new-style thread_id of the current thread visible in the DOM. */ thread_id(): string; /** * Returns available information about a specific email. * * @param email_id: new style email id. Legacy IDs not supported. If empty, default to latest in view. */ email_data(identifier: GmailEmailIdentifier): GmailNewEmailData | null; /** * Returns available information about a specific thread. * * @param thread_id: new style thread id. Legacy IDs not supported. If empty, default to current. */ thread_data(identifier?: GmailThreadIdentifier): GmailNewThreadData | null; } interface GmailNew { get: GmailNewGet; } interface GmailCache { debug_xhr_fetch: boolean; emailIdCache: { (emailId: string): GmailNewEmailData }; emailLegacyIdCache: { (legacyEmailId: string): GmailNewEmailData }; emailThreadIdCache: { (threadId: string): GmailNewThreadData }; } //////////////////////////////////////////////////////////////////////////////// // // actual gmail-class // //////////////////////////////////////////////////////////////////////////////// declare class Gmail { constructor(localJQuery?: JQueryStatic); version: string; /** These are some of the variables that are tracked and kept in memory while the rest of the methods are in use. */ tracker: GmailTracker; get: GmailGet; check: GmailCheck; /** These methods return the DOM data itself */ dom: GmailDom; /** These are some helper functions that the rest of the methods use. See source for input params */ tools: GmailTools; observe: GmailObserve; helper: GmailHelper; chat: GmailChat; compose: GmailCompose; /** Methods for new gmail only! */ new: GmailNew; old: { get: GmailGet; }; cache: GmailCache; }
the_stack
import {ifEnvSupports} from '../test-util'; describe('AsyncTestZoneSpec', function() { let log: string[]; const AsyncTestZoneSpec = (Zone as any)['AsyncTestZoneSpec']; function finishCallback() { log.push('finish'); } function failCallback() { log.push('fail'); } beforeEach(() => { log = []; }); it('should call finish after zone is run in sync call', (done) => { let finished = false; const testZoneSpec = new AsyncTestZoneSpec(() => { expect(finished).toBe(true); done(); }, failCallback, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { finished = true; }); }); it('should call finish after a setTimeout is done', (done) => { let finished = false; const testZoneSpec = new AsyncTestZoneSpec( () => { expect(finished).toBe(true); done(); }, () => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { setTimeout(() => { finished = true; }, 10); }); }); it('should call finish after microtasks are done', (done) => { let finished = false; const testZoneSpec = new AsyncTestZoneSpec( () => { expect(finished).toBe(true); done(); }, () => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { Promise.resolve().then(() => { finished = true; }); }); }); it('should call finish after both micro and macrotasks are done', (done) => { let finished = false; const testZoneSpec = new AsyncTestZoneSpec( () => { expect(finished).toBe(true); done(); }, () => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { new Promise<void>((resolve) => { setTimeout(() => { resolve(); }, 10); }).then(() => { finished = true; }); }); }); it('should call finish after both macro and microtasks are done', (done) => { let finished = false; const testZoneSpec = new AsyncTestZoneSpec( () => { expect(finished).toBe(true); done(); }, () => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { Promise.resolve().then(() => { setTimeout(() => { finished = true; }, 10); }); }); }); describe('event tasks', ifEnvSupports('document', () => { let button: HTMLButtonElement; beforeEach(function() { button = document.createElement('button'); document.body.appendChild(button); }); afterEach(function() { document.body.removeChild(button); }); it('should call finish because an event task is considered as sync', (done) => { let finished = false; const testZoneSpec = new AsyncTestZoneSpec( () => { expect(finished).toBe(true); done(); }, () => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { const listener = () => { finished = true; }; button.addEventListener('click', listener); const clickEvent = document.createEvent('Event'); clickEvent.initEvent('click', true, true); button.dispatchEvent(clickEvent); }); }); it('should call finish after an event task is done asynchronously', (done) => { let finished = false; const testZoneSpec = new AsyncTestZoneSpec( () => { expect(finished).toBe(true); done(); }, () => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { button.addEventListener('click', () => { setTimeout(() => { finished = true; }, 10); }); const clickEvent = document.createEvent('Event'); clickEvent.initEvent('click', true, true); button.dispatchEvent(clickEvent); }); }); })); describe('XHRs', ifEnvSupports('XMLHttpRequest', () => { it('should wait for XHRs to complete', function(done) { let req: XMLHttpRequest; let finished = false; const testZoneSpec = new AsyncTestZoneSpec( () => { expect(finished).toBe(true); done(); }, (err: Error) => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState === XMLHttpRequest.DONE) { finished = true; } }; req.open('get', '/', true); req.send(); }); }); it('should fail if an xhr fails', function(done) { let req: XMLHttpRequest; const testZoneSpec = new AsyncTestZoneSpec( () => { done.fail('expected failCallback to be called'); }, (err: Error) => { expect(err.message).toEqual('bad url failure'); done(); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { req = new XMLHttpRequest(); req.onload = () => { if (req.status != 200) { throw new Error('bad url failure'); } }; req.open('get', '/bad-url', true); req.send(); }); }); })); it('should not fail if setInterval is used and canceled', (done) => { const testZoneSpec = new AsyncTestZoneSpec( () => { done(); }, (err: Error) => { done.fail('async zone called failCallback unexpectedly'); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { let id = setInterval(() => { clearInterval(id); }, 100); }); }); it('should fail if an error is thrown asynchronously', (done) => { const testZoneSpec = new AsyncTestZoneSpec( () => { done.fail('expected failCallback to be called'); }, (err: Error) => { expect(err.message).toEqual('my error'); done(); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { setTimeout(() => { throw new Error('my error'); }, 10); }); }); it('should fail if a promise rejection is unhandled', (done) => { const testZoneSpec = new AsyncTestZoneSpec( () => { done.fail('expected failCallback to be called'); }, (err: Error) => { expect(err.message).toEqual('Uncaught (in promise): my reason'); done(); }, 'name'); const atz = Zone.current.fork(testZoneSpec); atz.run(function() { Promise.reject('my reason'); }); }); const asyncTest: any = (Zone as any)[Zone.__symbol__('asyncTest')]; function wrapAsyncTest(fn: Function, doneFn?: Function) { return function(this: unknown, done: Function) { const asyncWrapper = asyncTest(fn); return asyncWrapper.apply(this, [function(this: unknown) { if (doneFn) { doneFn(); } return done.apply(this, arguments); }]); }; } describe('async', () => { describe('non zone aware async task in promise should be detected', () => { let finished = false; const _global: any = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global; beforeEach(() => { _global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] = true; }); afterEach(() => { _global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] = false; }); it('should be able to detect non zone aware async task in promise', wrapAsyncTest( () => { new Promise((res, rej) => { const g: any = typeof window === 'undefined' ? global : window; g[Zone.__symbol__('setTimeout')](res, 100); }).then(() => { finished = true; }); }, () => { expect(finished).toBe(true); })); }); describe('test without beforeEach', () => { const logs: string[] = []; it('should automatically done after async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('timeout'); }, 100); }, () => { expect(logs).toEqual(['timeout']); logs.splice(0); })); it('should automatically done after all nested async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('timeout'); setTimeout(() => { logs.push('nested timeout'); }, 100); }, 100); }, () => { expect(logs).toEqual(['timeout', 'nested timeout']); logs.splice(0); })); it('should automatically done after multiple async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('1st timeout'); }, 100); setTimeout(() => { logs.push('2nd timeout'); }, 100); }, () => { expect(logs).toEqual(['1st timeout', '2nd timeout']); logs.splice(0); })); }); describe('test with sync beforeEach', () => { const logs: string[] = []; beforeEach(() => { logs.splice(0); logs.push('beforeEach'); }); it('should automatically done after async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('timeout'); }, 100); }, () => { expect(logs).toEqual(['beforeEach', 'timeout']); })); }); describe('test with async beforeEach', () => { const logs: string[] = []; beforeEach(wrapAsyncTest(() => { setTimeout(() => { logs.splice(0); logs.push('beforeEach'); }, 100); })); it('should automatically done after async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('timeout'); }, 100); }, () => { expect(logs).toEqual(['beforeEach', 'timeout']); })); it('should automatically done after all nested async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('timeout'); setTimeout(() => { logs.push('nested timeout'); }, 100); }, 100); }, () => { expect(logs).toEqual(['beforeEach', 'timeout', 'nested timeout']); })); it('should automatically done after multiple async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('1st timeout'); }, 100); setTimeout(() => { logs.push('2nd timeout'); }, 100); }, () => { expect(logs).toEqual(['beforeEach', '1st timeout', '2nd timeout']); })); }); describe('test with async beforeEach and sync afterEach', () => { const logs: string[] = []; beforeEach(wrapAsyncTest(() => { setTimeout(() => { expect(logs).toEqual([]); logs.push('beforeEach'); }, 100); })); afterEach(() => { logs.splice(0); }); it('should automatically done after async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('timeout'); }, 100); }, () => { expect(logs).toEqual(['beforeEach', 'timeout']); })); }); describe('test with async beforeEach and async afterEach', () => { const logs: string[] = []; beforeEach(wrapAsyncTest(() => { setTimeout(() => { expect(logs).toEqual([]); logs.push('beforeEach'); }, 100); })); afterEach(wrapAsyncTest(() => { setTimeout(() => { logs.splice(0); }, 100); })); it('should automatically done after async tasks finished', wrapAsyncTest( () => { setTimeout(() => { logs.push('timeout'); }, 100); }, () => { expect(logs).toEqual(['beforeEach', 'timeout']); })); }); }); });
the_stack
import CommonTypes = require('../ojcommontypes'); import { DataProvider } from '../ojdataprovider'; import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojSelectBase<V, D, SP extends ojSelectBaseSettableProperties<V, D>> extends editableValue<V, SP> { data: DataProvider<V, D>; itemText: keyof D | ((itemContext: CommonTypes.ItemContext<V, D>) => string); labelledBy: string | null; placeholder: string; readonly: boolean; required: boolean; virtualKeyboard: 'email' | 'number' | 'search' | 'tel' | 'text' | 'url'; addEventListener<T extends keyof ojSelectBaseEventMap<V, D, SP>>(type: T, listener: (this: HTMLElement, ev: ojSelectBaseEventMap<V, D, SP>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojSelectBaseSettableProperties<V, D>>(property: T): ojSelectBase<V, D, SP>[T]; getProperty(property: string): any; setProperty<T extends keyof ojSelectBaseSettableProperties<V, D>>(property: T, value: ojSelectBaseSettableProperties<V, D>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSelectBaseSettableProperties<V, D>>): void; setProperties(properties: ojSelectBaseSettablePropertiesLenient<V, D>): void; refresh(): void; validate(): Promise<any>; } export namespace ojSelectBase { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type dataChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["data"]>; // tslint:disable-next-line interface-over-type-literal type itemTextChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["itemText"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["placeholder"]>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["readonly"]>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["required"]>; // tslint:disable-next-line interface-over-type-literal type virtualKeyboardChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["virtualKeyboard"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.describedByChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.disabledChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.helpChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.helpHintsChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.labelEdgeChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.labelHintChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.messagesCustomChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.userAssistanceDensityChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type validChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.validChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.valueChanged<V, SP>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojSelectBaseEventMap<V, D, SP extends ojSelectBaseSettableProperties<V, D>> extends editableValueEventMap<V, SP> { 'ojAnimateEnd': ojSelectBase.ojAnimateEnd; 'ojAnimateStart': ojSelectBase.ojAnimateStart; 'dataChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["data"]>; 'itemTextChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["itemText"]>; 'labelledByChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["labelledBy"]>; 'placeholderChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["placeholder"]>; 'readonlyChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["readonly"]>; 'requiredChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["required"]>; 'virtualKeyboardChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["virtualKeyboard"]>; 'describedByChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["disabled"]>; 'helpChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["labelHint"]>; 'messagesCustomChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["messagesCustom"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["valid"]>; 'valueChanged': JetElementCustomEvent<ojSelectBase<V, D, SP>["value"]>; } export interface ojSelectBaseSettableProperties<V, D> extends editableValueSettableProperties<V> { data: DataProvider<V, D>; itemText: keyof D | ((itemContext: CommonTypes.ItemContext<V, D>) => string); labelledBy: string | null; placeholder: string; readonly: boolean; required: boolean; virtualKeyboard: 'email' | 'number' | 'search' | 'tel' | 'text' | 'url'; } export interface ojSelectBaseSettablePropertiesLenient<V, D> extends Partial<ojSelectBaseSettableProperties<V, D>> { [key: string]: any; } export type SelectBaseElement<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = ojSelectBase<V, D, SP>; export namespace SelectBaseElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type dataChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["data"]>; // tslint:disable-next-line interface-over-type-literal type itemTextChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["itemText"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["placeholder"]>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["readonly"]>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["required"]>; // tslint:disable-next-line interface-over-type-literal type virtualKeyboardChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = JetElementCustomEvent<ojSelectBase<V, D, SP>["virtualKeyboard"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.describedByChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.disabledChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.helpChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.helpHintsChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.labelEdgeChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.labelHintChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.messagesCustomChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.userAssistanceDensityChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type validChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.validChanged<V, SP>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V, D, SP extends ojSelectBaseSettableProperties<V, D>> = editableValue.valueChanged<V, SP>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ }
the_stack
// clang-format off import {assert} from 'chrome://resources/js/assert.m.js'; import {beforeNextRender, dedupingMixin, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BaseMixin} from '../base_mixin.js'; import {SettingsIdleLoadElement} from '../controls/settings_idle_load.js'; import {ensureLazyLoaded} from '../ensure_lazy_loaded.js'; import {loadTimeData} from '../i18n_setup.js'; import {routes} from '../route.js'; import {MinimumRoutes, Route, Router} from '../router.js'; // clang-format on /** * A categorization of every possible Settings URL, necessary for implementing * a finite state machine. */ export enum RouteState { // Initial state before anything has loaded yet. INITIAL = 'initial', // A dialog that has a dedicated URL (e.g. /importData). DIALOG = 'dialog', // A section (basically a scroll position within the top level page, e.g, // /appearance. SECTION = 'section', // A subpage, or sub-subpage e.g, /searchEngins. SUBPAGE = 'subpage', // The top level Settings page, '/'. TOP_LEVEL = 'top-level', } let guestTopLevelRoute = routes.SEARCH; // <if expr="chromeos"> guestTopLevelRoute = routes.PRIVACY; // </if> const TOP_LEVEL_EQUIVALENT_ROUTE: Route = loadTimeData.getBoolean('isGuest') ? guestTopLevelRoute : routes.PEOPLE; function classifyRoute(route: Route|null): RouteState { if (!route) { return RouteState.INITIAL; } const routes = Router.getInstance().getRoutes() as MinimumRoutes; if (route === routes.BASIC) { return RouteState.TOP_LEVEL; } if (route.isSubpage()) { return RouteState.SUBPAGE; } if (route.isNavigableDialog) { return RouteState.DIALOG; } return RouteState.SECTION; } type Constructor<T> = new (...args: any[]) => T; /** * Responds to route changes by expanding, collapsing, or scrolling to * sections on the page. Expanded sections take up the full height of the * container. At most one section should be expanded at any given time. */ export const MainPageMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<MainPageMixinInterface> => { const superClassBase = BaseMixin(superClass); class MainPageMixin extends superClassBase { static get properties() { return { /** * Whether a search operation is in progress or previous search * results are being displayed. */ inSearchMode: { type: Boolean, value: false, observer: 'inSearchModeChanged_', reflectToAttribute: true, }, }; } inSearchMode: boolean; scroller: HTMLElement|null = null; private validTransitions_: Map<RouteState, Set<RouteState>>; private lastScrollTop_: number = 0; // Populated by Polymer itself. domHost: HTMLElement|null; constructor(...args: any[]) { super(...args); /** * A map holding all valid state transitions. */ this.validTransitions_ = (function() { const allStates = new Set([ RouteState.DIALOG, RouteState.SECTION, RouteState.SUBPAGE, RouteState.TOP_LEVEL, ]); return new Map([ [RouteState.INITIAL, allStates], [ RouteState.DIALOG, new Set([ RouteState.SECTION, RouteState.SUBPAGE, RouteState.TOP_LEVEL, ]) ], [RouteState.SECTION, allStates], [RouteState.SUBPAGE, allStates], [RouteState.TOP_LEVEL, allStates], ]); })(); } connectedCallback() { this.scroller = this.domHost ? this.domHost.parentElement : document.body; // Purposefully calling this after |scroller| has been initialized. super.connectedCallback(); } /** * Method to be overridden by users of MainPageMixin. * @return Whether the given route is part of |this| page. */ containsRoute(_route: Route|null): boolean { return false; } private inSearchModeChanged_(_current: boolean, previous: boolean) { if (loadTimeData.getBoolean('enableLandingPageRedesign')) { // No need to deal with overscroll, as only one section is shown at // any given time. return; } // Ignore 1st occurrence which happens while the element is being // initialized. if (previous === undefined) { return; } if (!this.inSearchMode) { const route = Router.getInstance().getCurrentRoute(); if (this.containsRoute(route) && classifyRoute(route) === RouteState.SECTION) { // Re-fire the showing-section event to trigger settings-main // recalculation of the overscroll, now that sections are not // hidden-by-search. this.fire('showing-section', this.getSection(route.section)); } } } private shouldExpandAdvanced_(route: Route): boolean { const routes = Router.getInstance().getRoutes() as MinimumRoutes; return this.tagName === 'SETTINGS-BASIC-PAGE' && routes.ADVANCED && routes.ADVANCED.contains(route); } /** * Finds the settings section corresponding to the given route. If the * section is lazily loaded it force-renders it. * Note: If the section resides within "advanced" settings, a * 'hide-container' event is fired (necessary to avoid flashing). * Callers are responsible for firing a 'show-container' event. */ private ensureSectionForRoute_(route: Route): Promise<HTMLElement> { const section = this.getSection(route.section); if (section !== null) { return Promise.resolve(section); } // The function to use to wait for <dom-if>s to render. const waitFn = beforeNextRender.bind(null, this); return new Promise<HTMLElement>(resolve => { if (this.shouldExpandAdvanced_(route)) { this.fire('hide-container'); waitFn(() => { this.$$<SettingsIdleLoadElement>('#advancedPageTemplate')!.get() .then(() => { resolve(this.getSection(route.section)!); }); }); } else { waitFn(() => { resolve(this.getSection(route.section)!); }); } }); } /** * Finds the settings-section instances corresponding to the given * route. If the section is lazily loaded it force-renders it. Note: If * the section resides within "advanced" settings, a 'hide-container' * event is fired (necessary to avoid flashing). Callers are responsible * for firing a 'show-container' event. */ private ensureSectionsForRoute_(route: Route): Promise<Array<HTMLElement>> { const sections = this.querySettingsSections_(route.section); if (sections.length > 0) { return Promise.resolve(sections); } // The function to use to wait for <dom-if>s to render. const waitFn = beforeNextRender.bind(null, this); return new Promise(resolve => { if (this.shouldExpandAdvanced_(route)) { this.fire('hide-container'); waitFn(() => { this.$$<SettingsIdleLoadElement>('#advancedPageTemplate')!.get() .then(() => { resolve(this.querySettingsSections_(route.section)); }); }); } else { waitFn(() => { resolve(this.querySettingsSections_(route.section)); }); } }); } private enterSubpage_(route: Route) { this.lastScrollTop_ = this.scroller!.scrollTop; this.scroller!.scrollTop = 0; this.classList.add('showing-subpage'); this.fire('subpage-expand'); // Explicitly load the lazy_load.html module, since all subpages // reside in the lazy loaded module. ensureLazyLoaded(); this.ensureSectionForRoute_(route).then(section => { section.classList.add('expanded'); // Fire event used by a11y tests only. this.fire('settings-section-expanded'); this.fire('show-container'); }); } private enterMainPage_(oldRoute: Route): Promise<void> { const oldSection = this.getSection(oldRoute.section)!; oldSection.classList.remove('expanded'); this.classList.remove('showing-subpage'); return new Promise((res) => { requestAnimationFrame(() => { if (Router.getInstance().lastRouteChangeWasPopstate()) { this.scroller!.scrollTop = this.lastScrollTop_; } this.fire('showing-main-page'); res(); }); }); } private scrollToSection_(route: Route) { this.ensureSectionForRoute_(route).then(section => { if (!this.inSearchMode) { this.fire('showing-section', section); } this.fire('show-container'); }); } /** * Shows the section(s) corresponding to |newRoute| and hides the * previously |active| section(s), if any. */ private switchToSections_(newRoute: Route) { this.ensureSectionsForRoute_(newRoute).then(sections => { // Clear any previously |active| section. const oldSections = this.shadowRoot!.querySelectorAll(`settings-section[active]`); for (const s of oldSections) { s.toggleAttribute('active', false); } for (const s of sections) { s.toggleAttribute('active', true); } this.fire('show-container'); }); } /** * Detects which state transition is appropriate for the given new/old * routes. */ private getStateTransition_(newRoute: Route, oldRoute: Route|null) { const containsNew = this.containsRoute(newRoute); const containsOld = this.containsRoute(oldRoute); if (!containsNew && !containsOld) { // Nothing to do, since none of the old/new routes belong to this // page. return null; } // Case where going from |this| page to an unrelated page. For // example: // |this| is settings-basic-page AND // oldRoute is /searchEngines AND // newRoute is /help. if (containsOld && !containsNew) { return [classifyRoute(oldRoute), RouteState.TOP_LEVEL]; } // Case where return from an unrelated page to |this| page. For // example: // |this| is settings-basic-page AND // oldRoute is /help AND // newRoute is /searchEngines if (!containsOld && containsNew) { return [RouteState.TOP_LEVEL, classifyRoute(newRoute)]; } // Case where transitioning between routes that both belong to |this| // page. return [classifyRoute(oldRoute), classifyRoute(newRoute)]; } currentRouteChanged(newRoute: Route, oldRoute: Route|null) { const transition = this.getStateTransition_(newRoute, oldRoute); if (transition === null) { return; } const oldState = transition[0]; const newState = transition[1]; assert(this.validTransitions_.get(oldState)!.has(newState)); loadTimeData.getBoolean('enableLandingPageRedesign') ? this.processTransitionRedesign_( oldRoute, newRoute, oldState, newState) : this.processTransition_(oldRoute, newRoute, oldState, newState); } private processTransition_( oldRoute: Route|null, newRoute: Route, oldState: RouteState, newState: RouteState) { if (oldState === RouteState.TOP_LEVEL) { if (newState === RouteState.SECTION) { this.scrollToSection_(newRoute); } else if (newState === RouteState.SUBPAGE) { this.enterSubpage_(newRoute); } // Nothing to do here for the case of RouteState.DIALOG or // TOP_LEVEL. The latter happens when navigating from '/?search=foo' // to '/' (clearing search results). return; } if (oldState === RouteState.SECTION) { if (newState === RouteState.SECTION) { this.scrollToSection_(newRoute); } else if (newState === RouteState.SUBPAGE) { this.enterSubpage_(newRoute); } else if (newState === RouteState.TOP_LEVEL) { this.scroller!.scrollTop = 0; } // Nothing to do here for the case of RouteState.DIALOG. return; } if (oldState === RouteState.SUBPAGE) { if (newState === RouteState.SECTION) { this.enterMainPage_(oldRoute!); // Scroll to the corresponding section, only if the user // explicitly navigated to a section (via the menu). if (!Router.getInstance().lastRouteChangeWasPopstate()) { this.scrollToSection_(newRoute); } } else if (newState === RouteState.SUBPAGE) { // Handle case where the two subpages belong to // different sections, but are linked to each other. For example // /storage and /accounts (in ChromeOS). if (!oldRoute!.contains(newRoute) && !newRoute.contains(oldRoute!)) { this.enterMainPage_(oldRoute!).then(() => { this.enterSubpage_(newRoute); }); return; } // Handle case of subpage to sub-subpage navigation. if (oldRoute!.contains(newRoute)) { this.scroller!.scrollTop = 0; return; } // When going from a sub-subpage to its parent subpage, scroll // position is automatically restored, because we focus the // sub-subpage entry point. } else if (newState === RouteState.TOP_LEVEL) { this.enterMainPage_(oldRoute!); } else if (newState === RouteState.DIALOG) { // The only known case currently for such a transition is from // /syncSetup to /signOut. this.enterMainPage_(oldRoute!); } return; } if (oldState === RouteState.INITIAL) { if (newState === RouteState.SECTION) { this.scrollToSection_(newRoute); } else if (newState === RouteState.SUBPAGE) { this.enterSubpage_(newRoute); } // Nothing to do here for the case of RouteState.DIALOG and // TOP_LEVEL. return; } if (oldState === RouteState.DIALOG) { if (newState === RouteState.SUBPAGE) { // The only known case currently for such a transition is from // /signOut to /syncSetup. this.enterSubpage_(newRoute); } // Nothing to do for all other cases. } // Nothing to do for when oldState === RouteState.DIALOG. } private processTransitionRedesign_( oldRoute: Route|null, newRoute: Route, oldState: RouteState, newState: RouteState) { if (oldState === RouteState.TOP_LEVEL) { if (newState === RouteState.SECTION) { this.switchToSections_(newRoute); } else if (newState === RouteState.SUBPAGE) { this.switchToSections_(newRoute); this.enterSubpage_(newRoute); } else if (newState === RouteState.TOP_LEVEL) { // Case when navigating from '/?search=foo' to '/' (clearing // search results). this.switchToSections_(TOP_LEVEL_EQUIVALENT_ROUTE); } // Nothing to do here for the case of RouteState.DIALOG. return; } if (oldState === RouteState.SECTION) { if (newState === RouteState.SECTION) { this.switchToSections_(newRoute); } else if (newState === RouteState.SUBPAGE) { this.switchToSections_(newRoute); this.enterSubpage_(newRoute); } else if (newState === RouteState.TOP_LEVEL) { this.switchToSections_(TOP_LEVEL_EQUIVALENT_ROUTE); this.scroller!.scrollTop = 0; } // Nothing to do here for the case of RouteState.DIALOG. return; } if (oldState === RouteState.SUBPAGE) { if (newState === RouteState.SECTION) { this.enterMainPage_(oldRoute!); this.switchToSections_(newRoute); } else if (newState === RouteState.SUBPAGE) { // Handle case where the two subpages belong to // different sections, but are linked to each other. For example // /storage and /accounts (in ChromeOS). if (!oldRoute!.contains(newRoute) && !newRoute.contains(oldRoute!)) { this.enterMainPage_(oldRoute!).then(() => { this.enterSubpage_(newRoute); }); return; } // Handle case of subpage to sub-subpage navigation. if (oldRoute!.contains(newRoute)) { this.scroller!.scrollTop = 0; return; } // When going from a sub-subpage to its parent subpage, scroll // position is automatically restored, because we focus the // sub-subpage entry point. } else if (newState === RouteState.TOP_LEVEL) { this.enterMainPage_(oldRoute!); } return; } if (oldState === RouteState.INITIAL) { if ([RouteState.SECTION, RouteState.DIALOG].includes(newState)) { this.switchToSections_(newRoute); } else if (newState === RouteState.SUBPAGE) { this.switchToSections_(newRoute); this.enterSubpage_(newRoute); } else if (newState === RouteState.TOP_LEVEL) { this.switchToSections_(TOP_LEVEL_EQUIVALENT_ROUTE); } return; } // Nothing to do for when oldState === RouteState.DIALOG. } /** * TODO(dpapad): Rename this to |querySection| to distinguish it from * ensureSectionForRoute_() which force-renders the section as needed. * Helper function to get a section from the local DOM. * @param section Section name of the element to get. */ getSection(section: string): HTMLElement|null { if (!section) { return null; } return this.$$(`settings-section[section="${section}"]`); } /* * @param sectionName Section name of the element to get. */ private querySettingsSections_(sectionName: string): Array<HTMLElement> { const result = []; const section = this.getSection(sectionName); if (section) { result.push(section); } const extraSections = this.shadowRoot!.querySelectorAll<HTMLElement>( `settings-section[nest-under-section="${sectionName}"]`); if (extraSections.length > 0) { result.push(...extraSections); } return result; } } return MainPageMixin; }); export interface MainPageMixinInterface { containsRoute(route: Route|null): boolean; }
the_stack
import type { Operation } from '../../../../src/http/Operation'; import type { ErrorHandler, ErrorHandlerArgs } from '../../../../src/http/output/error/ErrorHandler'; import type { ResponseDescription } from '../../../../src/http/output/response/ResponseDescription'; import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation'; import type { Representation } from '../../../../src/http/representation/Representation'; import { RepresentationMetadata } from '../../../../src/http/representation/RepresentationMetadata'; import type { RegistrationManager, RegistrationResponse } from '../../../../src/identity/interaction/email-password/util/RegistrationManager'; import type { Initializer } from '../../../../src/init/Initializer'; import type { SetupInput } from '../../../../src/init/setup/SetupHttpHandler'; import { SetupHttpHandler } from '../../../../src/init/setup/SetupHttpHandler'; import type { HttpRequest } from '../../../../src/server/HttpRequest'; import type { HttpResponse } from '../../../../src/server/HttpResponse'; import { getBestPreference } from '../../../../src/storage/conversion/ConversionUtil'; import type { RepresentationConverterArgs, RepresentationConverter } from '../../../../src/storage/conversion/RepresentationConverter'; import type { KeyValueStorage } from '../../../../src/storage/keyvalue/KeyValueStorage'; import { APPLICATION_JSON } from '../../../../src/util/ContentTypes'; import type { HttpError } from '../../../../src/util/errors/HttpError'; import { InternalServerError } from '../../../../src/util/errors/InternalServerError'; import { MethodNotAllowedHttpError } from '../../../../src/util/errors/MethodNotAllowedHttpError'; import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError'; import { guardedStreamFrom, readableToString } from '../../../../src/util/StreamUtil'; import { CONTENT_TYPE, SOLID_META } from '../../../../src/util/Vocabularies'; describe('A SetupHttpHandler', (): void => { let request: HttpRequest; const response: HttpResponse = {} as any; let operation: Operation; const viewTemplate = '/templates/view'; const responseTemplate = '/templates/response'; const storageKey = 'completed'; let details: RegistrationResponse; let errorHandler: jest.Mocked<ErrorHandler>; let registrationManager: jest.Mocked<RegistrationManager>; let initializer: jest.Mocked<Initializer>; let converter: jest.Mocked<RepresentationConverter>; let storage: jest.Mocked<KeyValueStorage<string, any>>; let handler: SetupHttpHandler; beforeEach(async(): Promise<void> => { operation = { method: 'GET', target: { path: 'http://test.com/setup' }, preferences: { type: { 'text/html': 1 }}, body: new BasicRepresentation(), }; errorHandler = { handleSafe: jest.fn(({ error }: ErrorHandlerArgs): ResponseDescription => ({ statusCode: 400, data: guardedStreamFrom(`{ "name": "${error.name}", "message": "${error.message}" }`), })) } as any; initializer = { handleSafe: jest.fn(), } as any; details = { email: 'alice@test.email', createWebId: true, register: true, createPod: true, }; registrationManager = { validateInput: jest.fn((input): any => input), register: jest.fn().mockResolvedValue(details), } as any; converter = { handleSafe: jest.fn((input: RepresentationConverterArgs): Representation => { // Just find the best match; const type = getBestPreference(input.preferences.type!, { '*/*': 1 })!; const metadata = new RepresentationMetadata(input.representation.metadata, { [CONTENT_TYPE]: type.value }); return new BasicRepresentation(input.representation.data, metadata); }), } as any; storage = new Map<string, any>() as any; handler = new SetupHttpHandler({ initializer, registrationManager, converter, storageKey, storage, viewTemplate, responseTemplate, errorHandler, }); }); // Since all tests check similar things, the test functionality is generalized in here async function testPost(input: SetupInput, error?: HttpError): Promise<void> { operation.method = 'POST'; const initialize = Boolean(input.initialize); const registration = Boolean(input.registration); const requestBody = { initialize, registration }; if (Object.keys(input).length > 0) { operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json'); } const result = await handler.handle({ operation, request, response }); expect(result).toBeDefined(); expect(initializer.handleSafe).toHaveBeenCalledTimes(!error && initialize ? 1 : 0); expect(registrationManager.validateInput).toHaveBeenCalledTimes(!error && registration ? 1 : 0); expect(registrationManager.register).toHaveBeenCalledTimes(!error && registration ? 1 : 0); let expectedResult: any = { initialize, registration }; if (error) { expectedResult = { name: error.name, message: error.message }; } else if (registration) { Object.assign(expectedResult, details); } expect(JSON.parse(await readableToString(result.data!))).toEqual(expectedResult); expect(result.statusCode).toBe(error?.statusCode ?? 200); expect(result.metadata?.contentType).toBe('text/html'); expect(result.metadata?.get(SOLID_META.template)?.value).toBe(error ? viewTemplate : responseTemplate); if (!error && registration) { expect(registrationManager.validateInput).toHaveBeenLastCalledWith(requestBody, true); expect(registrationManager.register).toHaveBeenLastCalledWith(requestBody, true); } } it('returns the view template on GET requests.', async(): Promise<void> => { const result = await handler.handle({ operation, request, response }); expect(result).toBeDefined(); expect(JSON.parse(await readableToString(result.data!))).toEqual({}); expect(result.statusCode).toBe(200); expect(result.metadata?.contentType).toBe('text/html'); expect(result.metadata?.get(SOLID_META.template)?.value).toBe(viewTemplate); // Setup is still enabled since this was a GET request expect(storage.get(storageKey)).toBeUndefined(); }); it('simply disables the handler if no setup is requested.', async(): Promise<void> => { await expect(testPost({ initialize: false, registration: false })).resolves.toBeUndefined(); // Handler is now disabled due to successful POST expect(storage.get(storageKey)).toBe(true); }); it('defaults to an empty body if there is none.', async(): Promise<void> => { await expect(testPost({})).resolves.toBeUndefined(); }); it('calls the initializer when requested.', async(): Promise<void> => { await expect(testPost({ initialize: true, registration: false })).resolves.toBeUndefined(); }); it('calls the registrationManager when requested.', async(): Promise<void> => { await expect(testPost({ initialize: false, registration: true })).resolves.toBeUndefined(); }); it('converts non-HTTP errors to internal errors.', async(): Promise<void> => { converter.handleSafe.mockRejectedValueOnce(new Error('bad data')); const error = new InternalServerError('bad data'); await expect(testPost({ initialize: true, registration: false }, error)).resolves.toBeUndefined(); }); it('errors on non-GET/POST requests.', async(): Promise<void> => { operation.method = 'PUT'; const requestBody = { initialize: true, registration: true }; operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json'); const error = new MethodNotAllowedHttpError(); const result = await handler.handle({ operation, request, response }); expect(result).toBeDefined(); expect(initializer.handleSafe).toHaveBeenCalledTimes(0); expect(registrationManager.register).toHaveBeenCalledTimes(0); expect(errorHandler.handleSafe).toHaveBeenCalledTimes(1); expect(errorHandler.handleSafe).toHaveBeenLastCalledWith({ error, preferences: { type: { [APPLICATION_JSON]: 1 }}}); expect(JSON.parse(await readableToString(result.data!))).toEqual({ name: error.name, message: error.message }); expect(result.statusCode).toBe(405); expect(result.metadata?.contentType).toBe('text/html'); expect(result.metadata?.get(SOLID_META.template)?.value).toBe(viewTemplate); // Setup is not disabled since there was an error expect(storage.get(storageKey)).toBeUndefined(); }); it('errors when attempting registration when no RegistrationManager is defined.', async(): Promise<void> => { handler = new SetupHttpHandler({ errorHandler, initializer, converter, storageKey, storage, viewTemplate, responseTemplate, }); operation.method = 'POST'; const requestBody = { initialize: false, registration: true }; operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json'); const error = new NotImplementedHttpError('This server is not configured to support registration during setup.'); await expect(testPost({ initialize: false, registration: true }, error)).resolves.toBeUndefined(); // Setup is not disabled since there was an error expect(storage.get(storageKey)).toBeUndefined(); }); it('errors when attempting initialization when no Initializer is defined.', async(): Promise<void> => { handler = new SetupHttpHandler({ errorHandler, registrationManager, converter, storageKey, storage, viewTemplate, responseTemplate, }); operation.method = 'POST'; const requestBody = { initialize: true, registration: false }; operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json'); const error = new NotImplementedHttpError('This server is not configured with a setup initializer.'); await expect(testPost({ initialize: true, registration: false }, error)).resolves.toBeUndefined(); // Setup is not disabled since there was an error expect(storage.get(storageKey)).toBeUndefined(); }); });
the_stack
import { Signer } from "ethers"; import { ethers } from "hardhat"; import "module-alias/register"; import { DateString__factory } from "typechain/factories/DateString__factory"; import { IERC20__factory } from "typechain/factories/IERC20__factory"; import { InterestTokenFactory__factory } from "typechain/factories/InterestTokenFactory__factory"; import { InterestToken__factory } from "typechain/factories/InterestToken__factory"; import { IWETH__factory } from "typechain/factories/IWETH__factory"; import { IYearnVault__factory } from "typechain/factories/IYearnVault__factory"; import { TestERC20__factory } from "typechain/factories/TestERC20__factory"; import { TestUserProxy__factory } from "typechain/factories/TestUserProxy__factory"; import { TestWrappedPosition__factory } from "typechain/factories/TestWrappedPosition__factory"; import { TestYVault__factory } from "typechain/factories/TestYVault__factory"; import { TrancheFactory__factory } from "typechain/factories/TrancheFactory__factory"; import { Tranche__factory } from "typechain/factories/Tranche__factory"; import { YVaultAssetProxy__factory } from "typechain/factories/YVaultAssetProxy__factory"; import { ZapTrancheHop__factory } from "typechain/factories/ZapTrancheHop__factory"; import { ZapYearnShares__factory } from "typechain/factories/ZapYearnShares__factory"; import { IERC20 } from "typechain/IERC20"; import { InterestToken } from "typechain/InterestToken"; import { IWETH } from "typechain/IWETH"; import { IYearnVault } from "typechain/IYearnVault"; import { TestERC20 } from "typechain/TestERC20"; import { TestUserProxy } from "typechain/TestUserProxy"; import { TestWrappedPosition } from "typechain/TestWrappedPosition"; import { TestYVault } from "typechain/TestYVault"; import { Tranche } from "typechain/Tranche"; import { TrancheFactory } from "typechain/TrancheFactory"; import { YVaultAssetProxy } from "typechain/YVaultAssetProxy"; import { ZapTrancheHop } from "typechain/ZapTrancheHop"; import { ZapYearnShares } from "typechain/ZapYearnShares"; import data from "../../artifacts/contracts/Tranche.sol/Tranche.json"; export interface FixtureInterface { signer: Signer; usdc: TestERC20; yusdc: TestYVault; position: YVaultAssetProxy; tranche: Tranche; interestToken: InterestToken; proxy: TestUserProxy; trancheFactory: TrancheFactory; } export interface EthPoolMainnetInterface { signer: Signer; weth: IWETH; yweth: IYearnVault; position: YVaultAssetProxy; tranche: Tranche; proxy: TestUserProxy; } export interface UsdcPoolMainnetInterface { signer: Signer; usdc: IERC20; yusdc: IYearnVault; position: YVaultAssetProxy; tranche: Tranche; proxy: TestUserProxy; } export interface TrancheTestFixture { signer: Signer; usdc: TestERC20; positionStub: TestWrappedPosition; tranche: Tranche; interestToken: InterestToken; } export interface YearnShareZapInterface { sharesZapper: ZapYearnShares; signer: Signer; usdc: IERC20; yusdc: IYearnVault; position: YVaultAssetProxy; tranche: Tranche; } export interface TrancheHopInterface { trancheHop: ZapTrancheHop; signer: Signer; usdc: IERC20; yusdc: IYearnVault; position: YVaultAssetProxy; tranche1: Tranche; tranche2: Tranche; interestToken1: InterestToken; interestToken2: InterestToken; } const deployTestWrappedPosition = async (signer: Signer, address: string) => { const deployer = new TestWrappedPosition__factory(signer); return await deployer.deploy(address); }; const deployUsdc = async (signer: Signer, owner: string) => { const deployer = new TestERC20__factory(signer); return await deployer.deploy(owner, "tUSDC", 6); }; const deployYusdc = async ( signer: Signer, usdcAddress: string, decimals: number ) => { const deployer = new TestYVault__factory(signer); return await deployer.deploy(usdcAddress, decimals); }; const deployYasset = async ( signer: Signer, yUnderlying: string, underlying: string, name: string, symbol: string ) => { const yVaultDeployer = new YVaultAssetProxy__factory(signer); return await yVaultDeployer.deploy(yUnderlying, underlying, name, symbol); }; const deployInterestTokenFactory = async (signer: Signer) => { const deployer = new InterestTokenFactory__factory(signer); return await deployer.deploy(); }; export const deployTrancheFactory = async (signer: Signer) => { const interestTokenFactory = await deployInterestTokenFactory(signer); const deployer = new TrancheFactory__factory(signer); const dateLibFactory = new DateString__factory(signer); const dateLib = await dateLibFactory.deploy(); const deployTx = await deployer.deploy( interestTokenFactory.address, dateLib.address ); return deployTx; }; export async function loadFixture() { // The mainnet weth address won't work unless mainnet deployed const wethAddress = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; const [signer] = await ethers.getSigners(); const signerAddress = (await signer.getAddress()) as string; const usdc = await deployUsdc(signer, signerAddress); const yusdc = await deployYusdc(signer, usdc.address, 6); const position: YVaultAssetProxy = await deployYasset( signer, yusdc.address, usdc.address, "eyUSDC", "eyUSDC" ); // deploy and fetch tranche contract const trancheFactory = await deployTrancheFactory(signer); await trancheFactory.deployTranche(1e10, position.address); const eventFilter = trancheFactory.filters.TrancheCreated(null, null, null); const events = await trancheFactory.queryFilter(eventFilter); const trancheAddress = events[0] && events[0].args && events[0].args[0]; const tranche = Tranche__factory.connect(trancheAddress, signer); const interestTokenAddress = await tranche.interestToken(); const interestToken = InterestToken__factory.connect( interestTokenAddress, signer ); // Setup the proxy const bytecodehash = ethers.utils.solidityKeccak256( ["bytes"], [data.bytecode] ); const proxyFactory = new TestUserProxy__factory(signer); const proxy = await proxyFactory.deploy( wethAddress, trancheFactory.address, bytecodehash ); return { signer, usdc, yusdc, position, tranche, interestToken, proxy, trancheFactory, }; } export async function loadEthPoolMainnetFixture() { const wethAddress = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; const ywethAddress = "0xac333895ce1A73875CF7B4Ecdc5A743C12f3d82B"; const [signer] = await ethers.getSigners(); const weth = IWETH__factory.connect(wethAddress, signer); const yweth = IYearnVault__factory.connect(ywethAddress, signer); const position = await deployYasset( signer, yweth.address, weth.address, "Element Yearn Wrapped Ether", "eyWETH" ); // deploy and fetch tranche contract const trancheFactory = await deployTrancheFactory(signer); await trancheFactory.deployTranche(1e10, position.address); const eventFilter = trancheFactory.filters.TrancheCreated(null, null, null); const events = await trancheFactory.queryFilter(eventFilter); const trancheAddress = events[0] && events[0].args && events[0].args[0]; const tranche = Tranche__factory.connect(trancheAddress, signer); // Setup the proxy const bytecodehash = ethers.utils.solidityKeccak256( ["bytes"], [data.bytecode] ); const proxyFactory = new TestUserProxy__factory(signer); const proxy = await proxyFactory.deploy( wethAddress, trancheFactory.address, bytecodehash ); return { signer, weth, yweth, position, tranche, proxy, }; } export async function loadUsdcPoolMainnetFixture() { const usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; const yusdcAddress = "0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9"; const wethAddress = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; const [signer] = await ethers.getSigners(); const usdc = IERC20__factory.connect(usdcAddress, signer); const yusdc = IYearnVault__factory.connect(yusdcAddress, signer); const position = await deployYasset( signer, yusdc.address, usdc.address, "Element Yearn USDC", "eyUSDC" ); // deploy and fetch tranche contract const trancheFactory = await deployTrancheFactory(signer); await trancheFactory.deployTranche(1e10, position.address); const eventFilter = trancheFactory.filters.TrancheCreated(null, null, null); const events = await trancheFactory.queryFilter(eventFilter); const trancheAddress = events[0] && events[0].args && events[0].args[0]; const tranche = Tranche__factory.connect(trancheAddress, signer); // Setup the proxy const bytecodehash = ethers.utils.solidityKeccak256( ["bytes"], [data.bytecode] ); const proxyFactory = new TestUserProxy__factory(signer); const proxy = await proxyFactory.deploy( wethAddress, trancheFactory.address, bytecodehash ); return { signer, usdc, yusdc, position, tranche, proxy, }; } export async function loadTestTrancheFixture() { const [signer] = await ethers.getSigners(); const testTokenDeployer = new TestERC20__factory(signer); const usdc = await testTokenDeployer.deploy("test token", "TEST", 6); const positionStub: TestWrappedPosition = await deployTestWrappedPosition( signer, usdc.address ); // deploy and fetch tranche contract const trancheFactory = await deployTrancheFactory(signer); await trancheFactory.deployTranche(1e10, positionStub.address); const eventFilter = trancheFactory.filters.TrancheCreated(null, null, null); const events = await trancheFactory.queryFilter(eventFilter); const trancheAddress = events[0] && events[0].args && events[0].args[0]; const tranche = Tranche__factory.connect(trancheAddress, signer); const interestTokenAddress = await tranche.interestToken(); const interestToken = InterestToken__factory.connect( interestTokenAddress, signer ); return { signer, usdc, positionStub, tranche, interestToken, }; } export async function loadYearnShareZapFixture() { const usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; const yusdcAddress = "0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9"; const [signer] = await ethers.getSigners(); const usdc = IERC20__factory.connect(usdcAddress, signer); const yusdc = IYearnVault__factory.connect(yusdcAddress, signer); const position = await deployYasset( signer, yusdc.address, usdc.address, "Element Yearn USDC", "eyUSDC" ); // deploy and fetch tranche contract const trancheFactory = await deployTrancheFactory(signer); await trancheFactory.deployTranche(1e10, position.address); const eventFilter = trancheFactory.filters.TrancheCreated(null, null, null); const events = await trancheFactory.queryFilter(eventFilter); const trancheAddress = events[0] && events[0].args && events[0].args[0]; const tranche = Tranche__factory.connect(trancheAddress, signer); // Setup the proxy const bytecodehash = ethers.utils.solidityKeccak256( ["bytes"], [data.bytecode] ); const deployer = new ZapYearnShares__factory(signer); const sharesZapper = await deployer.deploy( trancheFactory.address, bytecodehash ); return { sharesZapper, signer, usdc, yusdc, position, tranche, }; } export async function loadTrancheHopFixture(toAuth: string) { const usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; const yusdcAddress = "0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9"; const [signer] = await ethers.getSigners(); const usdc = IERC20__factory.connect(usdcAddress, signer); const yusdc = IYearnVault__factory.connect(yusdcAddress, signer); const position = await deployYasset( signer, yusdc.address, usdc.address, "Element Yearn USDC", "eyUSDC" ); // deploy and fetch tranche contract const trancheFactory = await deployTrancheFactory(signer); await trancheFactory.deployTranche(1e10, position.address); await trancheFactory.deployTranche(2e10, position.address); const eventFilter = trancheFactory.filters.TrancheCreated(null, null, null); const events = await trancheFactory.queryFilter(eventFilter); const trancheAddress1 = events[0] && events[0].args && events[0].args[0]; const trancheAddress2 = events[1] && events[1].args && events[1].args[0]; const tranche1 = Tranche__factory.connect(trancheAddress1, signer); const tranche2 = Tranche__factory.connect(trancheAddress2, signer); const interestTokenAddress1 = await tranche1.interestToken(); const interestToken1 = InterestToken__factory.connect( interestTokenAddress1, signer ); const interestTokenAddress2 = await tranche2.interestToken(); const interestToken2 = InterestToken__factory.connect( interestTokenAddress2, signer ); // Setup the proxy const bytecodehash = ethers.utils.solidityKeccak256( ["bytes"], [data.bytecode] ); const deployer = new ZapTrancheHop__factory(signer); const trancheHop = await deployer.deploy( trancheFactory.address, bytecodehash ); await trancheHop.connect(signer).authorize(toAuth); await trancheHop.connect(signer).setOwner(toAuth); return { trancheHop, signer, usdc, yusdc, position, tranche1, tranche2, interestToken1, interestToken2, }; }
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { StandardProps, omitProps, findTypes, getFirst, } from '../../util/component-types'; import { lucidClassNames } from '../../util/style-helpers'; import { partitionText, propsSearch } from '../../util/text-manipulation'; import { buildModernHybridComponent } from '../../util/state-management'; import * as reducers from './SearchableSelect.reducers'; import ChevronIcon from '../Icon/ChevronIcon/ChevronIcon'; import { DropMenuDumb as DropMenu, IDropMenuOptionProps, IDropMenuOptionGroupProps, IDropMenuProps, IDropMenuState, IOptionsData, } from '../DropMenu/DropMenu'; import LoadingIcon from '../Icon/LoadingIcon/LoadingIcon'; import { SearchFieldDumb as SearchField } from '../SearchField/SearchField'; import { Validation } from '../Validation/Validation'; const cx = lucidClassNames.bind('&-SearchableSelect'); /** PropTypes */ const { any, bool, func, node, number, object, shape, string, oneOfType } = PropTypes; export interface ISearchableSelectPlaceholderProps extends StandardProps { description?: string; } /** Placeholder Child Component */ const Placeholder = (_props: ISearchableSelectPlaceholderProps): null => null; Placeholder.displayName = 'SearchableSelect.Placeholder'; Placeholder.peek = { description: ` The content rendered in the control when there is no option is selected. Also rendered in the option list to remove current selection. `, }; Placeholder.propName = 'Placeholder'; Placeholder.propTypes = {}; /** OptionGroup Child Component */ const OptionGroup = (_props: IDropMenuOptionGroupProps): null => null; OptionGroup.displayName = 'SearchableSelect.OptionGroup'; OptionGroup.peek = { description: ` A special kind of \`Option\` that is always rendered at the top of the menu and has an \`optionIndex\` of \`null\`. Useful for unselect. `, }; OptionGroup.propName = 'OptionGroup'; OptionGroup.propTypes = DropMenu.OptionGroup.propTypes; OptionGroup.defaultProps = DropMenu.OptionGroup.defaultProps; export interface ISearchableSelectOptionProps extends IDropMenuOptionProps { description?: string; name?: string; Selected?: React.ReactNode; } /** Option.Selected Child Component */ const Selected = (_props: { children?: React.ReactNode }): null => null; Selected.displayName = 'SearchableSelect.Option.Selected'; Selected.peek = { description: ` Customizes the rendering of the Option when it is selected and is displayed instead of the Placeholder. `, }; Selected.propName = 'Selected'; Selected.propTypes = {}; /** Option Child Component */ const Option = (_props: ISearchableSelectOptionProps): null => null; Option.displayName = 'SearchableSelect.Option'; Option.peek = { description: ` A selectable option in the list. `, }; Option.Selected = Selected; Option.propName = 'Option'; Option.propTypes = { /** Customizes the rendering of the Option when it is selected and is displayed instead of the Placeholder. */ Selected: any, value: string, filterText: string, ...DropMenu.Option.propTypes, }; Option.defaultProps = DropMenu.Option.defaultProps; type ISearchableSelectDropMenuProps = Partial<IDropMenuProps>; export interface ISearchableSelectProps extends StandardProps { hasReset: boolean; isDisabled: boolean; isInvisible: boolean; isLoading: boolean; isSelectionHighlighted: boolean; maxMenuHeight?: string | number; selectedIndex: number | null; searchText: string; DropMenu: ISearchableSelectDropMenuProps; Placeholder?: React.ReactNode; Option?: React.ReactNode; OptionGroup?: IDropMenuOptionGroupProps; Error: React.ReactNode; /** Called when an option is clicked, or when an option has focus and the Enter key is pressed. */ onSelect: ( optionIndex: number | null, { props, event, }: { props: IDropMenuOptionProps | undefined; event: React.KeyboardEvent | React.MouseEvent; } ) => void; onSearch: (searchText: string, firstVisibleIndex: number | undefined) => void; optionFilter: (searchValue: string, props: any) => boolean; } export interface ISearchableSelectState { DropMenu: IDropMenuState; selectedIndex: number | null; searchText: string | null; optionGroups: IDropMenuOptionGroupProps[]; flattenedOptionsData: IOptionsData[]; ungroupedOptionData: IOptionsData[]; optionGroupDataLookup: { [key: number]: IOptionsData[] }; } const defaultProps = { hasReset: true, isSelectionHighlighted: true, isDisabled: false, isInvisible: false, isLoading: false, optionFilter: propsSearch, searchText: '', selectedIndex: null, DropMenu: DropMenu.defaultProps, Error: null, onSearch: _.noop, onSelect: _.noop, }; /** SearchableSelect Component */ class SearchableSelect extends React.Component< ISearchableSelectProps, ISearchableSelectState > { static displayName = 'SearchableSelect'; static peek = { description: `A selector control (like native \`<select>\`) which is used to select a single option from a dropdown list using a \`SearchField\`. Supports option groups with and without labels.`, categories: ['controls', 'selectors'], madeFrom: ['DropMenu', 'SearchField'], }; static defaultProps = defaultProps; static reducers = reducers; static Placeholder = Placeholder; static Option = Option; static OptionGroup = OptionGroup; static SearchField = SearchField; static NullOption = DropMenu.NullOption; static FixedOption = DropMenu.FixedOption; static propTypes = { /** Should be instances of {\`SearchableSelect.Placeholder\`, \`SearchableSelect.Option\`, \`SearchableSelect.OptionGroup\`}. Other direct child elements will not render. */ children: node, className: string /** Appended to the component-specific class names set on the root elements. Applies to *both* the control and the flyout menu. */, /** Styles that are passed through to root element. */ style: object, /** Allows user to reset the \`optionIndex\` to \`null\` if they select the placeholder at the top of the options list. If \`false\`, it will not render the placeholder in the menu. */ hasReset: bool, /** Disables the SearchableSelect from being clicked or focused. */ isDisabled: bool, /** The SearchableSelect will be invisible. */ isInvisible: bool, /** Displays a centered LoadingIcon to allow for asynchronous loading of options. */ isLoading: bool, /** Applies primary color styling to the control when an item is selected. */ isSelectionHighlighted: bool, /** The max height of the fly-out menu. */ maxMenuHeight: oneOfType([number, string]), onSearch: func /** Called when the user enters a value to search for; the set of visible Options will be filtered using the value. Has the signature \`(searchText, firstVisibleIndex, {props, event}) => {}\` where \`searchText\` is the value from the \`SearchField\` and \`firstVisibleIndex\` is the index of the first option that will be visible after filtering. */, /** Called when an option is selected. Has the signature \`(optionIndex, {props, event}) => {}\` where \`optionIndex\` is the new \`selectedIndex\` or \`null\`. */ onSelect: func, /** The function that will be run against each Option's props to determine whether it should be visible or not. The default behavior of the function is to match, ignoring case, against any text node descendant of the \`Option\`. Has the signature \`(searchText, optionProps)\` If \`true\`, option will be visible. If \`false\`, the option will not be visible. */ optionFilter: func, /** The current search text to filter the list of options by. */ searchText: string, /** The currently selected \`SearchableSelect.Option\` index or \`null\` if nothing is selected. */ selectedIndex: number, /** Object of DropMenu props which are passed thru to the underlying DropMenu component. */ DropMenu: shape(DropMenu.propTypes), Placeholder: any /** *Child Element* - The content rendered in the control when there is no option is selected. Also rendered in the option list to remove current selection. */, Option: any /** *Child Element* - These are menu options. The \`optionIndex\` is in-order of rendering regardless of group nesting, starting with index \`0\`. Each \`Option\` may be passed a prop called \`isDisabled\` to disable selection of that \`Option\`. Any other props pass to Option will be available from the \`onSelect\` handler. */, FixedOption: any /** *Child Element* - A special kind of \`Option\` that is always rendered at the top of the menu. */, NullOption: any /** *Child Element* - A special kind of \`Option\` that is always rendered at the top of the menu and has an \`optionIndex\` of \`null\`. Useful for unselect. */, OptionGroup: any /** *Child Element* - Used to group \`Option\`s within the menu. Any non-\`Option\`s passed in will be rendered as a label for the group. */, /** In most cases this will be a string, but it also accepts any valid React element. If this is a falsey value, then no error message will be displayed. If this is the literal \`true\`, it will add the \`-is-error\` class to the wrapper div, but not render the \`-error-content\` \`div\`. */ Error: any, }; UNSAFE_componentWillMount() { // preprocess the options data before rendering const { optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, } = DropMenu.preprocessOptionData(this.props, SearchableSelect); this.setState({ optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, }); } UNSAFE_componentWillReceiveProps = (nextProps: ISearchableSelectProps) => { // only preprocess options data when it changes (via new props) - better performance than doing this each render const { optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, } = DropMenu.preprocessOptionData(nextProps, SearchableSelect); this.setState({ optionGroups, flattenedOptionsData, ungroupedOptionData, optionGroupDataLookup, }); }; handleSearch = (searchText: string) => { const { props: { onSearch, optionFilter }, } = this; const { flattenedOptionsData } = this.state; const firstVisibleIndex = _.get( _.find(flattenedOptionsData, ({ optionProps }) => { return optionFilter(searchText, optionProps); }), 'optionIndex' ); onSearch(searchText, firstVisibleIndex); }; renderUnderlinedChildren = (childText: string, searchText: string) => { const [pre, match, post] = partitionText( childText, new RegExp(_.escapeRegExp(searchText), 'i'), searchText.length ); return [ pre && ( <span key='pre' className={cx('&-Option-underline-pre')}> {pre} </span> ), match && ( <span key='match' className={cx('&-Option-underline-match')}> {match} </span> ), post && ( <span key='post' className={cx('&-Option-underline-post')}> {post} </span> ), ]; }; renderOption = (optionProps: IDropMenuOptionProps, optionIndex: number) => { const { isLoading, optionFilter, searchText } = this.props; if (searchText) { return ( <DropMenu.Option isDisabled={isLoading} {..._.omit(optionProps, ['children', 'Selected', 'filterText'])} isHidden={!optionFilter(searchText, optionProps)} key={'SearchableSelectOption' + optionIndex} > {_.isString(optionProps.children) ? this.renderUnderlinedChildren(optionProps.children, searchText) : _.isFunction(optionProps.children) ? React.createElement(optionProps.children, { searchText }) : optionProps.children} </DropMenu.Option> ); } return ( <DropMenu.Option key={'SearchableSelectOption' + optionIndex} {..._.omit(optionProps, ['children', 'Selected', 'filterText'])} isDisabled={optionProps.isDisabled || isLoading} > {_.isFunction(optionProps.children) ? React.createElement(optionProps.children, { searchText }) : optionProps.children} </DropMenu.Option> ); }; renderOptions() { const { searchText } = this.props; const { optionGroups, optionGroupDataLookup, ungroupedOptionData } = this.state; // for each option group passed in, render a DropMenu.OptionGroup, any // label will be included in it's children, render each option inside the // group const options = _.map( optionGroups, (optionGroupProps, optionGroupIndex) => { const childOptions = _.map( _.get(optionGroupDataLookup, optionGroupIndex), ({ optionProps, optionIndex }) => this.renderOption(optionProps, optionIndex) ); const visibleChildrenCount = _.filter( childOptions, (option) => !option.props.isHidden ).length; return ( <DropMenu.OptionGroup isHidden={visibleChildrenCount === 0} key={'SearchableSelectOptionGroup' + optionGroupIndex} {...optionGroupProps} > {optionGroupProps.children} {childOptions} </DropMenu.OptionGroup> ); // then render all the ungrouped options at the end } ).concat( _.map(ungroupedOptionData, ({ optionProps, optionIndex }) => this.renderOption(optionProps, optionIndex) ) ); const visibleOptionsCount = _.filter( options, (option) => !option.props.isHidden ).length; return visibleOptionsCount > 0 ? ( options ) : ( <DropMenu.Option isDisabled> <span className={cx('&-noresults')}> No results match "{searchText}" </span> </DropMenu.Option> ); } render() { const { props, props: { style, className, hasReset, isDisabled, isInvisible, isLoading, isSelectionHighlighted, maxMenuHeight, searchText, selectedIndex, onSelect, DropMenu: dropMenuProps, }, } = this; const { direction, optionContainerStyle, isExpanded } = dropMenuProps; const { flattenedOptionsData } = this.state; const searchFieldProps = _.get( getFirst(props, SearchField) || <SearchField placeholder='Search...' />, 'props' ); const placeholderProps = _.first( _.map(findTypes(this.props, SearchableSelect.Placeholder), 'props') ); const errorChildProps = _.first( _.map(findTypes(props, Validation.Error), 'props') ); const placeholder = _.get(placeholderProps, 'children', 'Select'); const isItemSelected = _.isNumber(selectedIndex); return ( <div className={cx('&', className)} style={style}> <DropMenu {...dropMenuProps} optionContainerStyle={_.assign( {}, optionContainerStyle, !_.isNil(maxMenuHeight) ? { maxHeight: maxMenuHeight } : null )} isDisabled={isDisabled} onSelect={onSelect} selectedIndices={_.isNumber(selectedIndex) ? [selectedIndex] : []} > <DropMenu.Control> <div tabIndex={0} className={cx('&-Control', { '&-Control-is-highlighted': (!isDisabled && isItemSelected && isSelectionHighlighted) || (isExpanded && isSelectionHighlighted), '&-Control-is-selected': !isDisabled && isItemSelected && isSelectionHighlighted && !(errorChildProps && errorChildProps.children), '&-Control-is-expanded': isExpanded, '&-Control-is-invisible': isInvisible, '&-Control-is-disabled': isDisabled, '&-Control-is-error': errorChildProps && errorChildProps.children, })} > <span {...(!isItemSelected ? placeholderProps : null)} className={cx( '&-Control-content', !isItemSelected ? _.get(placeholderProps, 'className') : null )} > {_.isNumber(selectedIndex) ? _.get( getFirst( flattenedOptionsData[selectedIndex].optionProps, SearchableSelect.Option.Selected ), 'props.children' ) || ((Children) => _.isFunction(Children) ? <Children /> : Children)( flattenedOptionsData[selectedIndex].optionProps.children ) : placeholder} </span> <ChevronIcon size={12} direction={isExpanded ? direction : 'down'} /> </div> </DropMenu.Control> <DropMenu.Header className={cx('&-Search-container')}> <SearchField {...searchFieldProps} autoComplete={searchFieldProps.autoComplete || 'off'} onChange={this.handleSearch} value={searchText} /> </DropMenu.Header> {isLoading && ( <DropMenu.Option key='SearchableSelectLoading' className={cx('&-Loading')} isDisabled > <LoadingIcon /> </DropMenu.Option> )} {hasReset && isItemSelected && ( <DropMenu.NullOption {...placeholderProps}> {placeholder} </DropMenu.NullOption> )} {this.renderOptions()} </DropMenu> {errorChildProps && errorChildProps.children && errorChildProps.children !== true ? ( <div {...omitProps(errorChildProps, undefined)} className={cx('&-error-content')} > {errorChildProps.children} </div> ) : null} </div> ); } } export default buildModernHybridComponent< ISearchableSelectProps, ISearchableSelectState, typeof SearchableSelect >(SearchableSelect as any, { reducers }); export { SearchableSelect as SearchableSelectDumb };
the_stack
import { Logger, LoggerFactory } from '../logger'; import { ColumnUtils } from './columnUtils'; import { AbstractColDef, ColDef, ColGroupDef } from "../entities/colDef"; import { ColumnKeyCreator } from "./columnKeyCreator"; import { IProvidedColumn } from "../entities/iProvidedColumn"; import { ProvidedColumnGroup } from "../entities/providedColumnGroup"; import { Column } from "../entities/column"; import { Autowired, Bean, Qualifier } from "../context/context"; import { DefaultColumnTypes } from "../entities/defaultColumnTypes"; import { BeanStub } from "../context/beanStub"; import { Constants } from "../constants/constants"; import { assign, iterateObject, mergeDeep } from '../utils/object'; import { attrToNumber, attrToBoolean, find } from '../utils/generic'; import { removeFromArray } from '../utils/array'; // takes ColDefs and ColGroupDefs and turns them into Columns and OriginalGroups @Bean('columnFactory') export class ColumnFactory extends BeanStub { @Autowired('columnUtils') private columnUtils: ColumnUtils; private logger: Logger; private setBeans(@Qualifier('loggerFactory') loggerFactory: LoggerFactory) { this.logger = loggerFactory.create('ColumnFactory'); } public createColumnTree(defs: (ColDef | ColGroupDef)[] | null, primaryColumns: boolean, existingTree?: IProvidedColumn[]) : { columnTree: IProvidedColumn[], treeDept: number; } { // column key creator dishes out unique column id's in a deterministic way, // so if we have two grids (that could be master/slave) with same column definitions, // then this ensures the two grids use identical id's. const columnKeyCreator = new ColumnKeyCreator(); const {existingCols, existingGroups, existingColKeys} = this.extractExistingTreeData(existingTree); columnKeyCreator.addExistingKeys(existingColKeys); // create am unbalanced tree that maps the provided definitions const unbalancedTree = this.recursivelyCreateColumns(defs, 0, primaryColumns, existingCols, columnKeyCreator, existingGroups); const treeDept = this.findMaxDept(unbalancedTree, 0); this.logger.log('Number of levels for grouped columns is ' + treeDept); const columnTree = this.balanceColumnTree(unbalancedTree, 0, treeDept, columnKeyCreator); const deptFirstCallback = (child: IProvidedColumn, parent: ProvidedColumnGroup) => { if (child instanceof ProvidedColumnGroup) { child.setupExpandable(); } // we set the original parents at the end, rather than when we go along, as balancing the tree // adds extra levels into the tree. so we can only set parents when balancing is done. child.setOriginalParent(parent); }; this.columnUtils.depthFirstOriginalTreeSearch(null, columnTree, deptFirstCallback); return { columnTree, treeDept }; } private extractExistingTreeData(existingTree?: IProvidedColumn[]): { existingCols: Column[], existingGroups: ProvidedColumnGroup[], existingColKeys: string[] } { const existingCols: Column[] = []; const existingGroups: ProvidedColumnGroup[] = []; const existingColKeys: string[] = []; if (existingTree) { this.columnUtils.depthFirstOriginalTreeSearch(null, existingTree, (item: IProvidedColumn) => { if (item instanceof ProvidedColumnGroup) { const group = item; existingGroups.push(group); } else { const col = item as Column; existingColKeys.push(col.getId()); existingCols.push(col); } }); } return {existingCols, existingGroups, existingColKeys}; } public createForAutoGroups(autoGroupCols: Column[], gridBalancedTree: IProvidedColumn[]): IProvidedColumn[] { const autoColBalancedTree: IProvidedColumn[] = []; autoGroupCols.forEach(col => { const fakeTreeItem = this.createAutoGroupTreeItem(gridBalancedTree, col); autoColBalancedTree.push(fakeTreeItem); }); return autoColBalancedTree; } private createAutoGroupTreeItem(balancedColumnTree: IProvidedColumn[], column: Column): IProvidedColumn { const dept = this.findDepth(balancedColumnTree); // at the end, this will be the top of the tree item. let nextChild: IProvidedColumn = column; for (let i = dept - 1; i >= 0; i--) { const autoGroup = new ProvidedColumnGroup( null, `FAKE_PATH_${column.getId()}}_${i}`, true, i ); this.context.createBean(autoGroup); autoGroup.setChildren([nextChild]); nextChild.setOriginalParent(autoGroup); nextChild = autoGroup; } // at this point, the nextChild is the top most item in the tree return nextChild; } private findDepth(balancedColumnTree: IProvidedColumn[]): number { let dept = 0; let pointer = balancedColumnTree; while (pointer && pointer[0] && pointer[0] instanceof ProvidedColumnGroup) { dept++; pointer = (pointer[0] as ProvidedColumnGroup).getChildren(); } return dept; } private balanceColumnTree( unbalancedTree: IProvidedColumn[], currentDept: number, columnDept: number, columnKeyCreator: ColumnKeyCreator ): IProvidedColumn[] { const result: IProvidedColumn[] = []; // go through each child, for groups, recurse a level deeper, // for columns we need to pad for (let i = 0; i < unbalancedTree.length; i++) { const child = unbalancedTree[i]; if (child instanceof ProvidedColumnGroup) { // child is a group, all we do is go to the next level of recursion const originalGroup = child; const newChildren = this.balanceColumnTree(originalGroup.getChildren(), currentDept + 1, columnDept, columnKeyCreator); originalGroup.setChildren(newChildren); result.push(originalGroup); } else { // child is a column - so here we add in the padded column groups if needed let firstPaddedGroup: ProvidedColumnGroup | undefined; let currentPaddedGroup: ProvidedColumnGroup | undefined; // this for loop will NOT run any loops if no padded column groups are needed for (let j = columnDept - 1; j >= currentDept; j--) { const newColId = columnKeyCreator.getUniqueKey(null, null); const colGroupDefMerged = this.createMergedColGroupDef(null); const paddedGroup = new ProvidedColumnGroup(colGroupDefMerged, newColId, true, currentDept); this.context.createBean(paddedGroup); if (currentPaddedGroup) { currentPaddedGroup.setChildren([paddedGroup]); } currentPaddedGroup = paddedGroup; if (!firstPaddedGroup) { firstPaddedGroup = currentPaddedGroup; } } // likewise this if statement will not run if no padded groups if (firstPaddedGroup && currentPaddedGroup) { result.push(firstPaddedGroup); const hasGroups = unbalancedTree.some(leaf => leaf instanceof ProvidedColumnGroup); if (hasGroups) { currentPaddedGroup.setChildren([child]); continue; } else { currentPaddedGroup.setChildren(unbalancedTree); break; } } result.push(child); } } return result; } private findMaxDept(treeChildren: IProvidedColumn[], dept: number): number { let maxDeptThisLevel = dept; for (let i = 0; i < treeChildren.length; i++) { const abstractColumn = treeChildren[i]; if (abstractColumn instanceof ProvidedColumnGroup) { const originalGroup = abstractColumn; const newDept = this.findMaxDept(originalGroup.getChildren(), dept + 1); if (maxDeptThisLevel < newDept) { maxDeptThisLevel = newDept; } } } return maxDeptThisLevel; } private recursivelyCreateColumns( defs: (ColDef | ColGroupDef)[] | null, level: number, primaryColumns: boolean, existingColsCopy: Column[], columnKeyCreator: ColumnKeyCreator, existingGroups: ProvidedColumnGroup[] ): IProvidedColumn[] { const result: IProvidedColumn[] = []; if (!defs) { return result; } defs.forEach((def: ColDef | ColGroupDef) => { let newGroupOrColumn: IProvidedColumn; if (this.isColumnGroup(def)) { newGroupOrColumn = this.createColumnGroup(primaryColumns, def as ColGroupDef, level, existingColsCopy, columnKeyCreator, existingGroups); } else { newGroupOrColumn = this.createColumn(primaryColumns, def as ColDef, existingColsCopy, columnKeyCreator); } result.push(newGroupOrColumn); }); return result; } private createColumnGroup( primaryColumns: boolean, colGroupDef: ColGroupDef, level: number, existingColumns: Column[], columnKeyCreator: ColumnKeyCreator, existingGroups: ProvidedColumnGroup[] ): ProvidedColumnGroup { const colGroupDefMerged = this.createMergedColGroupDef(colGroupDef); const groupId = columnKeyCreator.getUniqueKey(colGroupDefMerged.groupId || null, null); const originalGroup = new ProvidedColumnGroup(colGroupDefMerged, groupId, false, level); this.context.createBean(originalGroup); const existingGroup = this.findExistingGroup(colGroupDef, existingGroups); if (existingGroup && existingGroup.isExpanded()) { originalGroup.setExpanded(true); } const children = this.recursivelyCreateColumns(colGroupDefMerged.children, level + 1, primaryColumns, existingColumns, columnKeyCreator, existingGroups); originalGroup.setChildren(children); return originalGroup; } private createMergedColGroupDef(colGroupDef: ColGroupDef | null): ColGroupDef { const colGroupDefMerged: ColGroupDef = {} as ColGroupDef; assign(colGroupDefMerged, this.gridOptionsWrapper.getDefaultColGroupDef()); assign(colGroupDefMerged, colGroupDef); this.checkForDeprecatedItems(colGroupDefMerged); return colGroupDefMerged; } private createColumn( primaryColumns: boolean, colDef: ColDef, existingColsCopy: Column[] | null, columnKeyCreator: ColumnKeyCreator ): Column { const colDefMerged = this.mergeColDefs(colDef); this.checkForDeprecatedItems(colDefMerged); // see if column already exists let column = this.findExistingColumn(colDef, existingColsCopy); if (!column) { // no existing column, need to create one const colId = columnKeyCreator.getUniqueKey(colDefMerged.colId, colDefMerged.field); column = new Column(colDefMerged, colDef, colId, primaryColumns); this.context.createBean(column); } else { column.setColDef(colDefMerged, colDef); this.applyColumnState(column, colDefMerged); } return column; } private applyColumnState(column: Column, colDef: ColDef): void { // flex const flex = attrToNumber(colDef.flex); if (flex !== undefined) { column.setFlex(flex); } // width - we only set width if column is not flexing const noFlexThisCol = column.getFlex() <= 0; if (noFlexThisCol) { // both null and undefined means we skip, as it's not possible to 'clear' width (a column must have a width) const width = attrToNumber(colDef.width); if (width != null) { column.setActualWidth(width); } else { // otherwise set the width again, in case min or max width has changed, // and width needs to be adjusted. const widthBeforeUpdate = column.getActualWidth(); column.setActualWidth(widthBeforeUpdate); } } // sort - anything but undefined will set sort, thus null or empty string will clear the sort if (colDef.sort !== undefined) { if (colDef.sort == Constants.SORT_ASC || colDef.sort == Constants.SORT_DESC) { column.setSort(colDef.sort); } else { column.setSort(undefined); } } // sorted at - anything but undefined, thus null will clear the sortIndex const sortIndex = attrToNumber(colDef.sortIndex); if (sortIndex !== undefined) { column.setSortIndex(sortIndex); } // hide - anything but undefined, thus null will clear the hide const hide = attrToBoolean(colDef.hide); if (hide !== undefined) { column.setVisible(!hide); } // pinned - anything but undefined, thus null or empty string will remove pinned if (colDef.pinned !== undefined) { column.setPinned(colDef.pinned); } } public findExistingColumn(newColDef: ColDef, existingColsCopy: Column[] | null): Column | null { const res: Column | null = find(existingColsCopy, existingCol => { const existingColDef = existingCol.getUserProvidedColDef(); if (!existingColDef) { return false; } const newHasId = newColDef.colId != null; const newHasField = newColDef.field != null; if (newHasId) { return existingCol.getId() === newColDef.colId; } if (newHasField) { return existingColDef.field === newColDef.field; } // if no id or field present, then try object equivalence. if (existingColDef === newColDef) { return true; } return false; }); // make sure we remove, so if user provided duplicate id, then we don't have more than // one column instance for colDef with common id if (existingColsCopy && res) { removeFromArray(existingColsCopy, res); } return res; } public findExistingGroup(newGroupDef: ColGroupDef, existingGroups: ProvidedColumnGroup[]): ProvidedColumnGroup | null { const res: ProvidedColumnGroup | null = find(existingGroups, existingGroup => { const existingDef = existingGroup.getColGroupDef() if (!existingDef) { return false; } const newHasId = newGroupDef.groupId != null; if (newHasId) { return existingGroup.getId() === newGroupDef.groupId; } return false; }); // make sure we remove, so if user provided duplicate id, then we don't have more than // one column instance for colDef with common id if (res) { removeFromArray(existingGroups, res); } return res; } public mergeColDefs(colDef: ColDef) { // start with empty merged definition const colDefMerged: ColDef = {} as ColDef; // merge properties from default column definitions const defaultColDef = this.gridOptionsWrapper.getDefaultColDef(); mergeDeep(colDefMerged, defaultColDef, true, true); // merge properties from column type properties let columnType = colDef.type; if (!columnType) { columnType = defaultColDef && defaultColDef.type; } // if type of both colDef and defaultColDef, then colDef gets preference if (columnType) { this.assignColumnTypes(columnType, colDefMerged); } // merge properties from column definitions mergeDeep(colDefMerged, colDef, true, true); return colDefMerged; } private assignColumnTypes(type: string | string[], colDefMerged: ColDef) { let typeKeys: string[] = []; if (type instanceof Array) { const invalidArray = type.some(a => typeof a !== 'string'); if (invalidArray) { console.warn("ag-grid: if colDef.type is supplied an array it should be of type 'string[]'"); } else { typeKeys = type; } } else if (typeof type === 'string') { typeKeys = type.split(','); } else { console.warn("ag-grid: colDef.type should be of type 'string' | 'string[]'"); return; } // merge user defined with default column types const allColumnTypes = assign({}, DefaultColumnTypes); const userTypes = this.gridOptionsWrapper.getColumnTypes() || {}; iterateObject(userTypes, (key, value) => { if (key in allColumnTypes) { console.warn(`AG Grid: the column type '${key}' is a default column type and cannot be overridden.`); } else { allColumnTypes[key] = value; } }); typeKeys.forEach((t) => { const typeColDef = allColumnTypes[t.trim()]; if (typeColDef) { mergeDeep(colDefMerged, typeColDef, true, true); } else { console.warn("ag-grid: colDef.type '" + t + "' does not correspond to defined gridOptions.columnTypes"); } }); } private checkForDeprecatedItems(colDef: AbstractColDef) { if (colDef) { const colDefNoType = colDef as any; // take out the type, so we can access attributes not defined in the type if (colDefNoType.group !== undefined) { console.warn('ag-grid: colDef.group is invalid, please check documentation on how to do grouping as it changed in version 3'); } if (colDefNoType.headerGroup !== undefined) { console.warn('ag-grid: colDef.headerGroup is invalid, please check documentation on how to do grouping as it changed in version 3'); } if (colDefNoType.headerGroupShow !== undefined) { console.warn('ag-grid: colDef.headerGroupShow is invalid, should be columnGroupShow, please check documentation on how to do grouping as it changed in version 3'); } if (colDefNoType.suppressRowGroup !== undefined) { console.warn('ag-grid: colDef.suppressRowGroup is deprecated, please use colDef.type instead'); } if (colDefNoType.suppressAggregation !== undefined) { console.warn('ag-grid: colDef.suppressAggregation is deprecated, please use colDef.type instead'); } if (colDefNoType.suppressRowGroup || colDefNoType.suppressAggregation) { console.warn('ag-grid: colDef.suppressAggregation and colDef.suppressRowGroup are deprecated, use allowRowGroup, allowPivot and allowValue instead'); } if (colDefNoType.displayName) { console.warn("ag-grid: Found displayName " + colDefNoType.displayName + ", please use headerName instead, displayName is deprecated."); colDefNoType.headerName = colDefNoType.displayName; } } } // if object has children, we assume it's a group private isColumnGroup(abstractColDef: ColDef | ColGroupDef): boolean { return (abstractColDef as ColGroupDef).children !== undefined; } }
the_stack
import EventEmitter from 'eventemitter3' import delay, { ClearablePromise } from 'delay' import PCancelable from 'p-cancelable' import pEvent from 'p-event' import pTimeout from 'p-timeout' import uniq from 'lodash/uniq' import { BaseMessage, ChatCommands, Commands, Events, GlobalUserStateTags, Messages, NoticeMessages, RoomStateMessage, UserStateMessage, } from '../twitch' import createLogger, { Logger } from '../utils/logger' import Client from '../Client' import { ClientEvents } from '../Client/client-types' import * as Errors from './chat-errors' import * as parsers from './utils/parsers' import * as sanitizers from './utils/chat-sanitizers' import * as validators from './utils/chat-validators' import { ChatReadyStates, EventTypes, ChatOptions, ChannelStates, NoticeCompounds, PrivateMessageCompounds, UserNoticeCompounds, ChannelState, } from './chat-types' /** * Interact with Twitch chat. * * ## Connecting * * ```js * const token = 'cfabdegwdoklmawdzdo98xt2fo512y' * const username = 'ronni' * const { chat } = new TwitchJs({ token, username }) * * chat.connect().then(globalUserState => { * // Do stuff ... * }) * ``` * * **Note:** Connecting with a `token` and a `username` is optional. * * Once connected, `chat.userState` will contain * [[GlobalUserStateTags|global user state information]]. * * ## Joining a channel * * ```js * const channel = '#dallas' * * chat.join(channel).then(channelState => { * // Do stuff with channelState... * }) * ``` * * After joining a channel, `chat.channels[channel]` will contain * [[ChannelState|channel state information]]. * * ## Listening for events * * ```js * // Listen to all events * chat.on('*', message => { * // Do stuff with message ... * }) * * // Listen to private messages * chat.on('PRIVMSG', privateMessage => { * // Do stuff with privateMessage ... * }) * ``` * * Events are nested; for example: * * ```js * // Listen to subscriptions only * chat.on('USERNOTICE/SUBSCRIPTION', userStateMessage => { * // Do stuff with userStateMessage ... * }) * * // Listen to all user notices * chat.on('USERNOTICE', userStateMessage => { * // Do stuff with userStateMessage ... * }) * ``` * * For added convenience, TwitchJS also exposes event constants. * * ```js * const { chat } = new TwitchJs({ token, username }) * * // Listen to all user notices * chat.on(chat.events.USER_NOTICE, userStateMessage => { * // Do stuff with userStateMessage ... * }) * ``` * * ## Sending messages * * To send messages, [Chat] must be initialized with a `username` and a * [`token`](../#authentication) with `chat_login` scope. * * All messages sent to Twitch are automatically rate-limited according to * [Twitch Developer documentation](https://dev.twitch.tv/docs/irc/guide/#command--message-limits). * * ### Speak in channel * * ```js * const channel = '#dallas' * * chat * .say(channel, 'Kappa Keepo Kappa') * // Optionally ... * .then(() => { * // ... do stuff on success ... * }) * ``` * * ### Send command to channel * * All chat commands are currently supported and exposed as camel-case methods. For * example: * * ```js * const channel = '#dallas' * * // Enable followers-only for 1 week * chat.followersOnly(channel, '1w') * * // Ban ronni * chat.ban(channel, 'ronni') * ``` * * **Note:** `Promise`-resolves for each commands are * [planned](https://github.com/twitch-devs/twitch-js/issues/87). * * ## Joining multiple channels * * ```js * const channels = ['#dallas', '#ronni'] * * Promise.all(channels.map(channel => chat.join(channel))).then(channelStates => { * // Listen to all messages from #dallas only * chat.on('#dallas', message => { * // Do stuff with message ... * }) * * // Listen to private messages from #dallas and #ronni * chat.on('PRIVMSG', privateMessage => { * // Do stuff with privateMessage ... * }) * * // Listen to private messages from #dallas only * chat.on('PRIVMSG/#dallas', privateMessage => { * // Do stuff with privateMessage ... * }) * * // Listen to all private messages from #ronni only * chat.on('PRIVMSG/#ronni', privateMessage => { * // Do stuff with privateMessage ... * }) * }) * ``` * * ### Broadcasting to all channels * * ```js * chat * .broadcast('Kappa Keepo Kappa') * // Optionally ... * .then(userStateMessages => { * // ... do stuff with userStateMessages on success ... * }) * ``` */ class Chat extends EventEmitter<EventTypes> { static Commands = Commands static Events = Events static CompoundEvents = { [Events.NOTICE]: NoticeCompounds, [Events.PRIVATE_MESSAGE]: PrivateMessageCompounds, [Events.USER_NOTICE]: UserNoticeCompounds, } private _options: ChatOptions private _log: Logger private _client?: Client private _readyState: ChatReadyStates = ChatReadyStates.WAITING private _connectionAttempts = 0 private _connectionInProgress?: ClearablePromise<void> | void private _globalUserState?: GlobalUserStateTags private _channelState: ChannelStates = {} private _isAuthenticated = false /** * Chat constructor. */ constructor(options: Partial<ChatOptions>) { super() this._options = validators.chatOptions(options) // Create logger. this._log = createLogger({ name: 'Chat', ...this._options.log }) } /** * Connect to Twitch. */ async connect(): Promise<void> { try { this._readyState = ChatReadyStates.CONNECTING if (this._connectionInProgress) { return this._connectionInProgress } this._connectionInProgress = await pTimeout( this._handleConnectionAttempt(), this._options.connectionTimeout, ) this._readyState = ChatReadyStates.CONNECTED this._connectionAttempts = 0 } catch (error) { if ( this._readyState !== ChatReadyStates.DISCONNECTING && this._readyState !== ChatReadyStates.DISCONNECTED ) { this._log.info('retrying ...') await delay(this._options.connectionTimeout) return await this._handleAuthenticationFailure(error as BaseMessage) } else { throw error } } } /** * Updates the client options after instantiation. * To update `token` or `username`, use `reconnect()`. */ updateOptions(options: Partial<ChatOptions>) { const { token, username } = this._options this._options = validators.chatOptions({ ...options, token, username }) } /** * Send a raw message to Twitch. */ send( message: string, options?: Partial<{ priority: number; isModerator: boolean }>, ): Promise<void> { if (!this._client) { throw new Errors.ChatError('Not connected') } return this._client.send(message, options) } /** * Disconnected from Twitch. */ disconnect() { this._readyState = ChatReadyStates.DISCONNECTING this._client?.disconnect() this._readyState = ChatReadyStates.DISCONNECTED } /** * Reconnect to Twitch, providing new options to the client. */ async reconnect(options?: Partial<ChatOptions>) { if (options) { this._options = validators.chatOptions({ ...this._options, ...options }) } this._connectionInProgress = undefined this._readyState = ChatReadyStates.RECONNECTING const channels = this._getChannels() this.disconnect() await this.connect() return Promise.all(channels.map((channel) => this.join(channel))) } /** * Join a channel. * * @example <caption>Joining #dallas</caption> * const channel = '#dallas' * * chat.join(channel).then(channelState => { * // Do stuff with channelState... * }) * * @example <caption>Joining multiple channels</caption> * const channels = ['#dallas', '#ronni'] * * Promise.all(channels.map(channel => chat.join(channel))) * .then(channelStates => { * // Listen to all PRIVMSG * chat.on('PRIVMSG', privateMessage => { * // Do stuff with privateMessage ... * }) * * // Listen to PRIVMSG from #dallas ONLY * chat.on('PRIVMSG/#dallas', privateMessage => { * // Do stuff with privateMessage ... * }) * // Listen to all PRIVMSG from #ronni ONLY * chat.on('PRIVMSG/#ronni', privateMessage => { * // Do stuff with privateMessage ... * }) * }) */ async join(channel: string) { channel = validators.channel(channel) const joinProfiler = this._log.profile(`joining ${channel}`) const [roomState, userState] = await Promise.all([ pEvent<string, RoomStateMessage>( // @ts-expect-error EventTypes breaks this this, `${Commands.ROOM_STATE}/${channel}`, ), this._isAuthenticated ? pEvent<string, UserStateMessage>( // @ts-expect-error EventTypes breaks this this, `${Commands.USER_STATE}/${channel}`, ) : undefined, this.send(`${Commands.JOIN} ${channel}`), ]) const channelState = { roomState: roomState.tags, userState: userState ? userState.tags : undefined, } this._setChannelState(roomState.channel, channelState) joinProfiler.done(`Joined ${channel}`) return channelState } /** * Depart from a channel. */ part(channel: string) { channel = validators.channel(channel) this._log.info(`parting ${channel}`) this._removeChannelState(channel) return this.send(`${Commands.PART} ${channel}`) } /** * Send a message to a channel. */ async say( channel: string, message: string, options: { priority?: number } = {}, ): Promise<void> { if (!this._isAuthenticated) { throw new Errors.ChatError( 'To send messages, please connect with a token and username', ) } channel = validators.channel(channel) const isCommand = message.startsWith('/') const isModerator = this._channelState[channel]?.userState?.mod === '1' if (isCommand) { this._log.info(`CMD/${channel} :${message}`) } else { this._log.info(`PRIVMSG/${channel} :${message}`) } const resolver: Promise<void | UserStateMessage> = isCommand ? // Commands do not result in USERSTATE messages Promise.resolve() : pEvent<string, UserStateMessage>( // @ts-expect-error EventTypes breaks this this, `${Commands.USER_STATE}/${channel}`, ) await Promise.all([ resolver, this.send(`${Commands.PRIVATE_MESSAGE} ${channel} :${message}`, { isModerator, ...options, }), ]) } /** * Broadcast message to all connected channels. */ async broadcast(message: string) { if (!this._isAuthenticated) { throw new Errors.ChatError( 'To broadcast, please connect with a token and username', ) } return this._getChannels().map((channel) => this.say(channel, message)) } /** * This command will allow you to permanently ban a user from the chat room. */ async ban(channel: string, username: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.BAN} ${username}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.BAN_SUCCESS}/${channel}`, `${NoticeCompounds.ALREADY_BANNED}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * This command will allow you to block all messages from a specific user in * chat and whispers if you do not wish to see their comments. */ async block(channel: string, username: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.BLOCK} ${username}` return this.say(channel, message) } /** * Single message removal on a channel. */ async delete(channel: string, targetMessageId: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.DELETE} ${targetMessageId}` return this.say(channel, message) } /** * This command will allow the Broadcaster and chat moderators to completely * wipe the previous chat history. */ async clear(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.CLEAR}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${Commands.CLEAR_CHAT}/${channel}`], ), this.say(channel, message), ]) return notice } /** * Allows you to change the color of your username. */ async color(channel: string, color: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.COLOR} ${color}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.COLOR_CHANGED}/${channel}`], ), this.say(channel, message), ]) return notice } /** * An Affiliate and Partner command that runs a commercial for all of your * viewers. */ async commercial( channel: string, length: 30 | 60 | 90 | 120 | 150 | 180, ): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.COMMERCIAL} ${length}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.COMMERCIAL_SUCCESS}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command allows you to set your room so only messages that are 100% * emotes are allowed. */ async emoteOnly(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.EMOTE_ONLY}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.EMOTE_ONLY_ON}/${channel}`, `${NoticeCompounds.ALREADY_EMOTE_ONLY_ON}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * This command allows you to disable emote only mode if you previously * enabled it. */ async emoteOnlyOff(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.EMOTE_ONLY_OFF}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.EMOTE_ONLY_OFF}/${channel}`, `${NoticeCompounds.ALREADY_EMOTE_ONLY_OFF}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * This command allows you or your mods to restrict chat to all or some of * your followers, based on how long they’ve followed. * @param period - Follow time from 0 minutes (all followers) to 3 months. */ async followersOnly( channel: string, period: string, ): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.FOLLOWERS_ONLY} ${period}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.FOLLOWERS_ONZERO}/${channel}`, `${NoticeCompounds.FOLLOWERS_ON}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * This command will disable followers only mode if it was previously enabled * on the channel. */ async followersOnlyOff(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.FOLLOWERS_ONLY_OFF}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.FOLLOWERS_OFF}/${channel}`], ), this.say(channel, message), ]) return notice } async help(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.HELP}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.CMDS_AVAILABLE}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command will allow you to host another channel on yours. */ async host(channel: string, hostChannel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.HOST} ${hostChannel}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.HOST_ON}/${channel}`], ), this.say(channel, message), ]) return notice } /** * Adds a stream marker (with an optional description, max 140 characters) at * the current timestamp. You can use markers in the Highlighter for easier * editing. */ async marker(channel: string, description: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.MARKER} ${description.slice(0, 140)}` return this.say(channel, message) } /** * This command will color your text based on your chat name color. */ async me(channel: string, text: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.ME} ${text}` return this.say(channel, message) } /** * This command will allow you to promote a user to a channel moderator. */ async mod(channel: string, username: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.MOD} ${username}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.MOD_SUCCESS}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command will display a list of all chat moderators for that specific * channel. */ async mods(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.MODS}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.ROOM_MODS}/${channel}`], ), this.say(channel, message), ]) return notice } /** * @deprecated */ async r9K(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.R9K}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.R9K_ON}/${channel}`, `${NoticeCompounds.ALREADY_R9K_ON}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * @deprecated */ async r9KOff(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.R9K_OFF}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.R9K_OFF}/${channel}`, `${NoticeCompounds.ALREADY_R9K_OFF}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * This command will send the viewer to another live channel. */ async raid(channel: string, raidChannel: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.RAID} ${raidChannel}` return this.say(channel, message) } /** * This command allows you to set a limit on how often users in the chat room * are allowed to send messages (rate limiting). */ async slow(channel: string, seconds: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.SLOW} ${seconds}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.SLOW_ON}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command allows you to disable slow mode if you had previously set it. */ async slowOff(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.SLOW_OFF}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.SLOW_OFF}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command allows you to set your room so only users subscribed to you * can talk in the chat room. If you don't have the subscription feature it * will only allow the Broadcaster and the channel moderators to talk in the * chat room. */ async subscribers(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.SUBSCRIBERS}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.SUBS_ON}/${channel}`, `${NoticeCompounds.ALREADY_SUBS_ON}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * This command allows you to disable subscribers only chat room if you * previously enabled it. */ async subscribersOff(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.SUBSCRIBERS_OFF}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [ `${NoticeCompounds.SUBS_OFF}/${channel}`, `${NoticeCompounds.ALREADY_SUBS_OFF}/${channel}`, ], ), this.say(channel, message), ]) return notice } /** * This command allows you to temporarily ban someone from the chat room for * 10 minutes by default. This will be indicated to yourself and the * temporarily banned subject in chat on a successful temporary ban. A new * timeout command will overwrite an old one. */ async timeout( channel: string, username: string, timeout?: number, ): Promise<NoticeMessages> { channel = validators.channel(channel) const timeoutArg = timeout ? ` ${timeout}` : '' const message = `/${ChatCommands.TIMEOUT} ${username}${timeoutArg}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.TIMEOUT_SUCCESS}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command will allow you to lift a permanent ban on a user from the * chat room. You can also use this command to end a ban early; this also * applies to timeouts. */ async unban(channel: string, username: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.UNBAN} ${username}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.UNBAN_SUCCESS}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command will allow you to remove users from your block list that you * previously added. */ async unblock(channel: string, username: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.UNBLOCK} ${username}` return this.say(channel, message) } /** * Using this command will revert the embedding from hosting a channel and * return it to its normal state. */ async unhost(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.UNHOST}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.HOST_OFF}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command will allow you to demote an existing moderator back to viewer * status (removing their moderator abilities). */ async unmod(channel: string, username: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.UNMOD} ${username}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.UNMOD_SUCCESS}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command will cancel the raid. */ async unraid(channel: string): Promise<NoticeMessages> { channel = validators.channel(channel) const message = `/${ChatCommands.UNRAID}` const [notice] = await Promise.all([ pEvent<string, NoticeMessages>( // @ts-expect-error EventTypes breaks this this, [`${NoticeCompounds.UNRAID_SUCCESS}/${channel}`], ), this.say(channel, message), ]) return notice } /** * This command will grant VIP status to a user. */ unvip(channel: string, username: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.UNVIP} ${username}` return this.say(channel, message) } /** * This command will grant VIP status to a user. */ vip(channel: string, username: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.VIP} ${username}` return this.say(channel, message) } /** * This command will display a list of VIPs for that specific channel. */ vips(channel: string): Promise<void> { channel = validators.channel(channel) const message = `/${ChatCommands.VIPS}` return this.say(channel, message) } /** * This command sends a private message to another user on Twitch. */ async whisper(username: string, message: string): Promise<void> { if (!this._isAuthenticated) { throw new Errors.ChatError( 'To whisper, please connect with a token and username', ) } const command = `/${ChatCommands.WHISPER} ${username} ${message}` return this.send(command) } private _handleConnectionAttempt(): Promise<void> { return new PCancelable((resolve, reject) => { const connectProfiler = this._log.profile('connecting ...') const { token, username } = this._options // Connect ... this._readyState = ChatReadyStates.CONNECTING // Increment connection attempts. this._connectionAttempts += 1 if (this._client) { // Remove all listeners, just in case. this._client.removeAllListeners() } // Create client and connect. this._client = new Client(this._options) // Handle disconnects. this._client.on(ClientEvents.DISCONNECTED, this._handleDisconnect, this) // Listen for reconnects. this._client.once(ClientEvents.RECONNECT, () => this.reconnect()) // Listen for authentication failure. this._client.once(ClientEvents.AUTHENTICATION_FAILED, reject) // Once the client is connected, resolve ... this._client.once(ClientEvents.CONNECTED, (message) => { if (token && username) { this._handleAuthenticated(message) } this._handleJoinsAfterConnect() resolve() connectProfiler.done('connected') }) // Handle messages. this._client.on(ClientEvents.ALL, this._handleMessage, this) }) } private _handleDisconnect() { this._log.info('disconnecting ...') if (this._connectionInProgress) { this._connectionInProgress.clear() } this._connectionInProgress = undefined this._isAuthenticated = false this._clearChannelState() this._log.info('disconnected') } private _handleAuthenticated(message: BaseMessage) { const globalUserStateMessage = parsers.globalUserStateMessage(message) this._globalUserState = globalUserStateMessage.tags this._isAuthenticated = true } private async _handleAuthenticationFailure(originError: BaseMessage) { try { this._log.info('retrying ...') const token = await this._options.onAuthenticationFailure?.() if (token) { this._log.info('re-authenticating ...') this._options = { ...this._options, token } return await this.connect() } } catch (error) { this._log.error(error as Error, 're-authentication failed') throw new Errors.AuthenticationError( originError?.message || 'Login authentication failed', originError, ) } } private _handleMessage(baseMessage: BaseMessage) { if (baseMessage instanceof Error) { this.emit('error', baseMessage) return } try { const [eventName, message] = this._parseMessageForEmitter(baseMessage) this._emit(eventName, message) } catch (error) { /** * Catch errors while parsing base messages into events. */ this._log.error( '\n' + 'An error occurred while attempting to parse a message into a ' + 'event. Please use the following stack trace and raw message to ' + 'resolve the bug in the TwitchJS source code, and then issue a ' + 'pull request at https://github.com/twitch-js/twitch-js/compare\n' + '\n' + 'Stack trace:\n' + `${error}\n` + '\n' + 'Base message:\n' + JSON.stringify(baseMessage), ) this.emit(ClientEvents.ERROR_ENCOUNTERED, error as Error) } } private async _handleJoinsAfterConnect() { const channels = this._getChannels() await Promise.all(channels.map((channel) => this.join(channel))) } private _getChannels() { return Object.keys(this._channelState) } private _getChannelState(channel: string): ChannelState | undefined { return this._channelState[channel] } private _setChannelState(channel: string, state: ChannelState) { this._channelState[channel] = state } private _removeChannelState(channel: string) { this._channelState = Object.entries(this._channelState).reduce( (channelStates, [name, state]) => { return name === channel ? channelStates : { ...channelStates, [name]: state } }, {}, ) } private _clearChannelState() { this._channelState = {} } private _parseMessageForEmitter( baseMessage: BaseMessage, ): [string, Messages] { const channel = sanitizers.channel(baseMessage.channel) const baseEventName = baseMessage.event || baseMessage.command switch (baseMessage.command) { case Events.JOIN: { const message = parsers.joinMessage(baseMessage) const eventName = `${baseEventName}/${channel}` return [eventName, message] } case Events.PART: { const message = parsers.partMessage(baseMessage) const eventName = `${baseEventName}/${channel}` return [eventName, message] } case Events.NAMES: { const message = parsers.namesMessage(baseMessage) const eventName = `${baseEventName}/${channel}` return [eventName, message] } case Events.NAMES_END: { const message = parsers.namesEndMessage(baseMessage) const eventName = `${baseEventName}/${channel}` return [eventName, message] } case Events.CLEAR_CHAT: { const message = parsers.clearChatMessage(baseMessage) const eventName = `${baseEventName}/${message.event}/${channel}` return [eventName, message] } case Events.CLEAR_MESSAGE: { const message = parsers.clearMessageMessage(baseMessage) const eventName = `${baseEventName}/${channel}` return [eventName, message] } case Events.HOST_TARGET: { const message = parsers.hostTargetMessage(baseMessage) const eventName = `${baseEventName}/${channel}` return [eventName, message] } case Events.MODE: { const message = parsers.modeMessage(baseMessage) const eventName = `${baseEventName}/${channel}` const channelState = this._getChannelState(channel) if ( this._isAuthenticated && typeof channelState?.userState !== 'undefined' && message.username === this._options.username ) { this._setChannelState(channel, { ...channelState, userState: { ...channelState.userState, mod: message.isModerator ? '1' : '0', isModerator: message.isModerator, }, }) } return [eventName, message] } case Events.USER_STATE: { const message = parsers.userStateMessage(baseMessage) const eventName = `${baseEventName}/${channel}` const channelState = this._getChannelState(channel) if (channelState) { this._setChannelState(channel, { ...channelState, userState: message.tags, }) } return [eventName, message] } case Events.ROOM_STATE: { const message = parsers.roomStateMessage(baseMessage) const eventName = `${baseEventName}/${channel}` this._setChannelState(channel, { ...this._getChannelState(channel), roomState: message, }) return [eventName, message] } case Events.NOTICE: { const message = parsers.noticeMessage(baseMessage) const eventName = `${baseEventName}/${message.event}/${channel}` return [eventName, message] } case Events.USER_NOTICE: { const message = parsers.userNoticeMessage(baseMessage) const eventName = `${baseEventName}/${message.event}/${channel}` return [eventName, message] } case Events.PRIVATE_MESSAGE: { const message = parsers.privateMessage(baseMessage) const eventName = `${baseEventName}/${message.event}/${channel}` return [eventName, message] } default: { const eventName = channel ? `${baseEventName}/${channel}` : baseEventName return [eventName, baseMessage] } } } private _emit(eventName: string, message: Messages) { try { if (eventName) { this._log.info(message, eventName) const events = uniq(eventName.split('/')) events .filter((part) => part !== '#') .reduce<string[]>((parents, part) => { const eventParts = [...parents, part] const eventCompound = eventParts.join('/') if (eventParts.length > 1) { super.emit(part, message) } super.emit(eventCompound, message) return eventParts }, []) } // Emit message under the ALL `*` event. super.emit(Events.ALL, message) } catch (error) { /** * Catch external implementation errors. */ this._log.error( '\n' + `While attempting to handle the ${message.command} event, an ` + 'error occurred in your implementation. To avoid seeing this ' + 'message, please resolve the error:\n' + '\n' + `${(error as Error).stack}\n` + '\n' + 'Parsed messages:\n' + JSON.stringify(message), ) this.emit(ClientEvents.ERROR_ENCOUNTERED, error as Error) } } } export default Chat
the_stack
import * as angular from 'angular'; import { find, map, prop, UrlMatcher } from '../src/index'; import { UIRouter, UrlMatcherFactory, UrlService } from '@uirouter/core'; declare var inject; const module = angular['mock'].module; describe('UrlMatcher', function () { let router: UIRouter; let $umf: UrlMatcherFactory; let $url: UrlService; beforeEach(inject(function ($uiRouter, $urlMatcherFactory, $urlService) { router = $uiRouter; $umf = $urlMatcherFactory; $url = $urlService; })); describe('provider', function () { it('should factory matchers with correct configuration', function () { $umf.caseInsensitive(false); expect($umf.compile('/hello').exec('/HELLO')).toBeNull(); $umf.caseInsensitive(true); expect($umf.compile('/hello').exec('/HELLO')).toEqual({}); $umf.strictMode(true); expect($umf.compile('/hello').exec('/hello/')).toBeNull(); $umf.strictMode(false); expect($umf.compile('/hello').exec('/hello/')).toEqual({}); }); it('should correctly validate UrlMatcher interface', function () { let m = $umf.compile('/'); expect($umf.isMatcher(m)).toBe(true); m = angular.extend({}, m, { validates: null }); expect($umf.isMatcher(m)).toBe(false); }); }); it('should match static URLs', function () { expect($umf.compile('/hello/world').exec('/hello/world')).toEqual({}); }); it('should match static case insensitive URLs', function () { expect($umf.compile('/hello/world', { caseInsensitive: true }).exec('/heLLo/World')).toEqual({}); }); it('should match against the entire path', function () { const matcher = $umf.compile('/hello/world', { strict: true }); expect(matcher.exec('/hello/world/')).toBeNull(); expect(matcher.exec('/hello/world/suffix')).toBeNull(); }); it('should parse parameter placeholders', function () { const matcher = $umf.compile('/users/:id/details/{type}/{repeat:[0-9]+}?from&to'); expect(matcher.parameters().map(prop('id'))).toEqual(['id', 'type', 'repeat', 'from', 'to']); }); it('should encode and decode duplicate query string values as array', function () { const matcher = $umf.compile('/?foo'), array = { foo: ['bar', 'baz'] }; expect(matcher.exec('/', array)).toEqual(array); expect(matcher.format(array)).toBe('/?foo=bar&foo=baz'); }); it('should encode and decode slashes in parameter values as ~2F', function () { const matcher1 = $umf.compile('/:foo'); expect(matcher1.format({ foo: '/' })).toBe('/~2F'); expect(matcher1.format({ foo: '//' })).toBe('/~2F~2F'); expect(matcher1.exec('/')).toBeTruthy(); expect(matcher1.exec('//')).not.toBeTruthy(); expect(matcher1.exec('/').foo).toBe(''); expect(matcher1.exec('/123').foo).toBe('123'); expect(matcher1.exec('/~2F').foo).toBe('/'); expect(matcher1.exec('/123~2F').foo).toBe('123/'); // param :foo should match between two slashes const matcher2 = $umf.compile('/:foo/'); expect(matcher2.exec('/')).not.toBeTruthy(); expect(matcher2.exec('//')).toBeTruthy(); expect(matcher2.exec('//').foo).toBe(''); expect(matcher2.exec('/123/').foo).toBe('123'); expect(matcher2.exec('/~2F/').foo).toBe('/'); expect(matcher2.exec('/123~2F/').foo).toBe('123/'); }); it('should encode and decode tildes in parameter values as ~~', function () { const matcher1 = $umf.compile('/:foo'); expect(matcher1.format({ foo: 'abc' })).toBe('/abc'); expect(matcher1.format({ foo: '~abc' })).toBe('/~~abc'); expect(matcher1.format({ foo: '~2F' })).toBe('/~~2F'); expect(matcher1.exec('/abc').foo).toBe('abc'); expect(matcher1.exec('/~~abc').foo).toBe('~abc'); expect(matcher1.exec('/~~2F').foo).toBe('~2F'); }); describe('snake-case parameters', function () { it('should match if properly formatted', function () { const matcher = $umf.compile('/users/?from&to&snake-case&snake-case-triple'); expect(matcher.parameters().map(prop('id'))).toEqual(['from', 'to', 'snake-case', 'snake-case-triple']); }); it('should not match if invalid', function () { let err = "Invalid parameter name '-snake' in pattern '/users/?from&to&-snake'"; expect(function () { $umf.compile('/users/?from&to&-snake'); }).toThrowError(err); err = "Invalid parameter name 'snake-' in pattern '/users/?from&to&snake-'"; expect(function () { $umf.compile('/users/?from&to&snake-'); }).toThrowError(err); }); }); describe('parameters containing periods', function () { it('should match if properly formatted', function () { const matcher = $umf.compile('/users/?from&to&with.periods&with.periods.also'); const params = matcher.parameters().map(function (p) { return p.id; }); expect(params.sort()).toEqual(['from', 'to', 'with.periods', 'with.periods.also']); }); it('should not match if invalid', function () { let err = new Error("Invalid parameter name '.periods' in pattern '/users/?from&to&.periods'"); expect(function () { $umf.compile('/users/?from&to&.periods'); }).toThrow(err); err = new Error("Invalid parameter name 'periods.' in pattern '/users/?from&to&periods.'"); expect(function () { $umf.compile('/users/?from&to&periods.'); }).toThrow(err); }); }); describe('.exec()', function () { it('should capture parameter values', function () { const m = $umf.compile('/users/:id/details/{type}/{repeat:[0-9]+}?from&to', { strict: false }); expect(m.exec('/users/123/details//0', {})).toEqual({ id: '123', type: '', repeat: '0' }); }); it('should capture catch-all parameters', function () { const m = $umf.compile('/document/*path'); expect(m.exec('/document/a/b/c', {})).toEqual({ path: 'a/b/c' }); expect(m.exec('/document/', {})).toEqual({ path: '' }); }); it('should use the optional regexp with curly brace placeholders', function () { const m = $umf.compile('/users/:id/details/{type}/{repeat:[0-9]+}?from&to'); expect(m.exec('/users/123/details/what/thisShouldBeDigits', {})).toBeNull(); }); it("should not use optional regexp for '/'", function () { const m = $umf.compile('/{language:(?:fr|en|de)}'); expect(m.exec('/', {})).toBeNull(); }); it('should work with empty default value', function () { const m = $umf.compile('/foo/:str', { state: { params: { str: { value: '' } } } }); expect(m.exec('/foo/', {})).toEqual({ str: '' }); }); it('should work with empty default value for regex', function () { const m = $umf.compile('/foo/{param:(?:foo|bar|)}', { state: { params: { param: { value: '' } } } }); expect(m.exec('/foo/', {})).toEqual({ param: '' }); }); it('should treat the URL as already decoded and does not decode it further', function () { expect($umf.compile('/users/:id').exec('/users/100%25', {})).toEqual({ id: '100%25' }); }); xit('should allow embedded capture groups', function () { const shouldPass = { '/url/{matchedParam:([a-z]+)}/child/{childParam}': '/url/someword/child/childParam', '/url/{matchedParam:([a-z]+)}/child/{childParam}?foo': '/url/someword/child/childParam', }; angular.forEach(shouldPass, function (url, route) { expect($umf.compile(route).exec(url, {})).toEqual({ childParam: 'childParam', matchedParam: 'someword', }); }); }); it('should throw on unbalanced capture list', function () { const shouldThrow = { '/url/{matchedParam:([a-z]+)}/child/{childParam}': '/url/someword/child/childParam', '/url/{matchedParam:([a-z]+)}/child/{childParam}?foo': '/url/someword/child/childParam', }; angular.forEach(shouldThrow, function (url, route) { expect(function () { $umf.compile(route).exec(url, {}); }).toThrowError("Unbalanced capture group in route '" + route + "'"); }); const shouldPass = { '/url/{matchedParam:[a-z]+}/child/{childParam}': '/url/someword/child/childParam', '/url/{matchedParam:[a-z]+}/child/{childParam}?foo': '/url/someword/child/childParam', }; angular.forEach(shouldPass, function (url, route) { expect(function () { $umf.compile(route).exec(url, {}); }).not.toThrow(); }); }); }); describe('.format()', function () { it('should reconstitute the URL', function () { const m = $umf.compile('/users/:id/details/{type}/{repeat:[0-9]+}?from'), params = { id: '123', type: 'default', repeat: 444, ignored: 'value', from: '1970' }; expect(m.format(params)).toEqual('/users/123/details/default/444?from=1970'); }); it('should encode URL parameters', function () { expect($umf.compile('/users/:id').format({ id: '100%' })).toEqual('/users/100%25'); }); it('encodes URL parameters with hashes', function () { const m = $umf.compile('/users/:id#:section'); expect(m.format({ id: 'bob', section: 'contact-details' })).toEqual('/users/bob#contact-details'); }); it('should trim trailing slashes when the terminal value is optional', function () { const config = { state: { params: { id: { squash: true, value: '123' } } } }, m = $umf.compile('/users/:id', config), params = { id: '123' }; expect(m.format(params)).toEqual('/users'); }); it('should format query parameters from parent, child, grandchild matchers', function () { const m = $umf.compile('/parent?qParent'); const m2 = m.append($umf.compile('/child?qChild')); const m3 = m2.append($umf.compile('/grandchild?qGrandchild')); const params = { qParent: 'parent', qChild: 'child', qGrandchild: 'grandchild' }; const url = '/parent/child/grandchild?qParent=parent&qChild=child&qGrandchild=grandchild'; const formatted = m3.format(params); expect(formatted).toBe(url); expect(m3.exec(url.split('?')[0], params)).toEqual(params); }); }); describe('.append()', function () { it('should append matchers', function () { const matcher = $umf.compile('/users/:id/details/{type}?from').append($umf.compile('/{repeat:[0-9]+}?to')); const params = matcher.parameters(); expect(params.map(prop('id'))).toEqual(['id', 'type', 'from', 'repeat', 'to']); }); it('should return a new matcher', function () { const base = $umf.compile('/users/:id/details/{type}?from'); const matcher = base.append($umf.compile('/{repeat:[0-9]+}?to')); expect(matcher).not.toBe(base); }); it('should respect $urlMatcherFactoryProvider.strictMode', function () { let m = $umf.compile('/'); $umf.strictMode(false); m = m.append($umf.compile('foo')); expect(m.exec('/foo')).toEqual({}); expect(m.exec('/foo/')).toEqual({}); }); it('should respect $urlMatcherFactoryProvider.caseInsensitive', function () { let m = $umf.compile('/'); $umf.caseInsensitive(true); m = m.append($umf.compile('foo')); expect(m.exec('/foo')).toEqual({}); expect(m.exec('/FOO')).toEqual({}); }); it('should respect $urlMatcherFactoryProvider.caseInsensitive when validating regex params', function () { let m = $umf.compile('/'); $umf.caseInsensitive(true); m = m.append($umf.compile('foo/{param:bar}')); expect(m.validates({ param: 'BAR' })).toEqual(true); }); it('should generate/match params in the proper order', function () { let m = $umf.compile('/foo?queryparam'); m = m.append($umf.compile('/bar/:pathparam')); expect(m.exec('/foo/bar/pathval', { queryparam: 'queryval' })).toEqual({ pathparam: 'pathval', queryparam: 'queryval', }); }); }); describe('multivalue-query-parameters', function () { it('should handle .is() for an array of values', function () { const m = $umf.compile('/foo?{param1:int}'), param = m.parameter('param1'); expect(param.type.is([1, 2, 3])).toBe(true); expect(param.type.is([1, '2', 3])).toBe(false); }); it('should handle .equals() for two arrays of values', function () { const m = $umf.compile('/foo?{param1:int}&{param2:date}'), param1 = m.parameter('param1'), param2 = m.parameter('param2'); expect(param1.type.equals([1, 2, 3], [1, 2, 3])).toBe(true); expect(param1.type.equals([1, 2, 3], [1, 2])).toBe(false); expect( param2.type.equals( [new Date(2014, 11, 15), new Date(2014, 10, 15)], [new Date(2014, 11, 15), new Date(2014, 10, 15)] ) ).toBe(true); expect( param2.type.equals( [new Date(2014, 11, 15), new Date(2014, 9, 15)], [new Date(2014, 11, 15), new Date(2014, 10, 15)] ) ).toBe(false); }); it('should conditionally be wrapped in an array by default', function () { const m = $umf.compile('/foo?param1'); // empty array [] is treated like "undefined" expect(m.format({ param1: undefined })).toBe('/foo'); expect(m.format({ param1: [] })).toBe('/foo'); expect(m.format({ param1: '' })).toBe('/foo'); expect(m.format({ param1: '1' })).toBe('/foo?param1=1'); expect(m.format({ param1: ['1'] })).toBe('/foo?param1=1'); expect(m.format({ param1: ['1', '2'] })).toBe('/foo?param1=1&param1=2'); expect(m.exec('/foo')).toEqual({ param1: undefined }); expect(m.exec('/foo', {})).toEqual({ param1: undefined }); expect(m.exec('/foo', { param1: '' })).toEqual({ param1: undefined }); expect(m.exec('/foo', { param1: '1' })).toEqual({ param1: '1' }); // auto unwrap single values expect(m.exec('/foo', { param1: ['1', '2'] })).toEqual({ param1: ['1', '2'] }); $url.url('/foo'); expect(m.exec($url.path(), $url.search())).toEqual({ param1: undefined }); $url.url('/foo?param1=bar'); expect(m.exec($url.path(), $url.search())).toEqual({ param1: 'bar' }); // auto unwrap $url.url('/foo?param1='); expect(m.exec($url.path(), $url.search())).toEqual({ param1: undefined }); $url.url('/foo?param1=bar&param1=baz'); if (angular.isArray($url.search())) // conditional for angular 1.0.8 expect(m.exec($url.path(), $url.search())).toEqual({ param1: ['bar', 'baz'] }); expect(m.format({})).toBe('/foo'); expect(m.format({ param1: undefined })).toBe('/foo'); expect(m.format({ param1: '' })).toBe('/foo'); expect(m.format({ param1: 'bar' })).toBe('/foo?param1=bar'); expect(m.format({ param1: ['bar'] })).toBe('/foo?param1=bar'); expect(m.format({ param1: ['bar', 'baz'] })).toBe('/foo?param1=bar&param1=baz'); }); it('should be wrapped in an array if array: true', function () { const m = $umf.compile('/foo?param1', { state: { params: { param1: { array: true } } } }); // empty array [] is treated like "undefined" expect(m.format({ param1: undefined })).toBe('/foo'); expect(m.format({ param1: [] })).toBe('/foo'); expect(m.format({ param1: '' })).toBe('/foo'); expect(m.format({ param1: '1' })).toBe('/foo?param1=1'); expect(m.format({ param1: ['1'] })).toBe('/foo?param1=1'); expect(m.format({ param1: ['1', '2'] })).toBe('/foo?param1=1&param1=2'); expect(m.exec('/foo')).toEqual({ param1: undefined }); expect(m.exec('/foo', {})).toEqual({ param1: undefined }); expect(m.exec('/foo', { param1: '' })).toEqual({ param1: undefined }); expect(m.exec('/foo', { param1: '1' })).toEqual({ param1: ['1'] }); expect(m.exec('/foo', { param1: ['1', '2'] })).toEqual({ param1: ['1', '2'] }); $url.url('/foo'); expect(m.exec($url.path(), $url.search())).toEqual({ param1: undefined }); $url.url('/foo?param1='); expect(m.exec($url.path(), $url.search())).toEqual({ param1: undefined }); $url.url('/foo?param1=bar'); expect(m.exec($url.path(), $url.search())).toEqual({ param1: ['bar'] }); $url.url('/foo?param1=bar&param1=baz'); if (angular.isArray($url.search())) // conditional for angular 1.0.8 expect(m.exec($url.path(), $url.search())).toEqual({ param1: ['bar', 'baz'] }); expect(m.format({})).toBe('/foo'); expect(m.format({ param1: undefined })).toBe('/foo'); expect(m.format({ param1: '' })).toBe('/foo'); expect(m.format({ param1: 'bar' })).toBe('/foo?param1=bar'); expect(m.format({ param1: ['bar'] })).toBe('/foo?param1=bar'); expect(m.format({ param1: ['bar', 'baz'] })).toBe('/foo?param1=bar&param1=baz'); }); it('should be wrapped in an array if paramname looks like param[]', function () { const m = $umf.compile('/foo?param1[]'); expect(m.exec('/foo')).toEqual({}); $url.url('/foo?param1[]=bar'); expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': ['bar'] }); expect(m.format({ 'param1[]': 'bar' })).toBe('/foo?param1[]=bar'); expect(m.format({ 'param1[]': ['bar'] })).toBe('/foo?param1[]=bar'); $url.url('/foo?param1[]=bar&param1[]=baz'); if (angular.isArray($url.search())) // conditional for angular 1.0.8 expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': ['bar', 'baz'] }); expect(m.format({ 'param1[]': ['bar', 'baz'] })).toBe('/foo?param1[]=bar&param1[]=baz'); }); // Test for issue #2222 it('should return default value, if query param is missing.', function () { const m = $umf.compile('/state?param1&param2&param3&param5', { state: { params: { param1: 'value1', param2: { array: true, value: ['value2'] }, param3: { array: true, value: [] }, param5: { array: true, value: function () { return []; }, }, }, }, }); const expected = { param1: 'value1', param2: ['value2'], param3: [], param5: [], }; // Parse url to get Param.value() const parsed = m.exec('/state'); expect(parsed).toEqual(expected); // Pass again through Param.value() for normalization (like transitionTo) const paramDefs = m.parameters(); const values = map(parsed, function (val, key) { return find(paramDefs, function (def) { return def.id === key; }).value(val); }); expect(values).toEqual(expected); }); it('should not be wrapped by ui-router into an array if array: false', function () { const m = $umf.compile('/foo?param1', { state: { params: { param1: { array: false } } } }); expect(m.exec('/foo')).toEqual({}); $url.url('/foo?param1=bar'); expect(m.exec($url.path(), $url.search())).toEqual({ param1: 'bar' }); expect(m.format({ param1: 'bar' })).toBe('/foo?param1=bar'); expect(m.format({ param1: ['bar'] })).toBe('/foo?param1=bar'); $url.url('/foo?param1=bar&param1=baz'); if (angular.isArray($url.search())) // conditional for angular 1.0.8 expect(m.exec($url.path(), $url.search())).toEqual({ param1: 'bar,baz' }); // coerced to string expect(m.format({ param1: ['bar', 'baz'] })).toBe('/foo?param1=bar%2Cbaz'); // coerced to string }); }); describe('multivalue-path-parameters', function () { it('should behave as a single-value by default', function () { const m = $umf.compile('/foo/:param1'); expect(m.exec('/foo/')).toEqual({ param1: '' }); expect(m.exec('/foo/bar')).toEqual({ param1: 'bar' }); expect(m.format({ param1: 'bar' })).toBe('/foo/bar'); expect(m.format({ param1: ['bar', 'baz'] })).toBe('/foo/bar%2Cbaz'); // coerced to string }); it('should be split on - in url and wrapped in an array if array: true', inject(function ($location) { const m = $umf.compile('/foo/:param1', { state: { params: { param1: { array: true } } } }); expect(m.exec('/foo/')).toEqual({ param1: undefined }); expect(m.exec('/foo/bar')).toEqual({ param1: ['bar'] }); $url.url('/foo/bar-baz'); expect(m.exec($location.url())).toEqual({ param1: ['bar', 'baz'] }); expect(m.format({ param1: [] })).toEqual('/foo/'); expect(m.format({ param1: ['bar'] })).toEqual('/foo/bar'); expect(m.format({ param1: ['bar', 'baz'] })).toEqual('/foo/bar-baz'); })); it('should behave similar to multi-value query params', function () { const m = $umf.compile('/foo/:param1[]'); // empty array [] is treated like "undefined" expect(m.format({ 'param1[]': undefined })).toBe('/foo/'); expect(m.format({ 'param1[]': [] })).toBe('/foo/'); expect(m.format({ 'param1[]': '' })).toBe('/foo/'); expect(m.format({ 'param1[]': '1' })).toBe('/foo/1'); expect(m.format({ 'param1[]': ['1'] })).toBe('/foo/1'); expect(m.format({ 'param1[]': ['1', '2'] })).toBe('/foo/1-2'); expect(m.exec('/foo/')).toEqual({ 'param1[]': undefined }); expect(m.exec('/foo/1')).toEqual({ 'param1[]': ['1'] }); expect(m.exec('/foo/1-2')).toEqual({ 'param1[]': ['1', '2'] }); $url.url('/foo/'); expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': undefined }); $url.url('/foo/bar'); expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': ['bar'] }); $url.url('/foo/bar-baz'); expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': ['bar', 'baz'] }); expect(m.format({})).toBe('/foo/'); expect(m.format({ 'param1[]': undefined })).toBe('/foo/'); expect(m.format({ 'param1[]': '' })).toBe('/foo/'); expect(m.format({ 'param1[]': 'bar' })).toBe('/foo/bar'); expect(m.format({ 'param1[]': ['bar'] })).toBe('/foo/bar'); expect(m.format({ 'param1[]': ['bar', 'baz'] })).toBe('/foo/bar-baz'); }); it('should be split on - in url and wrapped in an array if paramname looks like param[]', function () { const m = $umf.compile('/foo/:param1[]'); expect(m.exec('/foo/')).toEqual({ 'param1[]': undefined }); expect(m.exec('/foo/bar')).toEqual({ 'param1[]': ['bar'] }); expect(m.exec('/foo/bar-baz')).toEqual({ 'param1[]': ['bar', 'baz'] }); expect(m.format({ 'param1[]': [] })).toEqual('/foo/'); expect(m.format({ 'param1[]': ['bar'] })).toEqual('/foo/bar'); expect(m.format({ 'param1[]': ['bar', 'baz'] })).toEqual('/foo/bar-baz'); }); it("should allow path param arrays with '-' in the values", function () { const m = $umf.compile('/foo/:param1[]'); expect(m.exec('/foo/')).toEqual({ 'param1[]': undefined }); expect(m.exec('/foo/bar\\-')).toEqual({ 'param1[]': ['bar-'] }); expect(m.exec('/foo/bar\\--\\-baz')).toEqual({ 'param1[]': ['bar-', '-baz'] }); expect(m.format({ 'param1[]': [] })).toEqual('/foo/'); expect(m.format({ 'param1[]': ['bar-'] })).toEqual('/foo/bar%5C%2D'); expect(m.format({ 'param1[]': ['bar-', '-baz'] })).toEqual('/foo/bar%5C%2D-%5C%2Dbaz'); expect(m.format({ 'param1[]': ['bar-bar-bar-', '-baz-baz-baz'] })).toEqual( '/foo/bar%5C%2Dbar%5C%2Dbar%5C%2D-%5C%2Dbaz%5C%2Dbaz%5C%2Dbaz' ); // check that we handle $location.url decodes correctly $url.url(m.format({ 'param1[]': ['bar-', '-baz'] })); expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': ['bar-', '-baz'] }); // check that we handle $location.url decodes correctly for multiple hyphens $url.url(m.format({ 'param1[]': ['bar-bar-bar-', '-baz-baz-baz'] })); expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': ['bar-bar-bar-', '-baz-baz-baz'] }); // check that pre-encoded values are passed correctly $url.url(m.format({ 'param1[]': ['%2C%20%5C%2C', '-baz'] })); expect(m.exec($url.path(), $url.search())).toEqual({ 'param1[]': ['%2C%20%5C%2C', '-baz'] }); }); }); }); describe('urlMatcherFactoryProvider', function () { describe('.type()', function () { let $umf; beforeEach( module('ui.router.util', function ($urlMatcherFactoryProvider) { $umf = $urlMatcherFactoryProvider; $urlMatcherFactoryProvider.type('myType', {}, function () { return { decode: function () { return { status: 'decoded' }; }, is: angular.isObject, }; }); }) ); it('should handle arrays properly with config-time custom type definitions', inject(function ($stateParams) { const m = $umf.compile('/test?{foo:myType}'); expect(m.exec('/test', { foo: '1' })).toEqual({ foo: { status: 'decoded' } }); expect(m.exec('/test', { foo: ['1', '2'] })).toEqual({ foo: [{ status: 'decoded' }, { status: 'decoded' }] }); })); }); // TODO: Fix object pollution between tests for urlMatcherConfig afterEach(inject(function ($urlMatcherFactory) { $urlMatcherFactory.caseInsensitive(false); })); }); describe('urlMatcherFactory', function () { let $umf: UrlMatcherFactory; let $url: UrlService; beforeEach(inject(function ($urlMatcherFactory, $urlService) { $umf = $urlMatcherFactory; $url = $urlService; })); it('compiles patterns', function () { const matcher = $umf.compile('/hello/world'); expect(matcher instanceof UrlMatcher).toBe(true); }); it('recognizes matchers', function () { expect($umf.isMatcher($umf.compile('/'))).toBe(true); const custom = { format: angular.noop, exec: angular.noop, append: angular.noop, isRoot: angular.noop, validates: angular.noop, parameters: angular.noop, parameter: angular.noop, _getDecodedParamValue: angular.noop, }; expect($umf.isMatcher(custom)).toBe(true); }); it('should handle case sensitive URL by default', function () { expect($umf.compile('/hello/world').exec('/heLLo/WORLD')).toBeNull(); }); it('should handle case insensitive URL', function () { $umf.caseInsensitive(true); expect($umf.compile('/hello/world').exec('/heLLo/WORLD')).toEqual({}); }); describe('typed parameters', function () { it('should accept object definitions', function () { const type = { encode: function () {}, decode: function () {} } as any; $umf.type('myType1', type); expect($umf.type('myType1').encode).toBe(type.encode); }); it('should reject duplicate definitions', function () { $umf.type('myType2', { encode: function () {}, decode: function () {} } as any); expect(function () { $umf.type('myType2', {} as any); }).toThrowError("A type named 'myType2' has already been defined."); }); it('should accept injected function definitions', inject(function ($stateParams) { $umf.type( 'myType3', {} as any, function ($stateParams) { return { decode: function () { return $stateParams; }, }; } as any ); expect($umf.type('myType3').decode()).toBe($stateParams); })); it('should accept annotated function definitions', inject(function ($stateParams) { $umf.type( 'myAnnotatedType', {} as any, [ '$stateParams', function (s) { return { decode: function () { return s; }, }; }, ] as any ); expect($umf.type('myAnnotatedType').decode()).toBe($stateParams); })); it('should match built-in types', function () { const m = $umf.compile('/{foo:int}/{flag:bool}'); expect(m.exec('/1138/1')).toEqual({ foo: 1138, flag: true }); expect(m.format({ foo: 5, flag: true })).toBe('/5/1'); expect(m.exec('/-1138/1')).toEqual({ foo: -1138, flag: true }); expect(m.format({ foo: -5, flag: true })).toBe('/-5/1'); }); it('should match built-in types with spaces', function () { const m = $umf.compile('/{foo: int}/{flag: bool}'); expect(m.exec('/1138/1')).toEqual({ foo: 1138, flag: true }); expect(m.format({ foo: 5, flag: true })).toBe('/5/1'); }); it('should match types named only in params', function () { const m = $umf.compile('/{foo}/{flag}', { state: { params: { foo: { type: 'int' }, flag: { type: 'bool' }, }, }, }); expect(m.exec('/1138/1')).toEqual({ foo: 1138, flag: true }); expect(m.format({ foo: 5, flag: true })).toBe('/5/1'); }); it('should throw an error if a param type is declared twice', function () { expect(function () { $umf.compile('/{foo:int}', { state: { params: { foo: { type: 'int' }, }, }, }); }).toThrow(new Error("Param 'foo' has two type configurations.")); }); it('should encode/decode dates', function () { const m = $umf.compile('/calendar/{date:date}'), result = m.exec('/calendar/2014-03-26'); const date = new Date(2014, 2, 26); expect(result.date instanceof Date).toBe(true); expect(result.date.toUTCString()).toEqual(date.toUTCString()); expect(m.format({ date: date })).toBe('/calendar/2014-03-26'); }); it('should encode/decode arbitrary objects to json', function () { const m = $umf.compile('/state/{param1:json}/{param2:json}'); const params = { param1: { foo: 'huh', count: 3 }, param2: { foo: 'wha', count: 5 }, }; const json1 = '{"foo":"huh","count":3}'; const json2 = '{"foo":"wha","count":5}'; expect(m.format(params)).toBe('/state/' + encodeURIComponent(json1) + '/' + encodeURIComponent(json2)); expect(m.exec('/state/' + json1 + '/' + json2)).toEqual(params); }); it('should not match invalid typed parameter values', function () { const m = $umf.compile('/users/{id:int}'); expect(m.exec('/users/1138').id).toBe(1138); expect(m.exec('/users/alpha')).toBeNull(); expect(m.format({ id: 1138 })).toBe('/users/1138'); expect(m.format({ id: 'alpha' })).toBeNull(); }); it('should automatically handle multiple search param values', function () { const m = $umf.compile('/foo/{fooid:int}?{bar:int}'); $url.url('/foo/5?bar=1'); expect(m.exec($url.path(), $url.search())).toEqual({ fooid: 5, bar: 1 }); expect(m.format({ fooid: 5, bar: 1 })).toEqual('/foo/5?bar=1'); $url.url('/foo/5?bar=1&bar=2&bar=3'); if (angular.isArray($url.search())) // conditional for angular 1.0.8 expect(m.exec($url.path(), $url.search())).toEqual({ fooid: 5, bar: [1, 2, 3] }); expect(m.format({ fooid: 5, bar: [1, 2, 3] })).toEqual('/foo/5?bar=1&bar=2&bar=3'); m.format(); }); it('should allow custom types to handle multiple search param values manually', function () { $umf.type('custArray', { encode: function (array) { return array.join('-'); }, decode: function (val) { return angular.isArray(val) ? val : val.split(/-/); }, equals: angular.equals, is: angular.isArray, }); const m = $umf.compile('/foo?{bar:custArray}', { state: { params: { bar: { array: false } } } }); $url.url('/foo?bar=fox'); expect(m.exec($url.path(), $url.search())).toEqual({ bar: ['fox'] }); expect(m.format({ bar: ['fox'] })).toEqual('/foo?bar=fox'); $url.url('/foo?bar=quick-brown-fox'); expect(m.exec($url.path(), $url.search())).toEqual({ bar: ['quick', 'brown', 'fox'] }); expect(m.format({ bar: ['quick', 'brown', 'fox'] })).toEqual('/foo?bar=quick-brown-fox'); }); }); describe('optional parameters', function () { it('should match with or without values', function () { const m = $umf.compile('/users/{id:int}', { state: { params: { id: { value: null, squash: true } }, }, }); expect(m.exec('/users/1138')).toEqual({ id: 1138 }); expect(m.exec('/users1138')).toBeNull(); expect(m.exec('/users/').id).toBeNull(); expect(m.exec('/users').id).toBeNull(); }); it('should correctly match multiple', function () { const m = $umf.compile('/users/{id:int}/{state:[A-Z]+}', { state: { params: { id: { value: null, squash: true }, state: { value: null, squash: true } }, }, }); expect(m.exec('/users/1138')).toEqual({ id: 1138, state: null }); expect(m.exec('/users/1138/NY')).toEqual({ id: 1138, state: 'NY' }); expect(m.exec('/users/').id).toBeNull(); expect(m.exec('/users/').state).toBeNull(); expect(m.exec('/users').id).toBeNull(); expect(m.exec('/users').state).toBeNull(); expect(m.exec('/users/NY').state).toBe('NY'); expect(m.exec('/users/NY').id).toBeNull(); }); it('should correctly format with or without values', function () { const m = $umf.compile('/users/{id:int}', { state: { params: { id: { value: null } }, }, }); expect(m.format()).toBe('/users/'); expect(m.format({ id: 1138 })).toBe('/users/1138'); }); it('should correctly format multiple', function () { const m = $umf.compile('/users/{id:int}/{state:[A-Z]+}', { state: { params: { id: { value: null, squash: true }, state: { value: null, squash: true } }, }, }); expect(m.format()).toBe('/users'); expect(m.format({ id: 1138 })).toBe('/users/1138'); expect(m.format({ state: 'NY' })).toBe('/users/NY'); expect(m.format({ id: 1138, state: 'NY' })).toBe('/users/1138/NY'); }); it('should match in between static segments', function () { const m = $umf.compile('/users/{user:int}/photos', { state: { params: { user: { value: 5, squash: true } }, }, }); expect(m.exec('/users/photos').user).toBe(5); expect(m.exec('/users/6/photos').user).toBe(6); expect(m.format()).toBe('/users/photos'); expect(m.format({ user: 1138 })).toBe('/users/1138/photos'); }); it('should correctly format with an optional followed by a required parameter', function () { const m = $umf.compile('/home/:user/gallery/photos/:photo', { state: { params: { user: { value: null, squash: true }, photo: undefined, }, }, }); expect(m.format({ photo: 12 })).toBe('/home/gallery/photos/12'); expect(m.format({ user: 1138, photo: 13 })).toBe('/home/1138/gallery/photos/13'); }); describe('default values', function () { it('should populate if not supplied in URL', function () { const m = $umf.compile('/users/{id:int}/{test}', { state: { params: { id: { value: 0, squash: true }, test: { value: 'foo', squash: true } }, }, }); expect(m.exec('/users')).toEqual({ id: 0, test: 'foo' }); expect(m.exec('/users/2')).toEqual({ id: 2, test: 'foo' }); expect(m.exec('/users/bar')).toEqual({ id: 0, test: 'bar' }); expect(m.exec('/users/2/bar')).toEqual({ id: 2, test: 'bar' }); expect(m.exec('/users/bar/2')).toBeNull(); }); it('should populate even if the regexp requires 1 or more chars', function () { const m = $umf.compile('/record/{appId}/{recordId:[0-9a-fA-F]{10,24}}', { state: { params: { appId: null, recordId: null }, }, }); expect(m.exec('/record/546a3e4dd273c60780e35df3/')).toEqual({ appId: '546a3e4dd273c60780e35df3', recordId: null, }); }); it('should allow shorthand definitions', function () { const m = $umf.compile('/foo/:foo', { state: { params: { foo: 'bar' }, }, }); expect(m.exec('/foo/')).toEqual({ foo: 'bar' }); }); it('should populate query params', function () { const defaults = { order: 'name', limit: 25, page: 1 }; const m = $umf.compile('/foo?order&{limit:int}&{page:int}', { state: { params: defaults, }, }); expect(m.exec('/foo')).toEqual(defaults); }); it('should allow function-calculated values', function () { function barFn() { return 'Value from bar()'; } let m = $umf.compile('/foo/:bar', { state: { params: { bar: barFn }, }, }); expect(m.exec('/foo/').bar).toBe('Value from bar()'); m = $umf.compile('/foo/:bar', { state: { params: { bar: { value: barFn, squash: true } }, }, }); expect(m.exec('/foo').bar).toBe('Value from bar()'); m = $umf.compile('/foo?bar', { state: { params: { bar: barFn }, }, }); expect(m.exec('/foo').bar).toBe('Value from bar()'); }); it('should allow injectable functions', inject(function ($stateParams) { const m = $umf.compile('/users/{user:json}', { state: { params: { user: function ($stateParams) { return $stateParams.user; }, }, }, }); const user = { name: 'Bob' }; $stateParams.user = user; expect(m.exec('/users/').user).toBe(user); })); xit('should match when used as prefix', function () { const m = $umf.compile('/{lang:[a-z]{2}}/foo', { state: { params: { lang: 'de' }, }, }); expect(m.exec('/de/foo')).toEqual({ lang: 'de' }); expect(m.exec('/foo')).toEqual({ lang: 'de' }); }); describe('squash policy', function () { const Session = { username: 'loggedinuser' }; function getMatcher(squash) { return $umf.compile('/user/:userid/gallery/:galleryid/photo/:photoid', { state: { params: { userid: { squash: squash, value: function () { return Session.username; }, }, galleryid: { squash: squash, value: 'favorites' }, }, }, }); } it(': true should squash the default value and one slash', inject(function ($stateParams) { const m = getMatcher(true); const defaultParams = { userid: 'loggedinuser', galleryid: 'favorites', photoid: '123' }; expect(m.exec('/user/gallery/photo/123')).toEqual(defaultParams); expect(m.exec('/user//gallery//photo/123')).toEqual(defaultParams); expect(m.format(defaultParams)).toBe('/user/gallery/photo/123'); const nonDefaultParams = { userid: 'otheruser', galleryid: 'travel', photoid: '987' }; expect(m.exec('/user/otheruser/gallery/travel/photo/987')).toEqual(nonDefaultParams); expect(m.format(nonDefaultParams)).toBe('/user/otheruser/gallery/travel/photo/987'); })); it(': false should not squash default values', inject(function ($stateParams) { const m = getMatcher(false); const defaultParams = { userid: 'loggedinuser', galleryid: 'favorites', photoid: '123' }; expect(m.exec('/user/loggedinuser/gallery/favorites/photo/123')).toEqual(defaultParams); expect(m.format(defaultParams)).toBe('/user/loggedinuser/gallery/favorites/photo/123'); const nonDefaultParams = { userid: 'otheruser', galleryid: 'travel', photoid: '987' }; expect(m.exec('/user/otheruser/gallery/travel/photo/987')).toEqual(nonDefaultParams); expect(m.format(nonDefaultParams)).toBe('/user/otheruser/gallery/travel/photo/987'); })); it(": '' should squash the default value to an empty string", inject(function ($stateParams) { const m = getMatcher(''); const defaultParams = { userid: 'loggedinuser', galleryid: 'favorites', photoid: '123' }; expect(m.exec('/user//gallery//photo/123')).toEqual(defaultParams); expect(m.format(defaultParams)).toBe('/user//gallery//photo/123'); const nonDefaultParams = { userid: 'otheruser', galleryid: 'travel', photoid: '987' }; expect(m.exec('/user/otheruser/gallery/travel/photo/987')).toEqual(nonDefaultParams); expect(m.format(nonDefaultParams)).toBe('/user/otheruser/gallery/travel/photo/987'); })); it(": '~' should squash the default value and replace it with '~'", inject(function ($stateParams) { const m = getMatcher('~'); const defaultParams = { userid: 'loggedinuser', galleryid: 'favorites', photoid: '123' }; expect(m.exec('/user//gallery//photo/123')).toEqual(defaultParams); expect(m.exec('/user/~/gallery/~/photo/123')).toEqual(defaultParams); expect(m.format(defaultParams)).toBe('/user/~/gallery/~/photo/123'); const nonDefaultParams = { userid: 'otheruser', galleryid: 'travel', photoid: '987' }; expect(m.exec('/user/otheruser/gallery/travel/photo/987')).toEqual(nonDefaultParams); expect(m.format(nonDefaultParams)).toBe('/user/otheruser/gallery/travel/photo/987'); })); }); }); }); describe('strict matching', function () { it('should match with or without trailing slash', function () { const m = $umf.compile('/users', { strict: false }); expect(m.exec('/users')).toEqual({}); expect(m.exec('/users/')).toEqual({}); }); it('should not match multiple trailing slashes', function () { const m = $umf.compile('/users', { strict: false }); expect(m.exec('/users//')).toBeNull(); }); it('should match when defined with parameters', function () { const m = $umf.compile('/users/{name}', { strict: false, state: { params: { name: { value: null }, }, }, }); expect(m.exec('/users/')).toEqual({ name: null }); expect(m.exec('/users/bob')).toEqual({ name: 'bob' }); expect(m.exec('/users/bob/')).toEqual({ name: 'bob' }); expect(m.exec('/users/bob//')).toBeNull(); }); }); });
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import Outputs from '../../../../../resources/outputs'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { TriggerSet } from '../../../../../types/trigger'; // TODO: Lightwave has different ids, do these mean anything? export interface Data extends RaidbossData { crystallize?: 'spread' | 'stack'; isEquinox?: boolean; } const storedMechanicsOutputStrings = { spread: Outputs.spread, stack: { en: 'Party Stack', de: 'Mit der Party sammeln', fr: 'Package en groupe', ja: '全員集合', cn: '8人分摊', ko: '파티 전체 쉐어', }, }; const crystallizeOutputStrings = { ...storedMechanicsOutputStrings, crystallize: { en: 'Crystallize: ${name}', de: 'Kristalisieren: ${name}', fr: 'Cristallisation : ${name}', ja: 'クリスタライズ: ${name}', }, }; const comboOutputStrings = { ...storedMechanicsOutputStrings, combo: { en: '${first} => ${second}', de: '${first} => ${second}', fr: '${first} => ${second}', ja: '${first} => ${second}', cn: '${first} => ${second}', ko: '${first} => ${second}', }, }; // Hydaelyn Normal Mode const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.TheMothercrystal, timelineFile: 'hydaelyn.txt', triggers: [ { id: 'Hydaelyn Heros\'s Radiance', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '65D7', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '65D7', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '65D7', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '65D7', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '65D7', source: '海德林', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '65D7', source: '하이델린', capture: false }), response: Responses.aoe(), }, { id: 'Hydaelyn Magos\'s Raidance', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '65D8', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '65D8', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '65D8', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '65D8', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '65D8', source: '海德林', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '65D8', source: '하이델린', capture: false }), response: Responses.aoe(), }, { id: 'Hydaelyn Crystallize Ice', type: 'Ability', netRegex: NetRegexes.ability({ id: '659C', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.ability({ id: '659C', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.ability({ id: '659C', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.ability({ id: '659C', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.ability({ id: '659C', source: '海德林', capture: false }), netRegexKo: NetRegexes.ability({ id: '659C', source: '하이델린', capture: false }), infoText: (_data, _matches, output) => output.crystallize!({ name: output.spread!() }), run: (data) => data.crystallize = 'spread', outputStrings: crystallizeOutputStrings, }, { id: 'Hydaelyn Crystallize Stone', type: 'Ability', netRegex: NetRegexes.ability({ id: '659E', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.ability({ id: '659E', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.ability({ id: '659E', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.ability({ id: '659E', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.ability({ id: '659E', source: '海德林', capture: false }), netRegexKo: NetRegexes.ability({ id: '659E', source: '하이델린', capture: false }), infoText: (_data, _matches, output) => output.crystallize!({ name: output.stack!() }), run: (data) => data.crystallize = 'stack', outputStrings: crystallizeOutputStrings, }, { id: 'Hydaelyn Dawn Mantle Equinox', type: 'StartsUsing', // Equinox is more complicated in normal mode than extreme. // There is no 8E1 effect for Equinox (a parser bug?), and there are some places where // it is used randomly and not in fixed places, and so it can't just be a timeline trigger. // However, in normal mode, Dawn Mantle is always cast prior to the marker appearing, // so assume any Dawn Mantle is Equinox unless we figure out otherwise. netRegex: NetRegexes.startsUsing({ id: '6C0C', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '6C0C', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '6C0C', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '6C0C', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '6C0C', source: '海德林', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '6C0C', source: '하이델린', capture: false }), preRun: (data) => data.isEquinox = true, // Dawn Mantle is a 4.9s cast, plus the normal 2.5s delay. (See Anthelion comment below.) delaySeconds: 2.5 + 4.9, durationSeconds: (data) => data.crystallize ? 5.5 : 2.5, alertText: (data, _matches, output) => { // If we've gotten some 8E1 effect, ignore this. if (!data.isEquinox) return; if (data.crystallize) return output.combo!({ first: output.intercards!(), second: output[data.crystallize]!() }); return output.intercards!(); }, run: (data) => { // Don't clear the crystallize if it's going to be used for Anthelion or Highest Holy. if (data.isEquinox) delete data.crystallize; }, outputStrings: { ...comboOutputStrings, intercards: { en: 'Intercards', de: 'Interkardinal', fr: 'Intercardinal', ja: '斜めへ', cn: '四角', ko: '대각선 쪽으로', }, }, }, { id: 'Hydaelyn Marker Anthelion', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '8E1', source: 'Hydaelyn', count: '1B5', capture: false }), netRegexDe: NetRegexes.gainsEffect({ effectId: '8E1', source: 'Hydaelyn', count: '1B5', capture: false }), netRegexFr: NetRegexes.gainsEffect({ effectId: '8E1', source: 'Hydaelyn', count: '1B5', capture: false }), netRegexJa: NetRegexes.gainsEffect({ effectId: '8E1', source: 'ハイデリン', count: '1B5', capture: false }), netRegexCn: NetRegexes.gainsEffect({ effectId: '8E1', source: '海德林', count: '1B5', capture: false }), netRegexKo: NetRegexes.gainsEffect({ effectId: '8E1', source: '하이델린', count: '1B5', capture: false }), // Example timeline: // t=0 StartsCasting Crystallize // t=4 ActionEffect Crystalize // t=7 StatusAdd 81E (this regex) // t=9.5 marker appears (this seems faster than extreme?) // t=13 ActionEffect Anthelion // t=17 ActionEffect Crystalline Blizzard // // We could call this out immediately, but then it's very close to the Crystallize call. // Additionally, if we call this out immediately then players have to remember something // for 10 seconds. A delay of 3 feels more natural in terms of time to react and // handle this, rather than calling it out extremely early. Also, add a duration so that // this stays on screen until closer to the Crystalline action. This also puts this call // closer to when the marker appears on screen, and so feels a little bit more natural. preRun: (data) => data.isEquinox = false, delaySeconds: 2.5, durationSeconds: (data) => data.crystallize ? 5.5 : 2.5, alertText: (data, _matches, output) => { if (data.crystallize) return output.combo!({ first: output.in!(), second: output[data.crystallize]!() }); return output.in!(); }, run: (data) => delete data.crystallize, outputStrings: { ...comboOutputStrings, in: Outputs.in, }, }, { id: 'Hydaelyn Marker Highest Holy', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ effectId: '8E1', source: 'Hydaelyn', count: '1B4', capture: false }), netRegexDe: NetRegexes.gainsEffect({ effectId: '8E1', source: 'Hydaelyn', count: '1B4', capture: false }), netRegexFr: NetRegexes.gainsEffect({ effectId: '8E1', source: 'Hydaelyn', count: '1B4', capture: false }), netRegexJa: NetRegexes.gainsEffect({ effectId: '8E1', source: 'ハイデリン', count: '1B4', capture: false }), netRegexCn: NetRegexes.gainsEffect({ effectId: '8E1', source: '海德林', count: '1B4', capture: false }), netRegexKo: NetRegexes.gainsEffect({ effectId: '8E1', source: '하이델린', count: '1B4', capture: false }), preRun: (data) => data.isEquinox = false, delaySeconds: 2.5, durationSeconds: (data) => data.crystallize ? 5.5 : 2.5, alertText: (data, _matches, output) => { if (data.crystallize) return output.combo!({ first: output.out!(), second: output[data.crystallize]!() }); return output.out!(); }, run: (data) => delete data.crystallize, outputStrings: { ...comboOutputStrings, out: Outputs.out, }, }, { id: 'Hydaelyn Mousa\'s Scorn', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '65D6', source: 'Hydaelyn' }), netRegexDe: NetRegexes.startsUsing({ id: '65D6', source: 'Hydaelyn' }), netRegexFr: NetRegexes.startsUsing({ id: '65D6', source: 'Hydaelyn' }), netRegexJa: NetRegexes.startsUsing({ id: '65D6', source: 'ハイデリン' }), netRegexCn: NetRegexes.startsUsing({ id: '65D6', source: '海德林' }), netRegexKo: NetRegexes.startsUsing({ id: '65D6', source: '하이델린' }), response: Responses.sharedTankBuster(), }, { id: 'Hydaelyn Exodus', type: 'Ability', netRegex: NetRegexes.ability({ id: '65BB', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.ability({ id: '65BB', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.ability({ id: '65BB', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.ability({ id: '65BB', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.ability({ id: '65BB', source: '海德林', capture: false }), netRegexKo: NetRegexes.ability({ id: '65BB', source: '하이델린', capture: false }), // 14.8 seconds from this ability (no cast) to 662B raidwide. delaySeconds: 5, response: Responses.aoe(), }, { id: 'Hydaelyn Radiant Halo', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '65D0', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '65D0', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '65D0', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '65D0', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '65D0', source: '海德林', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '65D0', source: '하이델린', capture: false }), response: Responses.aoe(), }, { id: 'Hydaelyn Heros\'s Sundering', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '65D5', source: 'Hydaelyn' }), netRegexDe: NetRegexes.startsUsing({ id: '65D5', source: 'Hydaelyn' }), netRegexFr: NetRegexes.startsUsing({ id: '65D5', source: 'Hydaelyn' }), netRegexJa: NetRegexes.startsUsing({ id: '65D5', source: 'ハイデリン' }), netRegexCn: NetRegexes.startsUsing({ id: '65D5', source: '海德林' }), netRegexKo: NetRegexes.startsUsing({ id: '65D5', source: '하이델린' }), response: Responses.tankCleave('alert'), }, { id: 'Hydaelyn Echo Crystaline Stone III', type: 'StartsUsing', // Midphase stack. netRegex: NetRegexes.startsUsing({ id: '6C59', source: 'Echo of Hydaelyn', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '6C59', source: 'Echo Der Hydaelyn', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '6C59', source: 'Écho D\'Hydaelyn', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '6C59', source: 'ハイデリン・エコー', capture: false }), alertText: (_data, _matches, output) => output.stack!(), outputStrings: { stack: crystallizeOutputStrings.stack, }, }, { id: 'Hydaelyn Echo Crystaline Blizzard III', type: 'StartsUsing', // Midphase spread. netRegex: NetRegexes.startsUsing({ id: '6C5A', source: 'Echo of Hydaelyn' }), netRegexDe: NetRegexes.startsUsing({ id: '6C5A', source: 'Echo Der Hydaelyn' }), netRegexFr: NetRegexes.startsUsing({ id: '6C5A', source: 'Écho D\'Hydaelyn' }), netRegexJa: NetRegexes.startsUsing({ id: '6C5A', source: 'ハイデリン・エコー' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.spread!(), outputStrings: { spread: crystallizeOutputStrings.spread, }, }, { id: 'Hydaelyn Parhelic Circle', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '65AC', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '65AC', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '65AC', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '65AC', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '65AC', source: '海德林', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '65AC', source: '하이델린', capture: false }), durationSeconds: 9, alertText: (_data, _matches, output) => output.avoid!(), run: (data) => delete data.crystallize, outputStrings: { avoid: { en: 'Avoid Line Ends', de: 'Weiche den Enden der Linien aus', fr: 'Évitez les fins de lignes', ja: '線の端から離れる', cn: '远离线', ko: '선의 끝부분 피하기', }, }, }, { id: 'Hydaelyn Echoes', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ id: '65B[567]', source: 'Hydaelyn', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '65B[567]', source: 'Hydaelyn', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '65B[567]', source: 'Hydaelyn', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '65B[567]', source: 'ハイデリン', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '65B[567]', source: '海德林', capture: false }), netRegexKo: NetRegexes.startsUsing({ id: '65B[567]', source: '하이델린', capture: false }), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Stack 5x', de: '5x Sammeln', fr: '5x Packages', ja: '頭割り5回', cn: '5连分摊', ko: '쉐어 5번', }, }, }, ], timelineReplace: [ { 'locale': 'en', 'replaceText': { 'Crystalline Blizzard III/Crystalline Stone III': 'Crystalline Blizzard/Stone III', }, }, { 'locale': 'de', 'replaceSync': { 'Echo of Hydaelyn': 'Echo der Hydaelyn', '(?<!of )Hydaelyn': 'Hydaelyn', 'Mystic Refulgence': 'Truglicht', }, 'replaceText': { 'Anthelion': 'Anthelion', 'Beacon': 'Lichtschein', 'Crystalline Blizzard III': 'Kristall-Eisga', 'Crystalline Stone III': 'Kristall-Steinga', 'Crystallize': 'Kristallisieren', 'Dawn Mantle': 'Neuer Mantel', 'Echoes': 'Echos', 'Equinox': 'Äquinoktium', 'Exodus': 'Exodus', 'Heros\'s Radiance': 'Glanz des Heros', 'Heros\'s Sundering': 'Schlag des Heros', 'Highest Holy': 'Höchstes Sanctus', 'Hydaelyn\'s Ray': 'Strahl der Hydaelyn', 'Incandescence': 'Inkandeszenz', 'Lightwave': 'Lichtwoge', 'Magos\'s Radiance': 'Glanz des Magos', 'Mousa\'s Scorn': 'Zorn der Mousa', 'Parhelic Circle': 'Horizontalkreis', '(?<!Sub)Parhelion': 'Parhelion', 'Radiant Halo': 'Strahlender Halo', 'Subparhelion': 'Subparhelion', }, }, { 'locale': 'fr', 'replaceSync': { 'Echo of Hydaelyn': 'écho d\'Hydaelyn', '(?<!of )Hydaelyn': 'Hydaelyn', 'Mystic Refulgence': 'illusion de Lumière', }, 'replaceText': { '\\?': ' ?', 'Anthelion': 'Anthélie', 'Beacon': 'Rayon de Lumière', 'Crystalline Blizzard III': 'Méga Glace cristallisée', 'Crystalline Stone III': 'Méga Terre cristallisée', 'Crystallize': 'Cristallisation', 'Dawn Mantle': 'Changement de cape', 'Echoes': 'Échos', 'Equinox': 'Équinoxe', 'Exodus': 'Exode', 'Heros\'s Radiance': 'Radiance du héros', 'Heros\'s Sundering': 'Fragmentation du héros', 'Highest Holy': 'Miracle suprême', 'Hydaelyn\'s Ray': 'Rayon d\'Hydaelyn', 'Incandescence': 'Incandescence', 'Lightwave': 'Vague de Lumière', 'Magos\'s Radiance': 'Radiance du mage', 'Mousa\'s Scorn': 'Mépris de la muse', 'Parhelic Circle': 'Cercle parhélique', '(?<!Sub)Parhelion': 'Parhélie', 'Radiant Halo': 'Halo radiant', 'Subparhelion': 'Subparhélie', }, }, { 'locale': 'ja', 'replaceSync': { 'Echo of Hydaelyn': 'ハイデリン・エコー', '(?<!of )Hydaelyn': 'ハイデリン', 'Mystic Refulgence': '幻想光', }, 'replaceText': { 'Anthelion': 'アントゥヘリオン', 'Beacon': '光芒', 'Crystalline Blizzard III': 'クリスタル・ブリザガ', 'Crystalline Stone III': 'クリスタル・ストンガ', 'Crystallize': 'クリスタライズ', 'Dawn Mantle': 'マントチェンジ', 'Echoes': 'エコーズ', 'Equinox': 'エクイノックス', 'Exodus': 'エクソダス', 'Heros\'s Radiance': 'ヘロイスラジエンス', 'Heros\'s Sundering': 'ヘロイスサンダリング', 'Highest Holy': 'ハイエストホーリー', 'Hydaelyn\'s Ray': 'ハイデリンレイ', 'Incandescence': '幻閃光', 'Lightwave': 'ライトウェーブ', 'Magos\'s Radiance': 'マゴスラジエンス', 'Mousa\'s Scorn': 'ムーサスコーン', 'Parhelic Circle': 'パーヘリックサークル', '(?<!Sub)Parhelion': 'パルヘリオン', 'Radiant Halo': 'レディアントヘイロー', 'Subparhelion': 'サブパルヘリオン', }, }, ], }; export default triggerSet;
the_stack
import { CyNode } from '../CytoscapeGraphUtils'; import { BoxByType } from 'types/Graph'; import { getLayoutByName } from '../graphs/LayoutDictionary'; export const BOX_NODE_CLASS = '__boxNodeClass'; const NAMESPACE_KEY = 'box-layout'; const STYLES_KEY = NAMESPACE_KEY + 'styles'; const RELATIVE_POSITION_KEY = NAMESPACE_KEY + 'relative_position'; const PARENT_POSITION_KEY = NAMESPACE_KEY + '.parent_position'; // Styles used to have more control on how the compound nodes are going to be seen by the Layout algorithm. type OverridenStyles = { shape: string; width: string; height: string; }; type LayoutBoxTypeResult = { boxNodes: any; syntheticEdges: any; removedElements: any; }; /** * Synthetic edge generator replaces edges to and from boxed nodes with edges to/from their boxes. Care is * taken to not generate duplicate edges when sourceA has multiple real edges into the same box. */ class SyntheticEdgeGenerator { private nextId = 0; private generatedMap = {}; public getEdge(parentBoxType: BoxByType, source: any, target: any) { const sourceId = this.normalizeToParent(parentBoxType, source).id(); const targetId = this.normalizeToParent(parentBoxType, target).id(); if (sourceId === targetId) { return false; } const key = `${sourceId}->${targetId}`; if (this.generatedMap[key]) { return false; } this.generatedMap[key] = true; return { group: 'edges', data: { id: 'synthetic-edge-' + this.nextId++, source: sourceId, target: targetId } }; } // Returns the element's parent if it exists and is also of the correct boxType. private normalizeToParent(parentBoxType: BoxByType, element: any) { const parent = element.parent(); return parent && parent.data(CyNode.isBox) === parentBoxType ? parent : element; } } /** * Main class for the BoxLayout, used to bridge with cytoscape to make it easier to integrate with current code */ export default class BoxLayout { readonly appBoxLayout; readonly clusterBoxLayout; readonly defaultLayout; readonly namespaceBoxLayout; readonly cy; readonly elements; readonly syntheticEdgeGenerator; constructor(options: any) { this.appBoxLayout = options.appBoxLayout || options.defaultLayout; this.clusterBoxLayout = options.clusterBoxLayout || options.defaultLayout; this.defaultLayout = options.defaultLayout; this.namespaceBoxLayout = options.namespaceBoxLayout || options.defaultLayout; this.cy = options.cy; this.elements = options.eles; this.syntheticEdgeGenerator = new SyntheticEdgeGenerator(); } /** * This code gets executed on the cy.layout(...). run() is the entrypoint of this algorithm. */ run() { this.runAsync(); } /** * This is a stub required by cytoscape to allow the layout impl to emit events * @param _events space separated string of event names */ emit(_events) { // intentionally empty } // Discrete layouts (dagre) always stop before layout.run() returns. Continuous layouts (cose,cola) // are started by layout.run() but may stop after run() returns. Because outer boxes require the inner // box layouts to complete, we need to force discrete behavior regardless of layout, and that is why // this code is complicated with a variety of async handling. Note that because namespace or cluster // boxes may comprise large portions of the graph, we need to be flexible with the layout support (in // other words, we can't force dagre like we do for app boxes). async runAsync(): Promise<any> { let allBoxNodes = this.cy.collection(); let removedElements = this.cy.collection(); let syntheticEdges = this.cy.collection(); let result; // (1) working from inner boxing to outer boxing, perform the box layouts. the inner box layouts // must complete before the outer box layouts can proceed. result = await this.layoutBoxType(BoxByType.APP); allBoxNodes = allBoxNodes.add(result.boxNodes); removedElements = removedElements.add(result.removedElements); syntheticEdges = syntheticEdges.add(result.syntheticEdges); result = await this.layoutBoxType(BoxByType.NAMESPACE); allBoxNodes = allBoxNodes.add(result.boxNodes); removedElements = removedElements.add(result.removedElements); syntheticEdges = syntheticEdges.add(result.syntheticEdges); result = await this.layoutBoxType(BoxByType.CLUSTER); allBoxNodes = allBoxNodes.add(result.boxNodes); removedElements = removedElements.add(result.removedElements); syntheticEdges = syntheticEdges.add(result.syntheticEdges); // (3) perform the final layout... // Before running the layout, reset the elements positions. // This is not absolutely necessary, but without this we have seen some problems with // `cola` + firefox + a particular mesh // Ensure we only touch the requested elements and not the whole graph. const layoutElements = this.cy.collection().add(this.elements).subtract(removedElements).add(syntheticEdges); layoutElements.position({ x: 0, y: 0 }); const layout = this.cy.layout({ // Create a new layout ...getLayoutByName(this.defaultLayout), // Sharing the main options eles: this.cy.elements() // and the current elements }); // Add a one-time callback to be fired when the layout stops layout.one('layoutstop', _event => { // If we add any children back, our parent nodes position are going to take the bounding box's position of all // their children. Before doing it, save this position in order to add this up to their children. allBoxNodes.each(boxNode => { boxNode.scratch(PARENT_POSITION_KEY, { ...boxNode.position() }); // Make a copy of the position, its an internal data from cy. }); // (3.a) Add back the child nodes (with edges still attached) removedElements.restore(); // (3.b) Remove synthetic edges this.cy.remove(syntheticEdges); // (3.c) Add and position the children nodes according to the layout allBoxNodes.each(boxNode => { const parentPosition = boxNode.scratch(PARENT_POSITION_KEY); boxNode.children().each(child => { const relativePosition = child.scratch(RELATIVE_POSITION_KEY); child.position({ x: parentPosition.x + relativePosition.x, y: parentPosition.y + relativePosition.y }); child.removeData(RELATIVE_POSITION_KEY); }); boxNode.style(boxNode.scratch(STYLES_KEY)); boxNode.removeClass(BOX_NODE_CLASS); // Discard the saved values boxNode.removeScratch(STYLES_KEY); boxNode.removeScratch(PARENT_POSITION_KEY); }); this.emit('layoutstop'); }); layout.run(); } async layoutBoxType(boxByType: BoxByType): Promise<LayoutBoxTypeResult> { return new Promise((resolve, _reject) => { const boxNodes = this.getBoxNodes(boxByType); let boxLayoutOptions; switch (boxByType) { case BoxByType.APP: boxLayoutOptions = getLayoutByName(this.appBoxLayout); break; case BoxByType.CLUSTER: boxLayoutOptions = getLayoutByName(this.clusterBoxLayout); break; case BoxByType.NAMESPACE: boxLayoutOptions = getLayoutByName(this.namespaceBoxLayout); break; default: boxLayoutOptions = getLayoutByName(this.defaultLayout); } // Before completing work for the box type we must wait for all individual box work to complete const boxNodePromises: Promise<any>[] = []; // (2) Prepare each box node by assigning a size and running the compound layout boxNodes.each(boxNode => { const boxedNodes = boxNode.children(); const boxedElements = boxedNodes.add(boxedNodes.edgesTo(boxedNodes)); const boxLayout = boxedElements.layout(boxLayoutOptions); boxNodePromises.push( new Promise((resolve, _reject) => { // (2.a) This promise resolves when the layout actually stops. this.runLayout(boxLayoutOptions.name, boxLayout).then(_response => { // (2.b) get the bounding box // see https://github.com/cytoscape/cytoscape.js/issues/2402 const boundingBox = boxNode.boundingBox(); // Save the relative positions, as we will need them later. boxedNodes.each(boxedNode => { boxedNode.scratch(RELATIVE_POSITION_KEY, boxedNode.relativePosition()); }); const backupStyles: OverridenStyles = { shape: boxNode.style('shape'), height: boxNode.style('height'), width: boxNode.style('width') }; const newStyles: OverridenStyles = { shape: 'rectangle', height: `${boundingBox.h}px`, width: `${boundingBox.w}px` }; // Saves a backup of current styles to restore them after we finish boxNode.scratch(STYLES_KEY, backupStyles); boxNode.addClass(BOX_NODE_CLASS); boxNode.style(newStyles); resolve(true); }); }) ); }); Promise.all(boxNodePromises).then(_results => { let removedElements = this.cy.collection(); let syntheticEdges = this.cy.collection(); // (2.c) Add synthetic edges for every edge that touches a child node. const boxedNodes = boxNodes.children(); for (const boxedNode of boxedNodes) { for (const edge of boxedNode.connectedEdges()) { const syntheticEdge = this.syntheticEdgeGenerator.getEdge(boxByType, edge.source(), edge.target()); if (syntheticEdge) { syntheticEdges = syntheticEdges.add(this.cy.add(syntheticEdge)); } } } // (2.d) Remove all child nodes from parents (and their edges). removedElements = removedElements.add(this.cy.remove(boxedNodes)); resolve({ boxNodes: boxNodes, syntheticEdges: syntheticEdges, removedElements: removedElements }); }); }); } async runLayout(layoutName, layout): Promise<any> { // Avoid propagating any local layout events up to cy, this would yield a global operation before the nodes are ready. layout.on('layoutstart layoutready layoutstop', _event => { return false; }); // We know dagre is discrete, we can resolve when run() returns if (layoutName === 'dagre') { return layout.run(); } const promise = layout.promiseOn('layoutstop'); layout.run(); return promise; } getBoxNodes(boxByType: BoxByType): any { return this.elements.nodes(`[${CyNode.isBox}="${boxByType}"]`); } }
the_stack
import _ from 'lodash'; import path from 'path'; import { Config as AppConfig, ROLES, createAnonymousRemoteUser, createRemoteUser, parseConfigFile, } from '@verdaccio/config'; import { API_ERROR, CHARACTER_ENCODING, TOKEN_BEARER, VerdaccioError, errorUtils, } from '@verdaccio/core'; import { setup } from '@verdaccio/logger'; import { configExample } from '@verdaccio/mock'; import { Config, RemoteUser, Security } from '@verdaccio/types'; import { AllowActionCallbackResponse, buildToken, buildUserBuffer, getAuthenticatedMessage, } from '@verdaccio/utils'; import { ActionsAllowed, Auth, IAuth, aesDecrypt, allow_action, getApiToken, getDefaultPlugins, getMiddlewareCredentials, signPayload, verifyJWTPayload, verifyPayload, } from '../src'; setup([]); const parseConfigurationFile = (conf) => { const { name, ext } = path.parse(conf); const format = ext.startsWith('.') ? ext.substring(1) : 'yaml'; return path.join(__dirname, `./partials/config/${format}/security/${name}.${format}`); }; describe('Auth utilities', () => { jest.setTimeout(20000); const parseConfigurationSecurityFile = (name) => { return parseConfigurationFile(`security/${name}`); }; function getConfig(configFileName: string, secret: string) { const conf = parseConfigFile(parseConfigurationSecurityFile(configFileName)); // @ts-ignore const secConf = _.merge(configExample(), conf); secConf.secret = secret; const config: Config = new AppConfig(secConf); return config; } async function getTokenByConfiguration( configFileName: string, username: string, password: string, secret = '12345', methodToSpy: string, methodNotBeenCalled: string ): Promise<string> { const config: Config = getConfig(configFileName, secret); const auth: IAuth = new Auth(config); // @ts-ignore const spy = jest.spyOn(auth, methodToSpy); // @ts-ignore const spyNotCalled = jest.spyOn(auth, methodNotBeenCalled); const user: RemoteUser = { name: username, real_groups: [], groups: [], }; const token = await getApiToken(auth, config, user, password); expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalledTimes(1); expect(spyNotCalled).not.toHaveBeenCalled(); expect(token).toBeDefined(); return token as string; } const verifyJWT = (token: string, user: string, password: string, secret: string) => { const payload = verifyPayload(token, secret); expect(payload.name).toBe(user); expect(payload.groups).toBeDefined(); expect(payload.real_groups).toBeDefined(); }; const verifyAES = (token: string, user: string, password: string, secret: string) => { // @ts-ignore const payload = aesDecrypt(token, secret).toString(CHARACTER_ENCODING.UTF8); const content = payload.split(':'); expect(content[0]).toBe(user); expect(content[0]).toBe(password); }; describe('getDefaultPlugins', () => { test('authentication should fail by default (default)', () => { const plugin = getDefaultPlugins({ trace: jest.fn() }); plugin.authenticate('foo', 'bar', (error: any) => { expect(error).toEqual(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD)); }); }); test('add user should fail by default (default)', () => { const plugin = getDefaultPlugins({ trace: jest.fn() }); // @ts-ignore plugin.adduser('foo', 'bar', (error: any) => { expect(error).toEqual(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD)); }); }); }); describe('allow_action', () => { describe('access/publish/unpublish and anonymous', () => { const packageAccess = { name: 'foo', version: undefined, access: ['foo'], unpublish: false, }; // const type = 'access'; test.each(['access', 'publish', 'unpublish'])( 'should restrict %s to anonymous users', (type) => { allow_action(type as ActionsAllowed, { trace: jest.fn() })( createAnonymousRemoteUser(), { ...packageAccess, [type]: ['foo'], }, (error: VerdaccioError | null, allowed: AllowActionCallbackResponse) => { expect(error).not.toBeNull(); expect(allowed).toBeUndefined(); } ); } ); test.each(['access', 'publish', 'unpublish'])( 'should allow %s to anonymous users', (type) => { allow_action(type as ActionsAllowed, { trace: jest.fn() })( createAnonymousRemoteUser(), { ...packageAccess, [type]: [ROLES.$ANONYMOUS], }, (error: VerdaccioError | null, allowed: AllowActionCallbackResponse) => { expect(error).toBeNull(); expect(allowed).toBe(true); } ); } ); test.each(['access', 'publish', 'unpublish'])( 'should allow %s only if user is anonymous if the logged user has groups', (type) => { allow_action(type as ActionsAllowed, { trace: jest.fn() })( createRemoteUser('juan', ['maintainer', 'admin']), { ...packageAccess, [type]: [ROLES.$ANONYMOUS], }, (error: VerdaccioError | null, allowed: AllowActionCallbackResponse) => { expect(error).not.toBeNull(); expect(allowed).toBeUndefined(); } ); } ); test.each(['access', 'publish', 'unpublish'])( 'should allow %s only if user is anonymous match any other groups', (type) => { allow_action(type as ActionsAllowed, { trace: jest.fn() })( createRemoteUser('juan', ['maintainer', 'admin']), { ...packageAccess, [type]: ['admin', 'some-other-group', ROLES.$ANONYMOUS], }, (error: VerdaccioError | null, allowed: AllowActionCallbackResponse) => { expect(error).toBeNull(); expect(allowed).toBe(true); } ); } ); test.each(['access', 'publish', 'unpublish'])( 'should not allow %s anonymous if other groups are defined and does not match', (type) => { allow_action(type as ActionsAllowed, { trace: jest.fn() })( createRemoteUser('juan', ['maintainer', 'admin']), { ...packageAccess, [type]: ['bla-bla-group', 'some-other-group', ROLES.$ANONYMOUS], }, (error: VerdaccioError | null, allowed: AllowActionCallbackResponse) => { expect(error).not.toBeNull(); expect(allowed).toBeUndefined(); } ); } ); }); }); describe('getApiToken test', () => { test('should sign token with aes and security missing', async () => { const token = await getTokenByConfiguration( 'security-missing', 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2', 'aesEncrypt', 'jwtEncrypt' ); verifyAES(token, 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2'); expect(_.isString(token)).toBeTruthy(); }); test('should sign token with aes and security empty', async () => { const token = await getTokenByConfiguration( 'security-empty', 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2', 'aesEncrypt', 'jwtEncrypt' ); verifyAES(token, 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2'); expect(_.isString(token)).toBeTruthy(); }); test('should sign token with aes', async () => { const token = await getTokenByConfiguration( 'security-basic', 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2', 'aesEncrypt', 'jwtEncrypt' ); verifyAES(token, 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2'); expect(_.isString(token)).toBeTruthy(); }); test('should sign token with legacy and jwt disabled', async () => { const token = await getTokenByConfiguration( 'security-no-legacy', 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2', 'aesEncrypt', 'jwtEncrypt' ); expect(_.isString(token)).toBeTruthy(); verifyAES(token, 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2'); }); test('should sign token with legacy enabled and jwt enabled', async () => { const token = await getTokenByConfiguration( 'security-jwt-legacy-enabled', 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2', 'jwtEncrypt', 'aesEncrypt' ); verifyJWT(token, 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2'); expect(_.isString(token)).toBeTruthy(); }); test('should sign token with jwt enabled', async () => { const token = await getTokenByConfiguration( 'security-jwt', 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2', 'jwtEncrypt', 'aesEncrypt' ); expect(_.isString(token)).toBeTruthy(); verifyJWT(token, 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2'); }); test('should sign with jwt whether legacy is disabled', async () => { const token = await getTokenByConfiguration( 'security-legacy-disabled', 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2', 'jwtEncrypt', 'aesEncrypt' ); expect(_.isString(token)).toBeTruthy(); verifyJWT(token, 'test', 'test', 'b2df428b9929d3ace7c598bbf4e496b2'); }); }); describe('getAuthenticatedMessage test', () => { test('should sign token with jwt enabled', () => { expect(getAuthenticatedMessage('test')).toBe("you are authenticated as 'test'"); }); }); describe('getMiddlewareCredentials test', () => { describe('should get AES credentials', () => { test.concurrent('should unpack aes token and credentials bearer auth', async () => { const secret = 'b2df428b9929d3ace7c598bbf4e496b2'; const user = 'test'; const pass = 'test'; const token = await getTokenByConfiguration( 'security-legacy', user, pass, secret, 'aesEncrypt', 'jwtEncrypt' ); const config: Config = getConfig('security-legacy', secret); const security: Security = config.security; const credentials = getMiddlewareCredentials(security, secret, `Bearer ${token}`); expect(credentials).toBeDefined(); // @ts-ignore expect(credentials.user).toEqual(user); // @ts-ignore expect(credentials.password).toEqual(pass); }); test.concurrent('should unpack aes token and credentials basic auth', async () => { const secret = 'b2df428b9929d3ace7c598bbf4e496b2'; const user = 'test'; const pass = 'test'; // basic authentication need send user as base64 const token = buildUserBuffer(user, pass).toString('base64'); const config: Config = getConfig('security-legacy', secret); const security: Security = config.security; const credentials = getMiddlewareCredentials(security, secret, `Basic ${token}`); expect(credentials).toBeDefined(); // @ts-ignore expect(credentials.user).toEqual(user); // @ts-ignore expect(credentials.password).toEqual(pass); }); test.concurrent('should return empty credential wrong secret key', async () => { const secret = 'b2df428b9929d3ace7c598bbf4e496b2'; const token = await getTokenByConfiguration( 'security-legacy', 'test', 'test', secret, 'aesEncrypt', 'jwtEncrypt' ); const config: Config = getConfig('security-legacy', secret); const security: Security = config.security; const credentials = getMiddlewareCredentials( security, 'b2df428b9929d3ace7c598bbf4e496_BAD_TOKEN', buildToken(TOKEN_BEARER, token) ); expect(credentials).not.toBeDefined(); }); test.concurrent('should return empty credential wrong scheme', async () => { const secret = 'b2df428b9929d3ace7c598bbf4e496b2'; const token = await getTokenByConfiguration( 'security-legacy', 'test', 'test', secret, 'aesEncrypt', 'jwtEncrypt' ); const config: Config = getConfig('security-legacy', secret); const security: Security = config.security; const credentials = getMiddlewareCredentials( security, secret, buildToken('BAD_SCHEME', token) ); expect(credentials).not.toBeDefined(); }); test.concurrent('should return empty credential corrupted payload', async () => { const secret = 'b2df428b9929d3ace7c598bbf4e496b2'; const config: Config = getConfig('security-legacy', secret); const auth: IAuth = new Auth(config); const token = auth.aesEncrypt(null); const security: Security = config.security; const credentials = getMiddlewareCredentials( security, secret, buildToken(TOKEN_BEARER, token as string) ); expect(credentials).not.toBeDefined(); }); }); describe('verifyJWTPayload', () => { test('should fail on verify the token and return anonymous users', () => { expect(verifyJWTPayload('fakeToken', 'b2df428b9929d3ace7c598bbf4e496b2')).toEqual( createAnonymousRemoteUser() ); }); test('should verify the token and return a remote user', async () => { const remoteUser = createRemoteUser('foo', []); const token = await signPayload(remoteUser, '12345'); const verifiedToken = verifyJWTPayload(token, '12345'); expect(verifiedToken.groups).toEqual(remoteUser.groups); expect(verifiedToken.name).toEqual(remoteUser.name); }); }); describe('should get JWT credentials', () => { test('should return anonymous whether token is corrupted', () => { const config: Config = getConfig('security-jwt', '12345'); const security: Security = config.security; const credentials = getMiddlewareCredentials( security, '12345', buildToken(TOKEN_BEARER, 'fakeToken') ); expect(credentials).toBeDefined(); // @ts-ignore expect(credentials.name).not.toBeDefined(); // @ts-ignore expect(credentials.real_groups).toBeDefined(); // @ts-ignore expect(credentials.real_groups).toEqual([]); }); test('should return anonymous whether token and scheme are corrupted', () => { const config: Config = getConfig('security-jwt', '12345'); const security: Security = config.security; const credentials = getMiddlewareCredentials( security, '12345', buildToken('FakeScheme', 'fakeToken') ); expect(credentials).not.toBeDefined(); }); test('should verify successfully a JWT token', async () => { const secret = 'b2df428b9929d3ace7c598bbf4e496b2'; const user = 'test'; const config: Config = getConfig('security-jwt', secret); const token = await getTokenByConfiguration( 'security-jwt', user, 'secretTest', secret, 'jwtEncrypt', 'aesEncrypt' ); const security: Security = config.security; const credentials = getMiddlewareCredentials( security, secret, buildToken(TOKEN_BEARER, token) ); expect(credentials).toBeDefined(); // @ts-ignore expect(credentials.name).toEqual(user); // @ts-ignore expect(credentials.real_groups).toBeDefined(); // @ts-ignore expect(credentials.real_groups).toEqual([]); }); }); }); });
the_stack
import { LayoutViewer } from '../index'; import { TableOptionsDialog } from './index'; import { Dialog } from '@syncfusion/ej2-popups'; import { CheckBox } from '@syncfusion/ej2-buttons'; import { NumericTextBox } from '@syncfusion/ej2-inputs'; import { WCellFormat } from '../index'; import { isNullOrUndefined, L10n, createElement } from '@syncfusion/ej2-base'; import { SelectionTableFormat, SelectionCellFormat } from '../index'; import { TableRowWidget, TableCellWidget } from '../viewer/page'; import { TextPosition } from '../selection/selection-helper'; import { DocumentHelper } from '../viewer'; /** * The Cell options dialog is used to modify margins of selected cells. */ export class CellOptionsDialog { /** * @private */ public documentHelper: DocumentHelper; public owner: LayoutViewer; /** * @private */ public dialog: Dialog; /** * @private */ public target: HTMLElement; private sameAsTableCheckBox: CheckBox; /** * @private */ public sameAsTable: boolean; /** * @private */ public topMarginBox: NumericTextBox; /** * @private */ public leftMarginBox: NumericTextBox; /** * @private */ public bottomMarginBox: NumericTextBox; /** * @private */ public rightMarginBox: NumericTextBox; /** * @private */ public cellFormatIn: WCellFormat; /** * @param {DocumentHelper} documentHelper - Specifies the document helper. * @private */ public constructor(documentHelper: DocumentHelper) { this.documentHelper = documentHelper; } /** * @private * @returns {WCellFormat} - Returns cell format. */ public get cellFormat(): WCellFormat { if (isNullOrUndefined(this.cellFormatIn)) { return this.cellFormatIn = new WCellFormat(); } return this.cellFormatIn; } private getModuleName(): string { return 'CellOptionsDialog'; } /** * @private * @param {L10n} localValue - Specifies the locale. * @param {boolean} isRtl - Specifies is rtl. * @returns {void} */ public initCellMarginsDialog(localValue: L10n, isRtl?: boolean): void { this.owner = this.documentHelper.owner.viewer; this.target = createElement('div', { className: 'e-de-table-cell-margin-dlg' }); const innerDiv: HTMLDivElement = <HTMLDivElement>createElement('div'); const innerDivLabel: HTMLElement = createElement('Label', { className: 'e-de-para-dlg-heading' }); innerDivLabel.innerHTML = localValue.getConstant('Cell margins'); innerDiv.appendChild(innerDivLabel); const table: HTMLTableElement = <HTMLTableElement>createElement('TABLE', { styles: 'padding-bottom: 8px;padding-top: 8px;', className: 'e-de-cell-margin-top' }); const tr: HTMLTableRowElement = <HTMLTableRowElement>createElement('tr'); const td: HTMLTableCellElement = <HTMLTableCellElement>createElement('td', { className: 'e-de-tbl-btn-separator' }); const sameAsTableCheckBox: HTMLInputElement = <HTMLInputElement>createElement('input', { attrs: { 'type': 'checkbox' }, id: this.target.id + '_sameAsCheckBox' }); td.appendChild(sameAsTableCheckBox); tr.appendChild(td); table.appendChild(tr); innerDiv.appendChild(table); CellOptionsDialog.getCellMarginDialogElements(this, innerDiv, localValue, true); const divBtn: HTMLDivElement = document.createElement('div'); this.target.appendChild(divBtn); this.sameAsTableCheckBox = new CheckBox({ label: localValue.getConstant('Same as the whole table'), change: this.changeSameAsTable, enableRtl: isRtl }); this.sameAsTableCheckBox.appendTo(sameAsTableCheckBox); this.sameAsTableCheckBox.addEventListener('change', this.changeSameAsTable); } /** * @private * @returns {void} */ public show(): void { const localizeValue: L10n = new L10n('documenteditor', this.documentHelper.owner.defaultLocale); localizeValue.setLocale(this.documentHelper.owner.locale); if (!this.target) { this.initCellMarginsDialog(localizeValue, this.documentHelper.owner.enableRtl); } this.loadCellMarginsDialog(); this.documentHelper.dialog.header = localizeValue.getConstant('Cell Options'); this.documentHelper.dialog.position = { X: 'center', Y: 'center' }; this.documentHelper.dialog.height = 'auto'; this.documentHelper.dialog.width = 'auto'; this.documentHelper.dialog.content = this.target; this.documentHelper.dialog.beforeOpen = undefined; this.documentHelper.dialog.open = undefined; this.documentHelper.dialog.close = this.removeEvents; this.documentHelper.dialog.buttons = [{ click: this.applyTableCellProperties, buttonModel: { content: localizeValue.getConstant('Ok'), cssClass: 'e-flat e-table-cell-margin-okay', isPrimary: true } }, { click: this.closeCellMarginsDialog, buttonModel: { content: localizeValue.getConstant('Cancel'), cssClass: 'e-flat e-table-cell-margin-cancel' } }]; this.documentHelper.dialog.show(); } /** * @private * @returns {void} */ public removeEvents = (): void => { this.documentHelper.dialog2.element.style.pointerEvents = ''; this.documentHelper.updateFocus(); }; /** * @private * @returns {void} */ public changeSameAsTable = (): void => { if (this.sameAsTableCheckBox.checked) { this.leftMarginBox.enabled = false; this.rightMarginBox.enabled = false; this.bottomMarginBox.enabled = false; this.topMarginBox.enabled = false; } else { this.leftMarginBox.enabled = true; this.rightMarginBox.enabled = true; this.bottomMarginBox.enabled = true; this.topMarginBox.enabled = true; } }; /** * @private * @returns {void} */ public loadCellMarginsDialog(): void { const cellFormat: SelectionCellFormat = this.documentHelper.selection.cellFormat; this.sameAsTable = isNullOrUndefined(cellFormat.leftMargin || cellFormat.topMargin || cellFormat.rightMargin || cellFormat.bottomMargin); if (this.sameAsTable) { const tableFormat: SelectionTableFormat = this.documentHelper.selection.tableFormat; this.loadCellProperties(tableFormat, false, true); } else { this.loadCellProperties(cellFormat, true, false); } } private loadCellProperties(format: SelectionCellFormat | SelectionTableFormat, enableTextBox: boolean, enableCheckBox: boolean): void { this.leftMarginBox.value = format.leftMargin; this.rightMarginBox.value = format.rightMargin; this.topMarginBox.value = format.topMargin; this.bottomMarginBox.value = format.bottomMargin; this.leftMarginBox.enabled = enableTextBox; this.rightMarginBox.enabled = enableTextBox; this.topMarginBox.enabled = enableTextBox; this.bottomMarginBox.enabled = enableTextBox; this.sameAsTableCheckBox.checked = enableCheckBox; } /** * @private * @returns {void} */ public applyTableCellProperties = (): void => { const cellFormat: SelectionCellFormat = this.documentHelper.selection.cellFormat; if (!isNullOrUndefined(this.bottomMarginBox.value || this.leftMarginBox.value || this.rightMarginBox.value || this.topMarginBox.value) && (cellFormat.bottomMargin !== this.bottomMarginBox.value || cellFormat.leftMargin !== this.leftMarginBox.value || cellFormat.rightMargin !== this.rightMarginBox.value || cellFormat.topMargin !== this.topMarginBox.value)) { this.documentHelper.owner.tablePropertiesDialogModule.isCellOptionsUpdated = true; this.applyTableOptions(this.cellFormat); this.documentHelper.owner.tablePropertiesDialogModule.applyTableSubProperties(); } this.closeCellMarginsDialog(); }; /** * @private * @param {WCellFormat} cellFormat Specifies cell format. * @returns {void} */ public applySubCellOptions(cellFormat: WCellFormat): void { this.documentHelper.owner.editorHistory.initComplexHistory(this.documentHelper.selection, 'CellMarginsSelection'); this.documentHelper.owner.editorModule.initHistory('CellOptions'); /* eslint-disable max-len */ this.documentHelper.selection.start.paragraph.associatedCell.ownerTable.combineWidget(this.owner); this.applyCellMarginValue(this.documentHelper.selection.start.paragraph.associatedCell.ownerRow.combineWidget(this.owner) as TableRowWidget, this.documentHelper.selection.start, this.documentHelper.selection.end, cellFormat); this.documentHelper.owner.editorModule.reLayout(this.documentHelper.selection, false); if (!isNullOrUndefined(this.documentHelper.owner.editorHistory.currentHistoryInfo)) { this.documentHelper.owner.editorHistory.updateComplexHistory(); } } public applyCellMarginValue(row: TableRowWidget, start: TextPosition, end: TextPosition, cellFormat: WCellFormat): void { this.applyCellMarginsInternal(row, cellFormat); if (end.paragraph.associatedCell.ownerRow === row) { return; } const newRow: TableRowWidget = row.nextWidget as TableRowWidget; if (!isNullOrUndefined(newRow)) { this.applyCellMarginValue(newRow, start, end, cellFormat); } } private applyCellMarginsInternal(row: TableRowWidget, cellFormat: WCellFormat): void { if (!isNullOrUndefined(this.documentHelper.owner.editorHistory.currentBaseHistoryInfo)) { const currentFormat: WCellFormat = (row.childWidgets[0] as TableCellWidget).cellFormat; /* eslint-disable max-len */ cellFormat = this.documentHelper.owner.editorHistory.currentBaseHistoryInfo.addModifiedCellOptions(currentFormat, cellFormat, row.ownerTable); } if (!isNullOrUndefined(cellFormat)) { this.applyCellMarginsForCells(row, cellFormat); } } private applyCellMarginsForCells(row: TableRowWidget, cellFormat: WCellFormat): void { const rowCells: TableCellWidget[] = row.childWidgets as TableCellWidget[]; this.iterateCells(rowCells, cellFormat); } private iterateCells(cells: TableCellWidget[], cellFormat: WCellFormat): void { for (let i: number = 0; i < cells.length; i++) { this.applySubCellMargins(cells[i].cellFormat, cellFormat); } this.documentHelper.owner.tablePropertiesDialogModule.calculateGridValue(cells[0].ownerTable); } private applySubCellMargins(sourceFormat: WCellFormat, cellFormat: WCellFormat): void { sourceFormat.leftMargin = cellFormat.leftMargin; sourceFormat.topMargin = cellFormat.topMargin; sourceFormat.rightMargin = cellFormat.rightMargin; sourceFormat.bottomMargin = cellFormat.bottomMargin; } private applyTableOptions(cellFormat: WCellFormat): void { if (!this.sameAsTableCheckBox.checked) { cellFormat.leftMargin = this.leftMarginBox.value; cellFormat.topMargin = this.topMarginBox.value; cellFormat.bottomMargin = this.bottomMarginBox.value; cellFormat.rightMargin = this.rightMarginBox.value; } } /** * @private * @returns {void} */ public closeCellMarginsDialog = (): void => { this.documentHelper.dialog.hide(); this.documentHelper.dialog.element.style.pointerEvents = ''; }; /** * @private * @returns {void} */ public destroy(): void { if (!isNullOrUndefined(this.target)) { if (this.target.parentElement) { this.target.parentElement.removeChild(this.target); } for (let y: number = 0; y < this.target.childNodes.length; y++) { this.target.removeChild(this.target.childNodes[y]); y--; } this.target = undefined; } this.dialog = undefined; this.target = undefined; this.documentHelper = undefined; this.sameAsTableCheckBox = undefined; } /** * @private * @param {CellOptionsDialog | TableOptionsDialog} dialog - Specifies cell options dialog. * @param {HTMLDivElement} div - Specifies the html element. * @param {L10n} locale - Specifies the locale * @returns {void} */ public static getCellMarginDialogElements(dialog: CellOptionsDialog | TableOptionsDialog, div: HTMLDivElement, locale: L10n, cellOptions: boolean): void { if (!isNullOrUndefined(dialog)) { const table: HTMLTableElement = <HTMLTableElement>createElement('div'); const tr1: HTMLTableRowElement = <HTMLTableRowElement>createElement('div', { className: 'e-de-container-row' }); const td1: HTMLTableCellElement = <HTMLTableCellElement>createElement('div', { className: 'e-de-subcontainer-left' }); const topTextBox: HTMLInputElement = <HTMLInputElement>createElement('input', { attrs: { 'type': 'text' }, styles: 'width:100%' }); td1.appendChild(topTextBox); const td2: HTMLTableCellElement = <HTMLTableCellElement>createElement('div', { className: 'e-de-subcontainer-right' }); const leftTextBox: HTMLInputElement = <HTMLInputElement>createElement('input', { attrs: { 'type': 'text' }, styles: 'width:100%' }); td2.appendChild(leftTextBox); tr1.appendChild(td1); tr1.appendChild(td2); const tr2: HTMLTableRowElement = <HTMLTableRowElement>createElement('div', { className: cellOptions ? 'e-de-dlg-row' : 'e-de-container-row' }); const td3: HTMLTableCellElement = <HTMLTableCellElement>createElement('div', { className: 'e-de-subcontainer-left' }); const bottomTextBox: HTMLInputElement = <HTMLInputElement>createElement('input', { attrs: { 'type': 'text' }, styles: 'width:100%' }); td3.appendChild(bottomTextBox); const td4: HTMLTableCellElement = <HTMLTableCellElement>createElement('div', { className: 'e-de-subcontainer-right' }); const rightTextBox: HTMLInputElement = <HTMLInputElement>createElement('input', { attrs: { 'type': 'text' }, styles: 'width:100%' }); td4.appendChild(rightTextBox); tr2.appendChild(td3); tr2.appendChild(td4); table.appendChild(tr1); table.appendChild(tr2); div.appendChild(table); dialog.target.appendChild(div); dialog.topMarginBox = new NumericTextBox({ value: 0, min: 0, max: 1584, decimals: 2, enablePersistence: false, placeholder: locale.getConstant('Top'), floatLabelType: 'Always' }); dialog.topMarginBox.appendTo(topTextBox); dialog.leftMarginBox = new NumericTextBox({ value: 0, min: 0, max: 1584, decimals: 2, enablePersistence: false, placeholder: locale.getConstant('Left'), floatLabelType: 'Always' }); dialog.leftMarginBox.appendTo(leftTextBox); dialog.bottomMarginBox = new NumericTextBox({ value: 0, min: 0, max: 1584, decimals: 2, enablePersistence: false, placeholder: locale.getConstant('Bottom'), floatLabelType: 'Always' }); dialog.bottomMarginBox.appendTo(bottomTextBox); dialog.rightMarginBox = new NumericTextBox({ value: 0, min: 0, max: 1584, decimals: 2, enablePersistence: false, placeholder: locale.getConstant('Right'), floatLabelType: 'Always' }); dialog.rightMarginBox.appendTo(rightTextBox); } } }
the_stack
import { KeysInitSparql, KeysQueryOperation } from '@comunica/context-entries'; import type { ActionContext, IActorArgs, IActorTest, Mediator } from '@comunica/core'; import { Actor } from '@comunica/core'; import { BlankNodeBindingsScoped } from '@comunica/data-factory'; import type { IActionQueryOperation, IActorQueryOperationOutput, IActorQueryOperationOutputBindings, IActorQueryOperationOutputBoolean, IActorQueryOperationOutputQuads, IActorQueryOperationOutputUpdate, IActorQueryOperationOutputStream, Bindings, PatternBindings, } from '@comunica/types'; import type * as RDF from '@rdfjs/types'; import type { Algebra } from 'sparqlalgebrajs'; import { materializeOperation } from './Bindings'; /** * @deprecated Use the type in @comunica/types */ export type { IActionQueryOperation }; /** * @deprecated Use the type in @comunica/types */ export type { IActorQueryOperationOutput }; /** * @deprecated Use the type in @comunica/types */ export type { IActorQueryOperationOutputBindings }; /** * @deprecated Use the type in @comunica/types */ export type { IActorQueryOperationOutputBoolean }; /** * @deprecated Use the type in @comunica/types */ export type { IActorQueryOperationOutputQuads }; /** * @deprecated Use the type in @comunica/types */ export type { IActorQueryOperationOutputUpdate }; /** * @deprecated Use the type in @comunica/types */ export type { IActorQueryOperationOutputStream }; /** * @deprecated Use the type in @comunica/types */ export type { PatternBindings as IPatternBindings }; /** * @type {string} Context entry for current metadata. * I.e., the metadata that was used to determine the next BGP operation. * @value {any} A metadata hash. * @deprecated Import this constant from @comunica/context-entries. */ export const KEY_CONTEXT_BGP_CURRENTMETADATA = KeysQueryOperation.bgpCurrentMetadata; /** * @type {string} Context entry for an array of parent metadata. * I.e., an array of the metadata that was present before materializing the current BGP operations. * This can be passed in 'bgp' actions. * The array entries should correspond to the pattern entries in the BGP. * @value {any} An array of metadata hashes. * @deprecated Import this constant from @comunica/context-entries. */ export const KEY_CONTEXT_BGP_PARENTMETADATA = KeysQueryOperation.bgpParentMetadata; /** * @type {string} Context entry for indicating which patterns were bound from variables. * I.e., an array of the same length as the value of KeysQueryOperation.patternParentMetadata, * where each array value corresponds to the pattern bindings for the corresponding pattern. * @value {any} An array of {@link PatternBindings}. * @deprecated Import this constant from @comunica/context-entries. */ export const KEY_CONTEXT_BGP_PATTERNBINDINGS = KeysQueryOperation.bgpPatternBindings; /** * @type {string} Context entry for parent metadata. * I.e., the metadata that was present before materializing the current operation. * This can be passed in 'pattern' actions. * @value {any} A metadata hash. * @deprecated Import this constant from @comunica/context-entries. */ export const KEY_CONTEXT_PATTERN_PARENTMETADATA = KeysQueryOperation.patternParentMetadata; /** * @type {string} Context entry for query's base IRI. * @value {any} A string. * @deprecated Import this constant from @comunica/context-entries. */ export const KEY_CONTEXT_BASEIRI = KeysInitSparql.baseIRI; /** * @type {string} A timestamp representing the current time. * This is required for certain SPARQL operations such as NOW(). * @value {any} a date. * @deprecated Import this constant from @comunica/context-entries. */ export const KEY_CONTEXT_QUERY_TIMESTAMP = KeysInitSparql.queryTimestamp; /** * @type {string} Context entry for indicating that only read operations are allowed, defaults to false. * @value {any} A boolean. * @deprecated Import this constant from @comunica/context-entries. */ export const KEY_CONTEXT_READONLY = KeysQueryOperation.readOnly; /** * A counter that keeps track blank node generated through BNODE() SPARQL * expressions. * * @type {number} */ let bnodeCounter = 0; /** * A comunica actor for query-operation events. * * Actor types: * * Input: IActionQueryOperation: A SPARQL Algebra operation. * * Test: <none> * * Output: IActorQueryOperationOutput: A bindings stream. * * @see IActionQueryOperation * @see IActorQueryOperationOutput */ export abstract class ActorQueryOperation extends Actor<IActionQueryOperation, IActorTest, IActorQueryOperationOutput> { protected constructor(args: IActorArgs<IActionQueryOperation, IActorTest, IActorQueryOperationOutput>) { super(args); } /** * Safely cast a query operation output to a bindings output. * This will throw a runtime error if the output is of the incorrect type. * @param {IActorQueryOperationOutput} output A query operation output. * @return {IActorQueryOperationOutputBindings} A bindings query operation output. */ public static getSafeBindings(output: IActorQueryOperationOutput): IActorQueryOperationOutputBindings { ActorQueryOperation.validateQueryOutput(output, 'bindings'); return <IActorQueryOperationOutputBindings> output; } /** * Safely cast a query operation output to a quads output. * This will throw a runtime error if the output is of the incorrect type. * @param {IActorQueryOperationOutput} output A query operation output. * @return {IActorQueryOperationOutputQuads} A quads query operation output. */ public static getSafeQuads(output: IActorQueryOperationOutput): IActorQueryOperationOutputQuads { ActorQueryOperation.validateQueryOutput(output, 'quads'); return <IActorQueryOperationOutputQuads> output; } /** * Safely cast a query operation output to a boolean output. * This will throw a runtime error if the output is of the incorrect type. * @param {IActorQueryOperationOutput} output A query operation output. * @return {IActorQueryOperationOutputBoolean} A boolean query operation output. */ public static getSafeBoolean(output: IActorQueryOperationOutput): IActorQueryOperationOutputBoolean { ActorQueryOperation.validateQueryOutput(output, 'boolean'); return <IActorQueryOperationOutputBoolean> output; } /** * Safely cast a query operation output to an update output. * This will throw a runtime error if the output is of the incorrect type. * @param {IActorQueryOperationOutput} output A query operation output. * @return {IActorQueryOperationOutputUpdate} An update query operation output. */ public static getSafeUpdate(output: IActorQueryOperationOutput): IActorQueryOperationOutputUpdate { ActorQueryOperation.validateQueryOutput(output, 'update'); return <IActorQueryOperationOutputUpdate> output; } /** * Convert a metadata callback to a lazy callback where the response value is cached. * @param {() => Promise<{[p: string]: any}>} metadata A metadata callback * @return {() => Promise<{[p: string]: any}>} The callback where the response will be cached. */ public static cachifyMetadata<T extends (() => Promise<Record<string, any>>) | (undefined | (() => Promise<Record<string, any>>))>(metadata: T): T { let lastReturn: Promise<Record<string, any>>; // eslint-disable-next-line no-return-assign,@typescript-eslint/no-misused-promises return <T> (metadata && (() => (lastReturn || (lastReturn = metadata())))); } /** * Throw an error if the output type does not match the expected type. * @param {IActorQueryOperationOutput} output A query operation output. * @param {string} expectedType The expected output type. */ public static validateQueryOutput(output: IActorQueryOperationOutput, expectedType: string): void { if (output.type !== expectedType) { throw new Error(`Invalid query output type: Expected '${expectedType}' but got '${output.type}'`); } } protected static getBaseExpressionContext(context: ActionContext): IBaseExpressionContext { if (context) { const now: Date = context.get(KeysInitSparql.queryTimestamp); const baseIRI: string = context.get(KeysInitSparql.baseIRI); // Handle two variants of providing extension functions if (context.has(KeysInitSparql.extensionFunctionCreator) && context.has(KeysInitSparql.extensionFunctions)) { throw new Error('Illegal simultaneous usage of extensionFunctionCreator and extensionFunctions in context'); } let extensionFunctionCreator: (functionNamedNode: RDF.NamedNode) => ((args: RDF.Term[]) => Promise<RDF.Term>) | undefined = context.get(KeysInitSparql.extensionFunctionCreator); // Convert dictionary-based variant to callback const extensionFunctions: Record<string, (args: RDF.Term[]) => Promise<RDF.Term>> = context .get(KeysInitSparql.extensionFunctions); if (extensionFunctions) { extensionFunctionCreator = functionNamedNode => extensionFunctions[functionNamedNode.value]; } return { now, baseIRI, extensionFunctionCreator }; } return {}; } /** * Create an options object that can be used to construct a sparqlee synchronous evaluator. * @param context An action context. * @param mediatorQueryOperation An optional query query operation mediator. * If defined, the existence resolver will be defined as `exists`. */ public static getExpressionContext(context: ActionContext, mediatorQueryOperation?: Mediator< Actor<IActionQueryOperation, IActorTest, IActorQueryOperationOutput>, IActionQueryOperation, IActorTest, IActorQueryOperationOutput>): IExpressionContext { return { ...this.getBaseExpressionContext(context), bnode: (input?: string) => new BlankNodeBindingsScoped(input || `BNODE_${bnodeCounter++}`), }; } /** * Create an options object that can be used to construct a sparqlee asynchronous evaluator. * @param context An action context. * @param mediatorQueryOperation An optional query query operation mediator. * If defined, the existence resolver will be defined as `exists`. */ public static getAsyncExpressionContext(context: ActionContext, mediatorQueryOperation?: Mediator< Actor<IActionQueryOperation, IActorTest, IActorQueryOperationOutput>, IActionQueryOperation, IActorTest, IActorQueryOperationOutput>): IAsyncExpressionContext { const expressionContext: IAsyncExpressionContext = { ...this.getBaseExpressionContext(context), bnode: (input?: string) => Promise.resolve(new BlankNodeBindingsScoped(input || `BNODE_${bnodeCounter++}`)), }; if (context && mediatorQueryOperation) { expressionContext.exists = ActorQueryOperation.createExistenceResolver(context, mediatorQueryOperation); } return expressionContext; } /** * Create an existence resolver for usage within an expression context. * @param context An action context. * @param mediatorQueryOperation A query operation mediator. */ public static createExistenceResolver(context: ActionContext, mediatorQueryOperation: Mediator< Actor<IActionQueryOperation, IActorTest, IActorQueryOperationOutput>, IActionQueryOperation, IActorTest, IActorQueryOperationOutput>): (expr: Algebra.ExistenceExpression, bindings: Bindings) => Promise<boolean> { return async(expr, bindings) => { const operation = materializeOperation(expr.input, bindings); const outputRaw = await mediatorQueryOperation.mediate({ operation, context }); const output = ActorQueryOperation.getSafeBindings(outputRaw); return new Promise( (resolve, reject) => { output.bindingsStream.on('end', () => { resolve(false); }); output.bindingsStream.on('error', reject); output.bindingsStream.on('data', () => { output.bindingsStream.close(); resolve(true); }); }, ) .then((exists: boolean) => expr.not ? !exists : exists); }; } /** * Throw an error if the context contains the readOnly flag. * @param context An action context. */ public static throwOnReadOnly(context?: ActionContext): void { if (context && context.get(KEY_CONTEXT_READONLY)) { throw new Error(`Attempted a write operation in read-only mode`); } } } /** * Helper function to get the metadata of an action output. * @param actionOutput An action output, with an optional metadata function. * @return The metadata. */ export function getMetadata(actionOutput: IActorQueryOperationOutputStream): Promise<Record<string, any>> { if (!actionOutput.metadata) { return Promise.resolve({}); } return actionOutput.metadata(); } interface IBaseExpressionContext { now?: Date; baseIRI?: string; extensionFunctionCreator?: (functionNamedNode: RDF.NamedNode) => ((args: RDF.Term[]) => Promise<RDF.Term>) | undefined; } // TODO: rename to ISyncExpressionContext in next major version export interface IExpressionContext extends IBaseExpressionContext { bnode: (input?: string | undefined) => RDF.BlankNode; } export interface IAsyncExpressionContext extends IBaseExpressionContext { bnode: (input?: string | undefined) => Promise<RDF.BlankNode>; exists?: (expr: Algebra.ExistenceExpression, bindings: Bindings) => Promise<boolean>; }
the_stack
import {get as getBrowserGlobals} from 'app/client/lib/browserGlobals'; import {reportError} from 'app/client/models/AppModel'; import {BillingModel} from 'app/client/models/BillingModel'; import * as css from 'app/client/ui/BillingPageCss'; import {colors, vars} from 'app/client/ui2018/cssVars'; import {IOption, select} from 'app/client/ui2018/menus'; import {IBillingAddress, IBillingCard, IBillingCoupon, IBillingOrgSettings, IFilledBillingAddress} from 'app/common/BillingAPI'; import {checkSubdomainValidity} from 'app/common/orgNameUtils'; import * as roles from 'app/common/roles'; import {Organization} from 'app/common/UserAPI'; import {Computed, Disposable, dom, DomArg, IDisposableOwnerT, makeTestId, Observable, styled} from 'grainjs'; import sortBy = require('lodash/sortBy'); const G = getBrowserGlobals('Stripe', 'window'); const testId = makeTestId('test-bp-'); const states = [ 'AK', 'AL', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR', 'PW', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY' ]; export interface IFormData { address?: IFilledBillingAddress; card?: IBillingCard; token?: string; settings?: IBillingOrgSettings; coupon?: IBillingCoupon; } // Optional autofill vales to pass in to the BillingForm constructor. interface IAutofill { address?: Partial<IBillingAddress>; settings?: Partial<IBillingOrgSettings>; // Note that the card name is the only value that may be initialized, since the other card // information is sensitive. card?: Partial<IBillingCard>; coupon?: Partial<IBillingCoupon>; } // An object containing a function to check the validity of its observable value. // The get function should return the observable value or throw an error if it is invalid. interface IValidated<T> { value: Observable<T>; checkValidity: (value: T) => void|Promise<void>; // Should throw with message on invalid values. isInvalid: Observable<boolean>; get: () => T|Promise<T>; } export class BillingForm extends Disposable { private readonly _address: BillingAddressForm|null; private readonly _discount: BillingDiscountForm|null; private readonly _payment: BillingPaymentForm|null; private readonly _settings: BillingSettingsForm|null; constructor( org: Organization|null, billingModel: BillingModel, options: {payment: boolean, address: boolean, settings: boolean, domain: boolean, discount: boolean}, autofill: IAutofill = {} ) { super(); // Get the number of forms - if more than one is present subheaders should be visible. const count = [options.settings, options.address, options.payment] .reduce((acc, x) => acc + (x ? 1 : 0), 0); // Org settings form. this._settings = options.settings ? new BillingSettingsForm(billingModel, org, { showHeader: count > 1, showDomain: options.domain, autofill: autofill.settings }) : null; // Discount form. this._discount = options.discount ? new BillingDiscountForm(billingModel, { autofill: autofill.coupon }) : null; // Address form. this._address = options.address ? new BillingAddressForm({ showHeader: count > 1, autofill: autofill.address }) : null; // Payment form. this._payment = options.payment ? new BillingPaymentForm({ showHeader: count > 1, autofill: autofill.card }) : null; } public buildDom() { return [ this._settings ? this._settings.buildDom() : null, this._discount ? this._discount.buildDom() : null, this._address ? this._address.buildDom() : null, this._payment ? this._payment.buildDom() : null ]; } // Note that this will throw if any values are invalid. public async getFormData(): Promise<IFormData> { const settings = this._settings ? await this._settings.getSettings() : undefined; const address = this._address ? await this._address.getAddress() : undefined; const cardInfo = this._payment ? await this._payment.getCardAndToken() : undefined; const coupon = this._discount ? await this._discount.getCoupon() : undefined; return { settings, address, coupon, token: cardInfo ? cardInfo.token : undefined, card: cardInfo ? cardInfo.card : undefined }; } } // Abstract class which includes helper functions for creating a form whose values are verified. abstract class BillingSubForm extends Disposable { protected readonly formError: Observable<string> = Observable.create(this, ''); constructor() { super(); } // Creates an input whose value is validated on blur. Input text turns red and the validation // error is shown on negative validation. protected billingInput(validated: IValidated<string>, ...args: Array<DomArg<any>>) { return css.billingInput(validated.value, {onInput: true}, css.billingInput.cls('-invalid', validated.isInvalid), dom.on('blur', () => this._onBlur(validated)), ...args ); } protected async _onBlur(validated: IValidated<string>): Promise<void> { // Do not show empty input errors on blur. if (validated.value.get().length === 0) { return; } try { await validated.get(); this.formError.set(''); } catch (e) { this.formError.set(e.message); } } } /** * Creates the payment card entry form using Stripe Elements. */ class BillingPaymentForm extends BillingSubForm { private readonly _stripe: any; private readonly _elements: any; // Stripe Element fields. Set when the elements are mounted to the dom. private readonly _numberElement: Observable<any> = Observable.create(this, null); private readonly _expiryElement: Observable<any> = Observable.create(this, null); private readonly _cvcElement: Observable<any> = Observable.create(this, null); private readonly _name: IValidated<string> = createValidated(this, checkRequired('Name')); constructor(private readonly _options: { showHeader: boolean; autofill?: Partial<IBillingCard>; }) { super(); const autofill = this._options.autofill; const stripeAPIKey = G.window.gristConfig.stripeAPIKey; try { this._stripe = G.Stripe(stripeAPIKey); this._elements = this._stripe.elements(); } catch (err) { reportError(err); } if (autofill) { this._name.value.set(autofill.name || ''); } } public buildDom() { return this._stripe ? css.paymentBlock( this._options.showHeader ? css.paymentSubHeader('Payment Method') : null, css.paymentRow( css.paymentField( css.paymentLabel('Cardholder Name'), this.billingInput(this._name, testId('card-name')), ) ), css.paymentRow( css.paymentField( css.paymentLabel({for: 'number-element'}, 'Card Number'), css.stripeInput({id: 'number-element'}), // A Stripe Element will be inserted here. testId('card-number') ) ), css.paymentRow( css.paymentField( css.paymentLabel({for: 'expiry-element'}, 'Expiry Date'), css.stripeInput({id: 'expiry-element'}), // A Stripe Element will be inserted here. testId('card-expiry') ), css.paymentSpacer(), css.paymentField( css.paymentLabel({for: 'cvc-element'}, 'CVC / CVV Code'), css.stripeInput({id: 'cvc-element'}), // A Stripe Element will be inserted here. testId('card-cvc') ) ), css.inputError( dom.text(this.formError), testId('payment-form-error') ), () => { setTimeout(() => this._mountStripeUI(), 0); } ) : null; } public async getCardAndToken(): Promise<{card: IBillingCard, token: string}> { // Note that we call createToken using only the card number element as the first argument // in accordance with the Stripe API: // // "If applicable, the Element pulls data from other Elements you’ve created on the same // instance of elements to tokenize—you only need to supply one element as the parameter." // // Source: https://stripe.com/docs/stripe-js/reference#stripe-create-token try { const result = await this._stripe.createToken(this._numberElement.get(), {name: await this._name.get()}); if (result.error) { throw new Error(result.error.message); } return { card: result.token.card, token: result.token.id }; } catch (e) { this.formError.set(e.message); throw e; } } private _mountStripeUI() { // Mount Stripe Element fields. this._mountStripeElement(this._numberElement, 'cardNumber', 'number-element'); this._mountStripeElement(this._expiryElement, 'cardExpiry', 'expiry-element'); this._mountStripeElement(this._cvcElement, 'cardCvc', 'cvc-element'); } private _mountStripeElement(elemObs: Observable<any>, stripeName: string, elementId: string): void { // For details on applying custom styles to Stripe Elements, see: // https://stripe.com/docs/stripe-js/reference#element-options const classes = {base: css.stripeInput.className}; const style = { base: { '::placeholder': { color: colors.slate.value }, 'fontSize': vars.mediumFontSize.value, 'fontFamily': vars.fontFamily.value } }; if (!elemObs.get()) { const stripeInst = this._elements.create(stripeName, {classes, style}); stripeInst.addEventListener('change', (event: any) => { if (event.error) { this.formError.set(event.error.message); } }); elemObs.set(stripeInst); } elemObs.get().mount(`#${elementId}`); } } /** * Creates the company address entry form. Used by BillingPaymentForm when billing address is needed. */ class BillingAddressForm extends BillingSubForm { private readonly _address1: IValidated<string> = createValidated(this, checkRequired('Address')); private readonly _address2: IValidated<string> = createValidated(this, () => undefined); private readonly _city: IValidated<string> = createValidated(this, checkRequired('City')); private readonly _state: IValidated<string> = createValidated(this, checkFunc( (val) => !this._isUS.get() || Boolean(val), `State is required.`)); private readonly _postal: IValidated<string> = createValidated(this, checkFunc( (val) => !this._isUS.get() || Boolean(val), 'Zip code is required.')); private readonly _countryCode: IValidated<string> = createValidated(this, checkRequired('Country')); private _isUS = Computed.create(this, this._countryCode.value, (use, code) => (code === 'US')); private readonly _countries: Array<IOption<string>> = getCountries(); constructor(private readonly _options: { showHeader: boolean; autofill?: Partial<IBillingAddress>; }) { super(); const autofill = this._options.autofill; if (autofill) { this._address1.value.set(autofill.line1 || ''); this._address2.value.set(autofill.line2 || ''); this._city.value.set(autofill.city || ''); this._state.value.set(autofill.state || ''); this._postal.value.set(autofill.postal_code || ''); } this._countryCode.value.set(autofill?.country || 'US'); } public buildDom() { return css.paymentBlock( this._options.showHeader ? css.paymentSubHeader('Company Address') : null, css.paymentRow( css.paymentField( css.paymentLabel('Street Address'), this.billingInput(this._address1, testId('address-street')) ) ), css.paymentRow( css.paymentField( css.paymentLabel('Suite / Unit'), this.billingInput(this._address2, testId('address-suite')) ) ), css.paymentRow( css.paymentField( css.paymentLabel('City'), this.billingInput(this._city, testId('address-city')) ), css.paymentSpacer(), css.paymentField({style: 'flex: 0.5 1 0;'}, dom.domComputed(this._isUS, (isUs) => isUs ? [ css.paymentLabel('State'), cssSelect(this._state.value, states), ] : [ css.paymentLabel('State / Region'), this.billingInput(this._state), ] ), testId('address-state') ) ), css.paymentRow( css.paymentField( css.paymentLabel(dom.text((use) => use(this._isUS) ? 'Zip Code' : 'Postal Code')), this.billingInput(this._postal, testId('address-zip')) ) ), css.paymentRow( css.paymentField( css.paymentLabel('Country'), cssSelect(this._countryCode.value, this._countries), testId('address-country') ) ), css.inputError( dom.text(this.formError), testId('address-form-error') ) ); } // Throws if any value is invalid. Returns a customer address as accepted by the customer // object in stripe. // For reference: https://stripe.com/docs/api/customers/object#customer_object-address public async getAddress(): Promise<IFilledBillingAddress|undefined> { try { return { line1: await this._address1.get(), line2: await this._address2.get(), city: await this._city.get(), state: await this._state.get(), postal_code: await this._postal.get(), country: await this._countryCode.get(), }; } catch (e) { this.formError.set(e.message); throw e; } } } /** * Creates the billing settings form, including the org name and the org subdomain values. */ class BillingSettingsForm extends BillingSubForm { private readonly _name: IValidated<string> = createValidated(this, checkRequired('Company name')); // Only verify the domain if it is shown. private readonly _domain: IValidated<string> = createValidated(this, this._options.showDomain ? d => this._verifyDomain(d) : () => undefined); constructor( private readonly _billingModel: BillingModel, private readonly _org: Organization|null, private readonly _options: { showHeader: boolean; showDomain: boolean; autofill?: Partial<IBillingOrgSettings>; } ) { super(); const autofill = this._options.autofill; if (autofill) { this._name.value.set(autofill.name || ''); this._domain.value.set(autofill.domain || ''); } } public buildDom() { const noEditAccess = Boolean(this._org && !roles.canEdit(this._org.access)); const hasDomain = Boolean(this._options.autofill?.domain); return css.paymentBlock( this._options.showHeader ? css.paymentSubHeader('Team Site') : null, css.paymentRow( css.paymentField( this.billingInput(this._name, dom.boolAttr('disabled', () => noEditAccess), testId('settings-name') ), noEditAccess ? css.paymentFieldInfo('Organization edit access is required', testId('settings-name-info') ) : null ) ), this._options.showDomain ? css.paymentRow( css.paymentField( css.paymentLabel('URL'), this.billingInput(this._domain, dom.boolAttr('disabled', () => noEditAccess), testId('settings-domain') ), noEditAccess ? css.paymentFieldInfo('Organization edit access is required', testId('settings-domain-info') ) : null, hasDomain ? css.paymentFieldDanger('Any saved links will need updating if the URL changes') : null, ), css.paymentField({style: 'flex: 0 1 0;'}, css.inputHintLabel('.getgrist.com') ) ) : null, css.inputError( dom.text(this.formError), testId('settings-form-error') ) ); } // Throws if any value is invalid. public async getSettings(): Promise<IBillingOrgSettings|undefined> { try { return { name: await this._name.get(), domain: await this._domain.get() }; } catch (e) { this.formError.set(e.message); throw e; } } // Throws if the entered domain contains any invalid characters or is already taken. private async _verifyDomain(domain: string): Promise<void> { // OK to retain current domain. if (domain === this._options.autofill?.domain) { return; } checkSubdomainValidity(domain); const isAvailable = await this._billingModel.isDomainAvailable(domain); if (!isAvailable) { throw new Error('Domain is already taken.'); } } } /** * Creates the billing discount form. */ class BillingDiscountForm extends BillingSubForm { private _isExpanded = Observable.create(this, false); private readonly _discountCode: IValidated<string> = createValidated(this, () => undefined); constructor( private readonly _billingModel: BillingModel, private readonly _options: { autofill?: Partial<IBillingCoupon>; } ) { super(); if (this._options.autofill) { const { promotion_code } = this._options.autofill; this._discountCode.value.set(promotion_code ?? ''); this._isExpanded.set(Boolean(promotion_code)); } } public buildDom() { return dom.domComputed(this._isExpanded, isExpanded => [ !isExpanded ? css.paymentBlock( css.paymentRow( css.billingText('Have a discount code?', testId('discount-code-question')), css.billingTextBtn( css.billingIcon('Settings'), 'Apply', dom.on('click', () => this._isExpanded.set(true)), testId('apply-discount-code') ) ) ) : css.paymentBlock( css.paymentRow( css.paymentField( css.paymentLabel('Discount Code'), this.billingInput(this._discountCode, testId('discount-code')), ) ), css.inputError( dom.text(this.formError), testId('discount-form-error') ) ) ]); } public async getCoupon() { const discountCode = await this._discountCode.get(); if (discountCode.trim() === '') { return undefined; } try { return await this._billingModel.fetchSignupCoupon(discountCode); } catch (e) { this.formError.set('Invalid or expired discount code.'); throw e; } } } function checkFunc(func: (val: string) => boolean, message: string) { return (val: string) => { if (!func(val)) { throw new Error(message); } }; } function checkRequired(propertyName: string) { return checkFunc(Boolean, `${propertyName} is required.`); } // Creates a validated object, which includes an observable and a function to check // if the current observable value is valid. function createValidated( owner: IDisposableOwnerT<any>, checkValidity: (value: string) => void|Promise<void>, ): IValidated<string> { const value = Observable.create(owner, ''); const isInvalid = Observable.create<boolean>(owner, false); owner.autoDispose(value.addListener(() => { isInvalid.set(false); })); return { value, isInvalid, checkValidity, get: async () => { const _value = value.get(); try { await checkValidity(_value); } catch (e) { isInvalid.set(true); throw e; } isInvalid.set(false); return _value; } }; } function getCountries(): Array<IOption<string>> { // Require just the one file because it has all the data we need and is substantially smaller // than requiring the whole module. const countryNames = require("i18n-iso-countries/langs/en.json").countries; const codes = Object.keys(countryNames); const entries = codes.map(code => { // The module provides names that are either a string or an array of names. If an array, pick // the first one. const names = countryNames[code]; return {value: code, label: Array.isArray(names) ? names[0] : names}; }); return sortBy(entries, 'label'); } const cssSelect = styled(select, ` height: 42px; padding-left: 13px; align-items: center; `);
the_stack
import produce from 'immer'; import { createSelector } from 'reselect'; import get from 'lodash.get'; import { sortDifficultyIds } from '../helpers/song.helpers'; import { DEFAULT_RED, DEFAULT_BLUE } from '../helpers/colors.helpers'; import { DEFAULT_GRID, DEFAULT_COL_WIDTH, DEFAULT_ROW_HEIGHT, } from '../helpers/grid.helpers'; import { isEmpty } from '../utils'; interface Difficulty { id: string; noteJumpSpeed: number; startBeatOffset: number; customLabel?: string; } interface ModSettings { mappingExtensions: { isEnabled: boolean; numRows: number; numCols: number; colWidth: number; rowHeight: number; }; customColors: { isEnabled: boolean; colorLeft: string; colorLeftOverdrive: number; colorRight: string; colorRightOverdrive: number; envColorLeft: string; envColorLeftOverdrive: number; envColorRight: string; envColorRightOverdrive: number; obstacleColor: string; obstacleColorOverdrive: number; }; } interface Song { id: string; name: string; subName?: string; artistName: string; mapAuthorName?: string; bpm: number; offset: number; swingAmount?: number; swingPeriod?: number; previewStartTime: number; previewDuration: number; environment: | 'DefaultEnvironment' | 'BigMirrorEnvironment' | 'TriangleEnvironment' | 'NiceEnvironment' | 'DragonsEnvironment'; songFilename: string; coverArtFilename: string; difficultiesById: { [key: string]: Difficulty }; selectedDifficulty?: Difficulty; createdAt: number; lastOpenedAt: number; demo?: boolean; modSettings: ModSettings; enabledFastWalls?: boolean; enabledLightshow?: boolean; } interface State { byId: { [key: string]: Song }; selectedId: string | null; processingImport: boolean; } const initialState = { byId: {}, selectedId: null, processingImport: false, }; const DEFAULT_NOTE_JUMP_SPEEDS = { Easy: 10, Normal: 10, Hard: 12, Expert: 15, ExpertPlus: 18, }; const DEFAULT_MOD_SETTINGS = { customColors: { isEnabled: false, colorLeft: DEFAULT_RED, colorLeftOverdrive: 0, colorRight: DEFAULT_BLUE, colorRightOverdrive: 0, envColorLeft: DEFAULT_RED, envColorLeftOverdrive: 0, envColorRight: DEFAULT_BLUE, envColorRightOverdrive: 0, obstacleColor: DEFAULT_RED, obstacleColorOverdrive: 0, }, mappingExtensions: { isEnabled: false, ...DEFAULT_GRID, }, }; export default function songsReducer(state: State = initialState, action: any) { switch (action.type) { case 'START_LOADING_SONG': { const { songId, difficulty } = action; return produce(state, (draftState: State) => { draftState.selectedId = songId; draftState.byId[songId].selectedDifficulty = difficulty; }); } case 'FINISH_LOADING_SONG': { const { song, lastOpenedAt } = action; return produce(state, (draftState: State) => { const draftSong = draftState.byId[song.id]; draftSong.lastOpenedAt = lastOpenedAt; draftSong.modSettings = draftSong.modSettings || {}; }); } case 'LEAVE_EDITOR': { return { ...state, selectedId: null, }; } case 'START_IMPORTING_SONG': { return { ...state, processingImport: true, }; } case 'CANCEL_IMPORTING_SONG': { return { ...state, processingImport: false, }; } case 'CREATE_NEW_SONG': { const { coverArtFilename, songFilename, songId, name, subName, artistName, bpm, offset, selectedDifficulty, mapAuthorName, createdAt, lastOpenedAt, } = action; return produce(state, (draftState: State) => { draftState.selectedId = songId; draftState.byId[songId] = { id: songId, name, subName, artistName, bpm, offset, previewStartTime: 12, previewDuration: 10, songFilename, coverArtFilename, environment: 'DefaultEnvironment', mapAuthorName, createdAt, lastOpenedAt, selectedDifficulty, difficultiesById: { [selectedDifficulty]: { id: selectedDifficulty, // @ts-ignore noteJumpSpeed: DEFAULT_NOTE_JUMP_SPEEDS[selectedDifficulty], startBeatOffset: 0, customLabel: '', }, }, modSettings: DEFAULT_MOD_SETTINGS, }; }); } case 'IMPORT_EXISTING_SONG': { const { createdAt, lastOpenedAt, songData: { songId, songFilename, coverArtFilename, name, subName, artistName, mapAuthorName, bpm, offset, swingAmount, swingPeriod, previewStartTime, previewDuration, environment, difficultiesById, demo, modSettings = {}, enabledFastWalls = false, enabledLightshow = false, }, } = action; // @ts-ignore const selectedDifficulty: Difficulty = Object.keys(difficultiesById)[0]; return produce(state, (draftState: State) => { draftState.processingImport = false; draftState.byId[songId] = { id: songId, name, subName, artistName, mapAuthorName, bpm, offset, swingAmount, swingPeriod, previewStartTime, previewDuration, songFilename, coverArtFilename, environment, selectedDifficulty, difficultiesById, createdAt, lastOpenedAt, demo, modSettings, enabledFastWalls, enabledLightshow, }; }); } case 'UPDATE_SONG_DETAILS': { const { type, songId, ...fieldsToUpdate } = action; return produce(state, (draftState: State) => { draftState.byId[songId] = { ...draftState.byId[songId], ...fieldsToUpdate, }; }); } case 'CREATE_DIFFICULTY': { const { difficulty } = action; return produce(state, (draftState: State) => { const selectedSongId = state.selectedId; if (!selectedSongId) { return state; } const song = draftState.byId[selectedSongId]; song.selectedDifficulty = difficulty; song.difficultiesById[difficulty] = { id: difficulty, // @ts-ignore noteJumpSpeed: DEFAULT_NOTE_JUMP_SPEEDS[difficulty], startBeatOffset: 0, customLabel: '', }; }); } case 'COPY_DIFFICULTY': { const { songId, fromDifficultyId, toDifficultyId } = action; return produce(state, (draftState: State) => { const song = draftState.byId[songId]; const newDifficultyObj = { ...song.difficultiesById[fromDifficultyId], id: toDifficultyId, }; song.selectedDifficulty = toDifficultyId; song.difficultiesById[toDifficultyId] = newDifficultyObj; }); } case 'CHANGE_SELECTED_DIFFICULTY': { const { songId, difficulty } = action; return produce(state, (draftState: State) => { const song = draftState.byId[songId]; song.selectedDifficulty = difficulty; }); } case 'DELETE_BEATMAP': { const { songId, difficulty } = action; return produce(state, (draftState: State) => { delete draftState.byId[songId].difficultiesById[difficulty]; }); } case 'UPDATE_BEATMAP_METADATA': { const { songId, difficulty, noteJumpSpeed, startBeatOffset, customLabel, } = action; return produce(state, (draftState: State) => { const currentBeatmapDifficulty = draftState.byId[songId].difficultiesById[difficulty]; currentBeatmapDifficulty.noteJumpSpeed = noteJumpSpeed; currentBeatmapDifficulty.startBeatOffset = startBeatOffset; currentBeatmapDifficulty.customLabel = customLabel; }); } case 'DELETE_SONG': { const { songId } = action; return produce(state, (draftState: State) => { delete draftState.byId[songId]; }); } case 'TOGGLE_MOD_FOR_SONG': { const { mod } = action; return produce(state, (draftState: any) => { // Should-be-impossible edge-case where no selected song exists if (!draftState.selectedId || !draftState.byId[draftState.selectedId]) { return; } const song = draftState.byId[draftState.selectedId]; // For a brief moment, modSettings was being set to an empty object, // before the children were required. Update that now, if so. if (!song.modSettings || isEmpty(song.modSettings)) { song.modSettings = DEFAULT_MOD_SETTINGS; } // Also for a brief moment, modSettings didn't always have properties // for each mod if (!song.modSettings[mod]) { // @ts-ignore song.modSettings[mod] = DEFAULT_MOD_SETTINGS[mod]; } const isModEnabled = get(song, `modSettings.${mod}.isEnabled`); song.modSettings[mod].isEnabled = !isModEnabled; }); } case 'UPDATE_MOD_COLOR': { const { element, color } = action; return produce(state, (draftState: State) => { const song = grabSelectedSong(draftState); if (!song) { return; } if (!song.modSettings.customColors) { song.modSettings.customColors = DEFAULT_MOD_SETTINGS.customColors; } // @ts-ignore song.modSettings.customColors[element] = color; }); } case 'UPDATE_MOD_COLOR_OVERDRIVE': { const { element, overdrive } = action; const elementOverdriveKey = `${element}Overdrive`; return produce(state, (draftState: State) => { const song = grabSelectedSong(draftState); if (!song) { return; } if (!song.modSettings.customColors) { song.modSettings.customColors = DEFAULT_MOD_SETTINGS.customColors; } // @ts-ignore song.modSettings.customColors[elementOverdriveKey] = overdrive; }); } case 'UPDATE_GRID': { const { numRows, numCols, colWidth, rowHeight } = action; return produce(state, (draftState: State) => { const song = grabSelectedSong(draftState); if (!song) { return; } if (!song.modSettings || !song.modSettings.mappingExtensions) { song.modSettings.mappingExtensions = DEFAULT_MOD_SETTINGS.mappingExtensions; } song.modSettings.mappingExtensions.numRows = numRows; song.modSettings.mappingExtensions.numCols = numCols; song.modSettings.mappingExtensions.colWidth = colWidth; song.modSettings.mappingExtensions.rowHeight = rowHeight; }); } case 'RESET_GRID': { return produce(state, (draftState: State) => { const song = grabSelectedSong(draftState); if (!song) { return; } song.modSettings.mappingExtensions = { ...song.modSettings.mappingExtensions, ...DEFAULT_GRID, }; }); } case 'LOAD_GRID_PRESET': { const { grid } = action; return produce(state, (draftState: State) => { const song = grabSelectedSong(draftState); if (!song) { return; } song.modSettings.mappingExtensions = { ...song.modSettings.mappingExtensions, ...grid, }; }); } case 'TOGGLE_PROPERTY_FOR_SELECTED_SONG': { const { property } = action; return produce(state, (draftState: State) => { const song = grabSelectedSong(draftState); if (!song) { return; } // @ts-ignore song[property] = !song[property]; }); } default: return state; } } // // //// HELPERS // const grabSelectedSong = (state: State) => { if (!state.selectedId) { return undefined; } return state.byId[state.selectedId]; }; // // //// SELECTORS // const getById = (state: any) => state.songs.byId; export const getAllSongs = (state: any): Array<Song> => { return Object.values(getById(state)); }; export const getAllSongIds = (state: any) => { return Object.keys(getById(state)); }; export const getAllSongsChronologically = (state: any) => { return getAllSongs(state).sort((a: Song, b: Song) => { return a.lastOpenedAt > b.lastOpenedAt ? -1 : 1; }); }; export const getProcessingImport = (state: any) => state.songs.processingImport; export const getSongById = (state: any, songId: string) => { const byId = getById(state); return byId[songId]; }; export const getSelectedSongId = (state: any) => { return state.songs.selectedId; }; export const getSelectedSong = (state: any) => { const byId = getById(state); return byId[getSelectedSongId(state)]; }; export const getSelectedSongDifficultyIds = createSelector( getSelectedSong, (selectedSong: any) => { /** * This selector comes with the added bonus that difficulties are sorted * (easy to expert+) */ const ids = Object.keys(selectedSong.difficultiesById); // @ts-ignore return sortDifficultyIds(ids); } ); export const getDemoSong = (state: any) => { return getAllSongs(state).find(song => song.demo); }; export const getGridSize = (state: any) => { const song = getSelectedSong(state); const mappingExtensions = get(song, 'modSettings.mappingExtensions'); // In legacy states, `mappingExtensions` was a boolean, and it was possible // to not have the key at all. // Also, if the user has set a custom grid but then disabled the extension, // we should const isLegacy = typeof mappingExtensions === 'boolean' || !mappingExtensions; const isDisabled = get(mappingExtensions, 'isEnabled') === false; if (isLegacy || isDisabled) { return DEFAULT_GRID; } return { numRows: mappingExtensions.numRows, numCols: mappingExtensions.numCols, colWidth: mappingExtensions.colWidth || DEFAULT_COL_WIDTH, rowHeight: mappingExtensions.rowHeight || DEFAULT_ROW_HEIGHT, }; }; type EnabledMods = { mappingExtensions: boolean; customColors: boolean; }; export const getEnabledMods = createSelector( getSelectedSong, (song): EnabledMods => { return { mappingExtensions: !!get(song, 'modSettings.mappingExtensions.isEnabled'), customColors: !!get(song, 'modSettings.customColors.isEnabled'), }; } ); export const getEnabledFastWalls = createSelector( getSelectedSong, song => { return song.enabledFastWalls; } ); export const getEnabledLightshow = createSelector( getSelectedSong, song => { return song.enabledLightshow; } ); export const getCustomColors = createSelector( getSelectedSong, song => { let colors = song.modSettings.customColors; if (!colors) { return DEFAULT_MOD_SETTINGS.customColors; } return { ...DEFAULT_MOD_SETTINGS.customColors, ...colors, }; } ); export const getMappingMode = createSelector( getEnabledMods, enabledMods => { return enabledMods.mappingExtensions ? 'mapping-extensions' : 'original'; } );
the_stack
'use strict'; import * as vscode from 'vscode'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as ini from 'ini'; import { FactorioModDebugSession } from './factorioModDebug'; import { validateLocale, LocaleColorProvider, LocaleDocumentSymbolProvider, LocaleCodeActionProvider } from './LocaleLangProvider'; import { ChangelogCodeActionProvider, validateChangelogTxt, ChangelogDocumentSymbolProvider } from './ChangeLogLangProvider'; import { ModsTreeDataProvider } from './ModPackageProvider'; import { ApiDocGenerator } from './apidocs/ApiDocGenerator'; let diagnosticCollection: vscode.DiagnosticCollection; export function activate(context: vscode.ExtensionContext) { const provider = new FactorioModConfigurationProvider(); context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('factoriomod', provider)); // debug adapters can be run in different ways by using a vscode.DebugAdapterDescriptorFactory: const factory = new InlineDebugAdapterFactory(context); context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory('factoriomod', factory)); context.subscriptions.push(factory); diagnosticCollection = vscode.languages.createDiagnosticCollection('factorio'); context.subscriptions.push(diagnosticCollection); context.subscriptions.push( vscode.languages.registerCodeActionsProvider({ scheme: 'file', language: 'factorio-changelog' }, new ChangelogCodeActionProvider())); vscode.workspace.findFiles("**/changelog.txt").then(uris => { // check diagnostics uris.forEach(async uri=> diagnosticCollection.set(uri, await validateChangelogTxt(uri))); }); context.subscriptions.push( vscode.languages.registerCodeActionsProvider({ scheme: 'file', language: 'factorio-locale' }, new LocaleCodeActionProvider())); vscode.workspace.findFiles("**/locale/*/*.cfg").then(uris => { // check diagnostics uris.forEach(async uri=> diagnosticCollection.set(uri, await validateLocale(uri))); }); vscode.workspace.onDidChangeTextDocument(async change =>{ if (change.document.languageId === "factorio-changelog") { // if it's changelog.txt, recheck diagnostics... diagnosticCollection.set(change.document.uri, await validateChangelogTxt(change.document)); } else if (change.document.languageId === "factorio-locale") { // if it's changelog.txt, recheck diagnostics... diagnosticCollection.set(change.document.uri, await validateLocale(change.document)); } }); vscode.workspace.onDidDeleteFiles(deleted => { deleted.files.forEach(uri=>{diagnosticCollection.set(uri, undefined);}); }); context.subscriptions.push( vscode.languages.registerDocumentSymbolProvider( {scheme:"file", language:"factorio-changelog"}, new ChangelogDocumentSymbolProvider())); context.subscriptions.push( vscode.languages.registerColorProvider( {scheme:"file", language:"factorio-locale"}, new LocaleColorProvider())); context.subscriptions.push( vscode.languages.registerDocumentSymbolProvider( {scheme:"file", language:"factorio-locale"}, new LocaleDocumentSymbolProvider())); context.subscriptions.push( vscode.commands.registerCommand("factorio.makedocs",async () => { const file = await vscode.window.showOpenDialog({filters:{ "JSON Docs":["json"] } }); if (!file) {return;} const docjson = Buffer.from(await vscode.workspace.fs.readFile(file[0])).toString("utf8"); const gen = new ApiDocGenerator(docjson); const save = await vscode.window.showSaveDialog({ filters:{ "EmmyLua Doc File":["lua"], //"TypeScriptToLua Doc File":["d.ts"], }, defaultUri: file[0].with({path: file[0].path.replace(/.json$/,".lua")}), }); if (save) { if (save.path.endsWith(".lua")) { const buff = gen.generate_emmylua_docs(); vscode.workspace.fs.writeFile(save,buff); const add_to_lib = <"Workspace"|"Global"|"No"|undefined> await vscode.window.showInformationMessage("Add generated file to library setting?", {}, "Workspace", "Global", "No"); if (add_to_lib && add_to_lib !== "No") { const config = vscode.workspace.getConfiguration("Lua"); const library: string[] = config.get("workspace.library") ?? []; if (!library.includes(save.fsPath)) { library.push(save.fsPath); config.update("workspace.library", library, add_to_lib==="Global"); } const preloadFileSize = config.get<number>("workspace.preloadFileSize",0); const docFileSize = Math.trunc(buff.length/1000)+1; if (preloadFileSize < docFileSize) { if ((await vscode.window.showWarningMessage(`workspace.preloadFileSize value ${preloadFileSize}kb is too small to load the generated definitions file (${docFileSize}kb). Increase workspace.preloadFileSize?`,"Yes","No")) === "Yes") { config.update("workspace.preloadFileSize",docFileSize, add_to_lib==="Global"); } } } const config_for_sumneko = <"Workspace"|"Global"|"No"|undefined> await vscode.window.showInformationMessage("Configure `sumneko.lua` environment for factorio?", {}, "Workspace", "Global", "No"); if (config_for_sumneko && config_for_sumneko !== "No") { const config = vscode.workspace.getConfiguration("Lua"); const globals= config.get<string[]>("diagnostics.globals") ?? []; [ "game", "script", "remote", "commands", "settings", "rcon", "rendering", "global", "log", "defines", "data", "mods", "serpent", "table_size", "bit32", "util", "localised_print", //TODO: more data stage ones? "circuit_connector_definitions", "universal_connector_template", "__DebugAdapter", "__Profiler", ].forEach(s=>{ if (!globals.includes(s)) { globals.push(s); } }); config.update("diagnostics.globals", globals, config_for_sumneko==="Global"); config.update("runtime.version", "Lua 5.2", config_for_sumneko==="Global"); const diagdisable= config.get<string[]>("diagnostics.disable") ?? []; if (!diagdisable.includes("lowercase-global")) { diagdisable.push("lowercase-global"); } config.update("diagnostics.disable", diagdisable, config_for_sumneko==="Global"); const path_is_regular = file[0].path.match(/^(.*)[\/\\]doc-html[\/\\]runtime-api.json$/); if (path_is_regular) { const library: string[] = config.get("workspace.library") ?? []; const rootpath = file[0].with({path:path_is_regular[1]}); const datapath = vscode.Uri.joinPath(rootpath,"data"); const lualibpath = vscode.Uri.joinPath(datapath,"core","lualib"); try { if (!library.includes(datapath.fsPath) && // eslint-disable-next-line no-bitwise ((await vscode.workspace.fs.stat(datapath)).type & vscode.FileType.Directory)) { library.push(datapath.fsPath); } } catch {} try { if (!library.includes(lualibpath.fsPath) && // eslint-disable-next-line no-bitwise ((await vscode.workspace.fs.stat(lualibpath)).type & vscode.FileType.Directory)) { library.push(lualibpath.fsPath); } } catch {} config.update("workspace.library", library, config_for_sumneko==="Global"); } } } else if (save.path.endsWith(".d.ts")) { vscode.workspace.fs.writeFile(save,gen.generate_ts_docs()); } } })); if (vscode.workspace.workspaceFolders) { const treeDataProvider = new ModsTreeDataProvider(); context.subscriptions.push(treeDataProvider); const view = vscode.window.createTreeView('factoriomods', { treeDataProvider: treeDataProvider }); context.subscriptions.push(view); } } export function deactivate() { // nothing to do } function translatePath(thispath:string,factorioPath:string):string { if (thispath.startsWith("__PATH__executable__")) {return path.join(path.dirname(factorioPath),thispath.replace("__PATH__executable__",""));} if (thispath.startsWith("__PATH__system-write-data__")) { // windows: %appdata%/Factorio // linux: ~/.factorio // mac: ~/Library/Application Support/factorio const syswrite = os.platform() === "win32" ? path.resolve(process.env.APPDATA!,"Factorio") : os.platform() === "linux" ? path.resolve(os.homedir(), ".factorio") : os.platform() === "darwin" ? path.resolve(os.homedir(), "Library/Application Support/factorio" ) : "??"; return path.join(syswrite,thispath.replace("__PATH__system-write-data__","")); } if (thispath.startsWith("__PATH__system-read-data__")) { // linux: /usr/share/factorio // mac: factorioPath/../data // else (windows,linuxsteam): factorioPath/../../data const sysread = os.platform() === "linux" ? "/usr/share/factorio" : os.platform() === "darwin" ? path.resolve(path.dirname(factorioPath), "../data" ) : path.resolve(path.dirname(factorioPath), "../../data" ); return path.join(sysread,thispath.replace("__PATH__system-read-data__","")); } return thispath; } interface FactorioConfigIni { path?:{ "read-data"?:string "write-data"?:string } other?:{ "cache-prototype-data"?:boolean } }; class FactorioModConfigurationProvider implements vscode.DebugConfigurationProvider { /** * Massage a debug configuration just before a debug session is being launched, * e.g. add all missing attributes to the debug configuration. */ async resolveDebugConfigurationWithSubstitutedVariables(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration|undefined> { // factorio path exists and is a file (and is a binary?) if (!config.factorioPath) { const factorioPath = await vscode.window.showOpenDialog({ canSelectFiles: true, canSelectFolders: false, openLabel: "Select Factorio binary", filters: os.platform() === "win32" ? { "": ["exe"] } : undefined }); if (factorioPath) { config.factorioPath = factorioPath[0].fsPath; } } if(!config.factorioPath){ vscode.window.showInformationMessage("factorioPath is required"); return undefined; // abort launch } else if (config.factorioPath.match(/^~[\\\/]/)){ config.factorioPath = path.posix.join( os.homedir().replace(/\\/g,"/"), config.factorioPath.replace(/^~[\\\/]/,"") ); } if(!fs.existsSync(config.factorioPath) ){ vscode.window.showInformationMessage(`factorioPath "${config.factorioPath}" does not exist`); return undefined; // abort launch } const args:string[] = config.factorioArgs; if (args) { if (args.includes("--config")) { vscode.window.showInformationMessage("Factorio --config option is set by configPath and should not be included in factorioArgs"); return undefined; // abort launch } if (args.includes("--mod-directory")) { vscode.window.showInformationMessage("Factorio --mod-directory option is set by modsPath and should not be included in factorioArgs"); return undefined; // abort launch } } if (!config.configPath) { // find config-path.cfg then config.ini and dataPath/modsPath defaults const cfgpath = path.resolve(path.dirname(config.factorioPath), "../../config-path.cfg" ); if (fs.existsSync(cfgpath)) { const configdata = ini.parse(fs.readFileSync(cfgpath,"utf8")); config.configPath = path.resolve( translatePath(configdata["config-path"],config.factorioPath), "./config.ini"); } else { // try for a config.ini in systemwritepath config.configPath = translatePath("__PATH__system-write-data__/config/config.ini",config.factorioPath); } config.configPathDetected = true; } else if (config.configPath.match(/^~[\\\/]/)){ config.configPath = path.posix.join( os.homedir().replace(/\\/g,"/"), config.configPath.replace(/^~[\\\/]/,"") ); } if (!fs.existsSync(config.configPath)) { if (config.configPathDetected) { vscode.window.showInformationMessage("Unable to detect config.ini location. New Factorio install? Try just launching the game directly once first to create one."); return undefined; // abort launch } else { vscode.window.showInformationMessage("Specified config.ini not found. New Factorio install? Try just launching the game directly once first to create one."); return undefined; // abort launch } } let configdata:FactorioConfigIni = ini.parse(fs.readFileSync(config.configPath,"utf8")); if (configdata?.other?.["cache-prototype-data"]) { const pcache = await vscode.window.showWarningMessage( "Prototype Caching is enabled, which usually conflicts with the final portion of debugger initialization (which occurs in settings stage).", "Disable in config.ini","Continue anyway" ); if (pcache === "Disable in config.ini") { let filedata = fs.readFileSync(config.configPath,"utf8"); filedata = filedata.replace("cache-prototype-data=","; cache-prototype-data="); fs.writeFileSync(config.configPath,filedata,"utf8"); configdata = ini.parse(filedata); } else if (pcache === undefined) { return undefined; } } const configDataPath = configdata?.path?.["read-data"]; if (!configDataPath) { return vscode.window.showInformationMessage("path.read-data missing in config.ini").then(_ => { return undefined; // abort launch }); } config.dataPath = path.posix.normalize(translatePath(configDataPath,config.factorioPath)); if (config.modsPath) { config.modsPathSource = "launch"; let modspath = path.posix.normalize(config.modsPath); if (modspath.match(/^~[\\\/]/)){ modspath = path.posix.join( os.homedir().replace(/\\/g,"/"), modspath.replace(/^~[\\\/]/,"") ); } if (modspath.match(/[\\\/]$/)) { modspath = modspath.replace(/[\\\/]+$/,""); } if (fs.existsSync(modspath)) { config.modsPath = modspath; if (!fs.existsSync(path.resolve(config.modsPath,"./mod-list.json"))) { const create = await vscode.window.showWarningMessage( "modsPath specified in launch configuration does not contain mod-list.json", "Create it","Cancel" ); if (create !== "Create it") { return undefined; // abort launch } } } else { return vscode.window.showInformationMessage("modsPath specified in launch configuration does not exist").then(_ => { return undefined; // abort launch }); } } else { // modsPath not configured: detect from config.ini or mods-list.json in workspace const workspaceModLists = await vscode.workspace.findFiles("**/mod-list.json"); if (workspaceModLists.length === 1) { // found one, just use it config.modsPath = path.dirname(workspaceModLists[0].fsPath); config.modsPathSource = "workspace"; } else if (workspaceModLists.length > 1) { // found more than one. quickpick them. config.modsPath = await vscode.window.showQuickPick( workspaceModLists.map(ml=>path.dirname(ml.fsPath)), { placeHolder: "Select mod-list.json to use", } ); config.modsPathSource = "workspace"; } else { // found none. detect from config.ini const configModsPath = configdata?.path?.["write-data"]; if (!configModsPath) { vscode.window.showInformationMessage("path.write-data missing in config.ini"); return undefined; // abort launch } config.modsPathSource = "config"; config.modsPath = path.posix.normalize(path.resolve( translatePath(configModsPath,config.factorioPath),"mods")); if (!fs.existsSync(path.resolve(config.modsPath,"./mod-list.json"))) { const create = await vscode.window.showWarningMessage( "modsPath detected from config.ini does not contain mod-list.json", "Create it","Cancel" ); if (create !== "Create it") { return undefined; // abort launch } } } } if (os.platform() === "win32" && config.modsPath.startsWith("/")) {config.modsPath = config.modsPath.substr(1);} return config; } } class InlineDebugAdapterFactory implements vscode.DebugAdapterDescriptorFactory { constructor(private readonly context: vscode.ExtensionContext) {} createDebugAdapterDescriptor(_session: vscode.DebugSession): vscode.ProviderResult<vscode.DebugAdapterDescriptor> { const fmds = new FactorioModDebugSession(); fmds.setContext(this.context); return new vscode.DebugAdapterInlineImplementation(fmds); } dispose() { } }
the_stack
import React from 'react'; import { act, cleanup, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom'; import { Collapse } from '../index'; import { sleep } from '@test/utils'; import { sashItemClassName } from 'mo/components/split/base'; import { collapsePaneClassName } from '../base'; afterEach(cleanup); describe('Test The Collapse Component', () => { beforeAll(() => { // @ts-ignore window.innerHeight = 500; }); let original; const observerFnCollection: any[] = []; beforeEach(() => { original = HTMLElement.prototype.getBoundingClientRect; // @ts-ignore HTMLElement.prototype.getBoundingClientRect = () => ({ height: 500, }); global.ResizeObserver = jest.fn().mockImplementation((fn) => { observerFnCollection.push(fn); return { observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), }; }); }); afterEach(() => { HTMLElement.prototype.getBoundingClientRect = original; observerFnCollection.length = 0; }); test('Match Snapshot', () => { const { asFragment } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 } }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock2', name: 'test2' }, ]} /> ); expect(asFragment()).toMatchSnapshot(); }); test('Should uncollapsing the mock2', async () => { const mockFn = jest.fn(); const mockResize = jest.fn(); const { container } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 } }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3' }, ]} onCollapseChange={mockFn} onResize={mockResize} /> ); const collaspeItem = container.querySelector( 'div[data-collapse-id="mock2"]' ); expect(collaspeItem?.parentElement?.style.height).toBe('26px'); await act(async () => { // uncollasing mock2 fireEvent.click(collaspeItem?.childNodes[0]!); await sleep(300); }); expect(mockFn).toBeCalled(); expect(mockFn.mock.calls[0][0]).toEqual(['mock2']); expect(mockResize).toBeCalled(); expect(mockResize.mock.calls[0][0]).toEqual([26, 448, 26]); mockFn.mockClear(); mockResize.mockClear(); await act(async () => { // collapsing mock2 to restore default status fireEvent.click(collaspeItem?.childNodes[0]!); await sleep(300); }); expect(mockFn).toBeCalled(); expect(mockFn.mock.calls[0][0]).toEqual([]); expect(mockResize).toBeCalled(); expect(mockResize.mock.calls[0][0]).toEqual([26, 26, 26]); await act(async () => { // collapsing mock2 and mock3 const mock3 = container.querySelector( 'div[data-collapse-id="mock3"]' ); fireEvent.click(collaspeItem?.childNodes[0]!); await sleep(300); fireEvent.click(mock3?.childNodes[0]!); await sleep(300); }); expect(mockResize).toBeCalled(); // divided the remaining space by grow number expect(mockResize.mock.calls[2][0]).toEqual([26, 316, 158]); }); test('Should support to change size', async () => { const mockResize = jest.fn(); const { container, getByTestId } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 } }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3', renderPanel: () => <div data-testid="test"></div>, }, ]} onResize={mockResize} /> ); expect(getByTestId('test')).toBeInTheDocument(); await act(async () => { const mock2 = container.querySelector( 'div[data-collapse-id="mock2"]' ); const mock3 = container.querySelector( 'div[data-collapse-id="mock3"]' ); fireEvent.click(mock2?.childNodes[0]!); await sleep(300); fireEvent.click(mock3?.childNodes[0]!); await sleep(300); }); mockResize.mockClear(); const wrapper = container.querySelector(`.${collapsePaneClassName}`)!; const sashs = container.querySelectorAll(`.${sashItemClassName}`); fireEvent.mouseDown(sashs[2]); fireEvent.mouseMove(wrapper, { screenX: 10, screenY: 10 }); fireEvent.mouseUp(wrapper); expect(mockResize).toBeCalled(); expect(mockResize.mock.calls[0][0]).toEqual([26, 326, 148]); }); test('Should NOT trigger onChange', async () => { const mockResize = jest.fn(); const { container, getByTestId } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 } }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3', renderPanel: () => <div data-testid="test"></div>, }, ]} onResize={mockResize} /> ); expect(getByTestId('test')).toBeInTheDocument(); await act(async () => { const mock2 = container.querySelector( 'div[data-collapse-id="mock2"]' ); const mock3 = container.querySelector( 'div[data-collapse-id="mock3"]' ); fireEvent.click(mock2?.childNodes[0]!); await sleep(300); fireEvent.click(mock3?.childNodes[0]!); await sleep(300); }); mockResize.mockClear(); const wrapper = container.querySelector(`.${collapsePaneClassName}`)!; const sashs = container.querySelectorAll(`.${sashItemClassName}`); // ensure when there is no changes in sizes it won't trigger onResize event fireEvent.mouseDown(sashs[2]); fireEvent.mouseMove(wrapper, { screenX: 0, screenY: 0 }); fireEvent.mouseUp(wrapper); expect(mockResize).not.toBeCalled(); }); test('Should resize grow:2 pane', async () => { const { container } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 } }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3', }, ]} /> ); const mock2 = container.querySelector('div[data-collapse-id="mock2"]'); await act(async () => { fireEvent.click(mock2?.childNodes[0]!); await sleep(300); }); expect(mock2?.parentElement?.style.height).toBe('448px'); await act(async () => { // @ts-ignore HTMLElement.prototype.getBoundingClientRect = () => ({ height: 1000, }); observerFnCollection.forEach((f) => f()); await sleep(150); }); expect(mock2?.parentElement?.style.height).toBe('948px'); }); test('Should NOT render hidden pane', async () => { const { container } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 }, hidden: true, }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3', }, ]} /> ); const mock1 = container.querySelector('div[data-collapse-id="mock1"]'); expect(mock1?.parentElement?.style.height).toBe('0px'); await act(async () => { const mock2 = container.querySelector( 'div[data-collapse-id="mock2"]' ); fireEvent.click(mock2?.childNodes[0]!); await sleep(300); }); // didn't effect the hidden pane expect(mock1?.parentElement?.style.height).toBe('0px'); }); test('Should support to collapse a auto height pane', async () => { const { container } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 }, renderPanel: () => ( <div data-content="mock1" style={{ height: 500 }}> 1 </div> ), }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3', }, ]} /> ); const mock1 = container.querySelector('div[data-collapse-id="mock1"]'); expect(mock1?.parentElement?.style.height).toBe('26px'); await act(async () => { fireEvent.click(mock1?.childNodes[0]!); await sleep(300); }); expect(mock1?.parentElement?.style.height).toBe('220px'); await act(async () => { // collapsing it fireEvent.click(mock1?.childNodes[0]!); await sleep(300); // @ts-ignore HTMLElement.prototype.getBoundingClientRect = () => ({ height: 100, }); // re-uncollapse it fireEvent.click(mock1?.childNodes[0]!); await sleep(300); }); expect(mock1?.parentElement?.style.height).toBe('126px'); }); test('Should NOT uncollapse the empty grow-0 pane', async () => { const { container } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 }, renderPanel: () => null, }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3', }, ]} /> ); const mock1 = container.querySelector('div[data-collapse-id="mock1"]'); expect(mock1?.parentElement?.style.height).toBe('26px'); await act(async () => { fireEvent.click(mock1?.childNodes[0]!); await sleep(300); }); expect(mock1?.parentElement?.style.height).toBe('26px'); }); test('Should support to cache the adjusted size', async () => { const { container } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 } }, { id: 'mock2', name: 'test2', config: { grow: 2 } }, { id: 'mock3', name: 'test3' }, ]} /> ); // uncollaspe the mock2 and mock3 const mock2 = container.querySelector('div[data-collapse-id="mock2"]'); const mock3 = container.querySelector('div[data-collapse-id="mock3"]'); await act(async () => { fireEvent.click(mock2?.childNodes[0]!); await sleep(300); fireEvent.click(mock3?.childNodes[0]!); await sleep(300); }); expect(mock2?.parentElement?.style.height).toBe('316px'); expect(mock3?.parentElement?.style.height).toBe('158px'); // adjust the sizes of the mock2 and mock3 const wrapper = container.querySelector(`.${collapsePaneClassName}`)!; const sashs = container.querySelectorAll(`.${sashItemClassName}`); fireEvent.mouseDown(sashs[2]); fireEvent.mouseMove(wrapper, { screenX: 10, screenY: 10 }); fireEvent.mouseUp(wrapper); expect(mock2?.parentElement?.style.height).toBe('326px'); expect(mock3?.parentElement?.style.height).toBe('148px'); await act(async () => { // collapse the mock3 fireEvent.click(mock3?.childNodes[0]!); await sleep(300); }); expect(mock2?.parentElement?.style.height).toBe('448px'); expect(mock3?.parentElement?.style.height).toBe('26px'); await act(async () => { // uncollapse the mock3 fireEvent.click(mock3?.childNodes[0]!); await sleep(300); }); expect(mock2?.parentElement?.style.height).toBe('326px'); expect(mock3?.parentElement?.style.height).toBe('148px'); }); test('Should support to onToolbarClick', async () => { const mockFn = jest.fn(); const { container, getByTestId } = render( <Collapse data={[ { id: 'mock1', name: 'test1', config: { grow: 0 } }, { id: 'mock2', name: 'test2', config: { grow: 2 }, toolbar: [ { id: 'toolbar1', 'data-testid': 'toolbar1' }, ], }, { id: 'mock3', name: 'test3' }, ]} onToolbarClick={mockFn} /> ); await act(async () => { // uncollaspe the mock2 and mock3 const mock2 = container.querySelector( 'div[data-collapse-id="mock2"]' ); fireEvent.click(mock2?.childNodes[0]!); await sleep(300); }); expect(getByTestId('toolbar1')).toBeInTheDocument(); fireEvent.click(getByTestId('toolbar1')); expect(mockFn).toBeCalled(); expect(mockFn.mock.calls[0][0]).toEqual( expect.objectContaining({ id: 'toolbar1', 'data-testid': 'toolbar1', }) ); expect(mockFn.mock.calls[0][1]).toEqual({ id: 'mock2', name: 'test2', config: { grow: 2 }, toolbar: [{ id: 'toolbar1', 'data-testid': 'toolbar1' }], }); }); });
the_stack
declare type Commands = HashTable<ICommand>; interface HashTable<T> { [key: string]: T; } interface ICommand { name: string; id: number; args: any[]; // TODO specify array structure retType: string; } interface CmdMessage { devid: number; cmd: ICommand; data: Uint8Array; } interface Payload { dv: DataView; classId: number; funcId: number; } class Driver { constructor(public name: string, public id: number, private cmds: any) {} getCmdRef(cmdName) { for (let cmd of this.cmds) { if (cmdName === cmd.name) { return cmd.id; } } throw new ReferenceError(cmdName + ': command not found'); } getCmds() { let cmdsDict = {}; for (let cmd of this.cmds) { cmdsDict[cmd.name] = cmd; } return cmdsDict; } } class WebSocketPool { private pool: Array<WebSocket>; private freeSockets: number[]; private dedicatedSockets: Array<WebSocket>; private socketCounter: number; private exiting: boolean; constructor(private poolSize: number, private url: string, private onOpenCallback: any) { this.poolSize = poolSize; this.url = url; this.pool = []; this.freeSockets = []; this.dedicatedSockets = []; this.socketCounter = 0; this.exiting = false; for (let i = 0, end = this.poolSize-1, asc = 0 <= end; asc ? i <= end : i >= end; asc ? i++ : i--) { var websocket = this._newWebSocket(); this.pool.push(websocket); websocket.onopen = evt => { return this.waitForConnection(websocket, 100, () => { console.assert(websocket.readyState === 1, 'Websocket not ready'); this.freeSockets.push(this.socketCounter); if (this.socketCounter === 0) { onOpenCallback(); } websocket.ID = this.socketCounter; websocket.onclose = evt => { setTimeout(function(){ location.reload(); }, 1000); }; websocket.onerror = evt => { console.error(`error: ${evt.data}\n`); return websocket.close(); }; return this.socketCounter++; } ); }; } } _newWebSocket() { let websocket; if (typeof window !== 'undefined' && window !== null) { websocket = new WebSocket(this.url); } else { // Node let clientConfig: any = {}; clientConfig.fragmentOutgoingMessages = false; let __WebSocket = require('websocket').w3cwebsocket; websocket = new __WebSocket(this.url, null, null, null, null, clientConfig); } websocket.binaryType = 'arraybuffer'; return websocket; } waitForConnection(websocket, interval, callback) { if (websocket.readyState === 1) { // If the client has been set to exit while establishing the connection // we don't initialize the socket if (this.exiting) { return; } return callback(); } else { return setTimeout( () => { return this.waitForConnection(websocket, interval, callback); } , interval); } } getSocket(sockid) { if (this.exiting) { return null; } if (!(this.freeSockets.some(x => x == sockid)) && (sockid >= 0) && (sockid < this.poolSize)) { return this.pool[sockid]; } else { throw new ReferenceError(`Socket ID ${sockid.toString()} not available`); } } // Obtain a socket for a dedicated task. // This function is provided for long term use. // A new socket is opened and returned to the caller. // This socket is not shared and can be used for a // dedicated task. // TODO: Caller close dedicated socket getDedicatedSocket(callback) { let websocket = this._newWebSocket(); this.dedicatedSockets.push(websocket); return websocket.onopen = evt => { return this.waitForConnection(websocket, 100, () => { console.assert(websocket.readyState === 1, 'Websocket not ready'); websocket.onclose = evt => { let idx = this.dedicatedSockets.indexOf(websocket); if (idx > -1) { return this.dedicatedSockets.splice(idx, 1); } }; websocket.onerror = evt => { console.error(`error: ${evt.data}\n`); return websocket.close(); }; return callback(websocket); } ); }; } // Retrieve a socket from the pool. // This function is provided for short term socket use // and the socket must be given back to the pool by // calling freeeSocket. requestSocket(callback) { if (this.exiting) { callback(-1); return; } if ((this.freeSockets != null) && (this.freeSockets.length > 0)) { let sockid = this.freeSockets[this.freeSockets.length-1]; this.freeSockets.pop(); return this.waitForConnection(this.pool[sockid], 100, () => { console.assert(this.pool[sockid].readyState === 1, 'Websocket not ready'); return callback(sockid); } ); } else { // All sockets are busy. We wait a bit and retry. console.assert(this.freeSockets.length === 0, 'Non empty freeSockets'); return setTimeout( () => { return this.requestSocket(callback); } , 100); } } // Give back a socket to the pool freeSocket(sockid) { if (this.exiting) { return; } if (!(this.freeSockets.some(x => x == sockid)) && (sockid >= 0) && (sockid < this.poolSize)) { return this.freeSockets.push(sockid); } else { if (sockid != null) { return console.error(`Invalid Socket ID ${sockid.toString()}`); } else { return console.error('Undefined Socket ID'); } } } exit() { this.exiting = true; this.freeSockets = []; this.socketCounter = 0; for (let websocket of this.pool) { websocket.close(); } return this.dedicatedSockets.map((socket) => socket.close()); } } // === Helper functions to build binary buffer === let appendInt8 = function(buffer, value) { buffer.push(value & 0xff); return 1; }; let appendUint8 = function(buffer, value) { buffer.push(value & 0xff); return 1; }; let appendInt16 = function(buffer, value) { buffer.push((value >> 8) & 0xff); buffer.push(value & 0xff); return 2; }; let appendUint16 = function(buffer, value) { buffer.push((value >> 8) & 0xff); buffer.push(value & 0xff); return 2; }; let appendInt32 = function(buffer, value) { buffer.push((value >> 24) & 0xff); buffer.push((value >> 16) & 0xff); buffer.push((value >> 8) & 0xff); buffer.push(value & 0xff); return 4; }; let appendUint32 = function(buffer, value) { buffer.push((value >> 24) & 0xff); buffer.push((value >> 16) & 0xff); buffer.push((value >> 8) & 0xff); buffer.push(value & 0xff); return 4; }; let floatToBytes = function(f) { let buf = new ArrayBuffer(4); (new Float32Array(buf))[0] = f; return (new Uint32Array(buf))[0]; }; let bytesTofloat = function(bytes) { let buffer = new ArrayBuffer(4); (new Uint32Array(buffer))[0] = bytes; return new Float32Array(buffer)[0]; }; let appendFloat32 = (buffer, value) => appendUint32(buffer, floatToBytes(value)); let appendFloat64 = function(buffer, value) { let buf = new ArrayBuffer(8); (new Float64Array(buf))[0] = value; appendUint32(buffer, (new Uint32Array(buf, 4))[0]); appendUint32(buffer, (new Uint32Array(buf, 0))[0]); console.assert(buf.byteLength === 8, 'Invalid float64 size'); return buf.byteLength; }; let appendArray = function(buffer, array) { let bytes = new Uint8Array(array.buffer); return bytes.map((_byte) => buffer.push(_byte)); }; let appendVector = function(buffer, array) { appendUint32(buffer, array.buffer.byteLength); let bytes = new Uint8Array(array.buffer); return bytes.map((_byte) => buffer.push(_byte)); }; let appendString = function(buffer, str: string) { appendUint32(buffer, str.length); for (let i = 0; i < str.length; i++) { buffer.push(str.charCodeAt(i)); } }; let isStdArray = type => type.split('<')[0].trim() === 'std::array'; let isStdVector = type => type.split('<')[0].trim() === 'std::vector'; let isStdString = type => type.trim() === 'std::string'; let isStdTuple = type => type.split('<')[0].trim() === 'std::tuple'; let getStdVectorType = type => type.split('<')[1].split('>')[0].trim(); function Command(devId: number, cmd: ICommand, ...params: any[]): CmdMessage { let buffer = []; appendUint32(buffer, 0); // RESERVED appendUint16(buffer, devId); appendUint16(buffer, cmd.id); if (cmd.args.length === 0) { return { devid: devId, cmd, data: new Uint8Array(buffer) }; } if (cmd.args.length !== params.length) { throw new Error(`Invalid number of arguments. Expected ${cmd.args.length} receive ${params.length}.`); } let buildPayload = function(args, params) { if (args == null) { args = []; } let payload = []; for (let i = 0; i < args.length; i++) { let arg = args[i]; switch (arg.type) { case 'uint8_t': appendUint8(payload, params[i]); break; case 'int8_t': appendInt8(payload, params[i]); break; case 'uint16_t': appendUint16(payload, params[i]); break; case 'int16_t': appendInt16(payload, params[i]); break; case 'uint32_t': appendUint32(payload, params[i]); break; case 'int32_t': appendInt32(payload, params[i]); break; case 'float': appendFloat32(payload, params[i]); break; case 'double': appendFloat64(payload, params[i]); break; case 'bool': if (params[i]) { appendUint8(payload, 1); } else { appendUint8(payload, 0); } break; default: if (isStdArray(arg.type)) { appendArray(payload, params[i]); } else if (isStdVector(arg.type)) { appendVector(payload, params[i]); } else if (isStdString(arg.type)) { appendString(payload, params[i]); } else { throw new TypeError(`Unknown type ${arg.type}`); } } } return payload; }; return { devid: devId, cmd, data: new Uint8Array(buffer.concat(buildPayload(cmd.args, params))) }; } class Client { private url: string; private driversList: Array<Driver>; private websockpool: WebSocketPool; constructor(private IP: string, private websockPoolSize: number) { if (websockPoolSize == null) { websockPoolSize = 5; } this.websockPoolSize = websockPoolSize; this.url = `ws://${IP}:8080`; this.driversList = []; } init(callback) { return this.websockpool = new WebSocketPool(this.websockPoolSize, this.url, (function() { return this.loadCmds(callback); }.bind(this))); } exit() { this.websockpool.exit(); return delete this.websockpool; } // ------------------------ // Send // ------------------------ send(cmd) { if (this.websockpool === null || typeof this.websockpool === 'undefined') { return; } this.websockpool.requestSocket( sockid => { if (sockid < 0) { return; } let websocket = this.websockpool.getSocket(sockid); websocket.send(cmd.data); if (this.websockpool !== null && typeof this.websockpool !== 'undefined') { this.websockpool.freeSocket(sockid); } } ); } // ------------------------ // Receive // ------------------------ redirectError(errTest, errMsg, onSuccess, onError) { if (errTest) { if (onError === null) { throw new TypeError(errMsg); } else { return onError(errMsg); } } else { return onSuccess(); } } getPayload(mode, evt) { let buffer, dvBuff, i, len; let dv = new DataView(evt.data); let reserved = dv.getUint32(0); let classId = dv.getUint16(4); let funcId = dv.getUint16(6); if (mode === 'static') { len = dv.byteLength - 8; buffer = new ArrayBuffer(len); dvBuff = new DataView(buffer); for (i = 0, end = len-1, asc = 0 <= end; asc ? i <= end : i >= end; asc ? i++ : i--) { var asc, end; dvBuff.setUint8(i, dv.getUint8(8 + i)); } } else { // 'dynamic' len = dv.getUint32(8); console.assert(dv.byteLength === (len + 12)); buffer = new ArrayBuffer(len); dvBuff = new DataView(buffer); for (i = 0, end1 = len-1, asc1 = 0 <= end1; asc1 ? i <= end1 : i >= end1; asc1 ? i++ : i--) { var asc1, end1; dvBuff.setUint8(i, dv.getUint8(12 + i)); } } return [dvBuff, classId, funcId]; } _readBase(mode: string, cmd: CmdMessage, fn: (x: DataView) => void): void { if ((this.websockpool === null || typeof(this.websockpool) === 'undefined')) { return fn(null); } this.websockpool.requestSocket( sockid => { if (sockid < 0) { return fn(null); } let websocket = this.websockpool.getSocket(sockid); websocket.send(cmd.data); websocket.onmessage = evt => { fn(this.getPayload(mode, evt)[0]); if (this.websockpool !== null && typeof this.websockpool !== 'undefined') { this.websockpool.freeSocket(sockid); } }; }); } readUint32Array(cmd: CmdMessage, fn: (x: Uint32Array) => void): void { this._readBase('static', cmd, (data) => { fn(new Uint32Array(data.buffer)); }); } readFloat32Array(cmd: CmdMessage, fn: (x: Float32Array) => void): void { this._readBase('static', cmd, (data) => { fn(new Float32Array(data.buffer)); }); } readFloat64Array(cmd: CmdMessage, fn: (x: Float64Array) => void): void { this._readBase('static', cmd, (data) => { fn(new Float64Array(data.buffer)); }); } readUint32Vector(cmd: CmdMessage, fn: (x: Uint32Array) => void): void { this._readBase('dynamic', cmd, (data) => { fn(new Uint32Array(data.buffer)); }); } readFloat32Vector(cmd: CmdMessage, fn: (x: Float32Array) => void): void { this._readBase('dynamic', cmd, (data) => { fn(new Float32Array(data.buffer)); }); } readFloat64Vector(cmd: CmdMessage, fn: (x: Float64Array) => void): void { this._readBase('dynamic', cmd, (data) => { fn(new Float64Array(data.buffer)); }); } readUint32(cmd: CmdMessage, fn: (x: number) => void): void { this._readBase('static', cmd, data => { fn(data.getUint32(0)); }); } readInt32(cmd: CmdMessage, fn: (x: number) => void): void { this._readBase('static', cmd, (data) => { fn(data.getInt32(0)); }); } readFloat32(cmd: CmdMessage, fn: (x: number) => void): void { this._readBase('static', cmd, data => { fn(data.getFloat32(0)); }); } readFloat64(cmd: CmdMessage, fn: (x: number) => void): void { this._readBase('static', cmd, data => { fn(data.getFloat64(0)); }); } readBool(cmd: CmdMessage, fn: (x: boolean) => void): void { this._readBase('static', cmd, data => { fn(data.getUint8(0) === 1); }); } readTuple(cmd: CmdMessage, fmt: string, fn: (x: any[]) => void): void { this._readBase('static', cmd, data => { fn(this.deserialize(fmt, data)); }); } deserialize(fmt: string, dv: DataView, onError?: any) { if (onError == null) { onError = null; } let tuple = []; let offset = 0; for (let i = 0, end = fmt.length-1, asc = 0 <= end; asc ? i <= end : i >= end; asc ? i++ : i--) { switch (fmt[i]) { case 'B': tuple.push(dv.getUint8(offset)); offset += 1; break; case 'b': tuple.push(dv.getInt8(offset)); offset += 1; break; case 'H': tuple.push(dv.getUint16(offset)); offset += 2; break; case 'h': tuple.push(dv.getInt16(offset)); offset += 2; break; case 'I': tuple.push(dv.getUint32(offset)); offset += 4; break; case 'i': tuple.push(dv.getInt32(offset)); offset += 4; break; case 'f': tuple.push(dv.getFloat32(offset)); offset += 4; break; case 'd': tuple.push(dv.getFloat64(offset)); offset += 8; break; case '?': if (dv.getUint8(offset) === 0) { tuple.push(false); } else { tuple.push(true); } offset += 1; break; default: this.redirectError(true, `Unknown or unsupported type ${fmt[i]}`, (function() {}), onError); } } return tuple; } parseString(data: DataView, offset?: number) { if (offset == null) { offset = 0; } return (__range__(0, data.byteLength - offset - 1, true).map((i) => (String.fromCharCode(data.getUint8(offset + i))))).join(''); } readString(cmd: CmdMessage, fn: (str: string) => void): void { this._readBase('dynamic', cmd, data => { fn(this.parseString(data)) }); } readJSON(cmd: CmdMessage, fn: (json: any) => void): void { this.readString(cmd, str => { fn(JSON.parse(str)); }); } // ------------------------ // Drivers // ------------------------ loadCmds(callback: () => void) { this.readJSON(Command(1, <ICommand>{'id': 1, 'args': []}), data => { for (let driver of data) { let dev = new Driver(driver.class, driver.id, driver.functions); // dev.show() this.driversList.push(dev); } callback(); }); } getDriver(name: string) { for (let driver of this.driversList) { if (driver.name === name) { return driver; } } throw new Error(`Driver ${name} not found`); } getDriverById(id) { for (let driver of this.driversList) { if (driver.id === id) { return driver; } } throw new ReferenceError(`Driver ID ${id} not found`); } }; function __range__(left, right, inclusive) { let range = []; let ascending = left < right; let end = !inclusive ? right : ascending ? right + 1 : right - 1; for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) { range.push(i); } return range; } class Imports { private importLinks: HTMLLinkElement[]; constructor (document: Document) { this.importLinks = <HTMLLinkElement[]><any>document.querySelectorAll('link[rel="import"]'); for (let i = 0; i < this.importLinks.length ; i++) { let template = (this.importLinks[i] as any).import.querySelector('.template'); let clone = document.importNode(template.content, true); let parentId = this.importLinks[i].dataset.parent; document.getElementById(parentId).appendChild(clone); } } }
the_stack
import * as React from 'react'; import * as Utility from '../../Utility'; import * as $ from 'jquery'; import { BrowserRouter as Router, Route, Link, withRouter } from 'react-router-dom'; import { RouteComponent } from '../RouteComponent'; import { SendTopic } from './Topic-SendTopic'; import { Category } from './Topic-Category'; import { Pager } from '../Pager'; import { Reply } from './Topic-Reply'; import { NotFoundTopic, UnauthorizedTopic, ServerError } from '../Status'; import { TopicInfo } from './Topic-TopicInfo'; import { NoticeMessage } from '../NoticeMessage'; import DocumentTitle from '../DocumentTitle'; const initQuoteContext = { content: "", userName: "", replyTime: "", floor: "", postId: "" } export const QuoteContext = React.createContext((context) => { }); export class Post extends RouteComponent<{ history }, { topicid, page, totalPage, userName, boardId, topicInfo, boardInfo, fetchState, quote, shouldRender, isFav, IPData }, { topicid, page, userName }> { constructor(props, context) { super(props, context); this.update = this.update.bind(this); this.handleChange = this.handleChange.bind(this); this.quote = this.quote.bind(this); this.state = { page: 1, shouldRender: true, topicid: this.match.params.topicid, totalPage: 1, userName: null, boardId: 7, topicInfo: { replyCount: 0 }, boardInfo: { masters: [], id: 7 }, fetchState: 'ok', quote: "", isFav: false, IPData: [] }; } quote(content, userName, replyTime, floor, postId) { const y = $("#sendTopicInfo").offset().top; let page = this.state.page; if (!this.state.page) page = 1; const url = `/topic/${this.state.topicid}/${page}#sendTopicInfo`; this.props.history.push(url); this.setState({ quote: { content: content, userName: userName, replyTime: replyTime, floor: floor, postId: postId } }); } update() { this.setState({}); } async handleChange() { let page: number; if (!this.match.params.page) { page = 1; } else { page = parseInt(this.match.params.page); } const topicInfo = await Utility.getTopicInfo(this.match.params.topicid); this.setState({ topicInfo: topicInfo }); const newPage = (topicInfo.replyCount + 1) % 10 === 0 ? (topicInfo.replyCount + 1) / 10 : ((topicInfo.replyCount + 1) - (topicInfo.replyCount + 1) % 10) / 10 + 1; const totalPage = await this.getTotalPage(topicInfo.replyCount); const userName = this.match.params.userName; const floor = (topicInfo.replyCount + 1) % 10; //检查用户是否设置跳转到最新回复 let noticeSetting = Utility.getLocalStorage("noticeSetting"); if (page != newPage) { console.log("当前页不是最新一页"); //如果设置了跳转到最新回复或者刚好翻页,则跳转 if ((noticeSetting && noticeSetting.post === "是") || ((newPage == page + 1) && (floor == 1))) { console.log("要跳转"); page = newPage; if(!page)page=1; let url = `/topic/${topicInfo.id}/${page}#${floor}`; this.setState({ quote: { userName: "", content: "", replyTime: "", floor: "" } }, this.props.history.push(url)); } else { let url = `/topic/${topicInfo.id}/${page}`; //如果是引用了某一层楼,发帖后应该跳转回这层楼 if (this.state.quote && this.state.quote.floor) { let quoteFloor = this.state.quote.floor % 10; if(!page)page=1; url = `/topic/${topicInfo.id}/${page}#${quoteFloor}`; this.setState({ quote: { userName: "", content: "", replyTime: "", floor: "" } }, this.props.history.push(url)); } //如果没有引用则不需要跳转,直接还是在输入框那个位置 } } else { page = newPage; if(!page)page=1; let url = `/topic/${topicInfo.id}/${page}#${floor}`; this.setState({ quote: { userName: "", content: "", replyTime: "", floor: "" } }, this.props.history.push(url)); } //回复成功提示 Utility.noticeMessageShow('replyMessage'); //const isFav = await Utility.getFavState(this.match.params.topicid); //this.setState({ topicInfo: topicInfo, quote: { userName: "", content: "", replyTime: "", floor: "" },isFav:isFav}); } async componentWillReceiveProps(newProps) { //page 是否变了 let page: number; if (!newProps.match.params.page) { page = 1; } else { page = parseInt(newProps.match.params.page); } const userName = newProps.match.params.userName; const topicInfo = await Utility.getTopicInfo(newProps.match.params.topicid); const boardId = topicInfo.boardId; const boardInfo = await Utility.getBoardInfo(boardId); const totalPage = this.getTotalPage(topicInfo.replyCount); const floor = (topicInfo.replyCount + 1) % 10; //如果page超过最大页码,就跳转到最大页码 if (page > totalPage) { page = totalPage; const url = `/topic/${topicInfo.id}/${page}#${floor}`; this.props.history.push(url); } const isFav = await Utility.getFavState(newProps.match.params.topicid); this.setState({ page: page, topicid: newProps.match.params.topicid, totalPage: totalPage, userName: userName, boardId: boardId, topicInfo: topicInfo, boardInfo: boardInfo, isFav: isFav }); } async componentDidMount() { await Utility.getBoards(); let page: number; if (!this.match.params.page) { page = 1; } else { page = parseInt(this.match.params.page); } const userName = this.match.params.userName; const topicInfo = await Utility.getTopicInfo(this.match.params.topicid); const boardId = topicInfo.boardId; const boardInfo = await Utility.getBoardInfo(boardId); const totalPage = this.getTotalPage(topicInfo.replyCount); const floor = (topicInfo.replyCount + 1) % 10; //如果page超过最大页码,就跳转到最大页码 if (page > totalPage) { page = totalPage; const url = `/topic/${topicInfo.id}/${page}#${floor}`; this.props.history.push(url); } const isFav = await Utility.getFavState(this.match.params.topicid); let IPData = []; // if (Utility.isMaster(boardInfo.boardMasters)) // IPData = await Utility.findIP(this.match.params.topicid); this.setState({ isFav, page: page, topicid: this.match.params.topicid, totalPage: totalPage, userName: userName, boardId: boardId, topicInfo: topicInfo, boardInfo: boardInfo, fetchState: topicInfo, IPData: IPData }); } getTotalPage(count) { return Utility.getTotalPageof10(count); } handleQuoteContextChange = (context) => { console.log("传进topic.tsx") console.log(context); this.setState({ quote: context }); } render() { console.log("topic render"); console.log("state"); console.log(this.state.quote); //$(".signature").children("article").children("img").css("display", "none"); // $(".signature").children("article").children("img:first").css("display", ""); switch (this.state.fetchState) { case 'ok': return <div></div>; case 'not found': return <NotFoundTopic />; case 'unauthorized': return <UnauthorizedTopic />; case 'server error': return <ServerError /> } let topic = null; let hotReply = null; let topicInfo = null; topicInfo = <TopicInfo topicInfo={this.state.topicInfo} tag1={this.state.topicInfo.tag1} tag2={this.state.topicInfo.tag2} boardInfo={this.state.boardInfo} isFav={this.state.isFav} />; if (parseInt(this.match.params.page) === 1 || !this.match.params.page) { hotReply = <Reply topicInfo={this.state.topicInfo} page={this.match.params.page} boardInfo={this.state.boardInfo} quote={this.quote} isTrace={false} isHot={true} postId={null} topicId={this.match.params.topicid} /> } const pagerUrl = `/topic/${this.state.topicid}/`; let sendTopic = null; if (Utility.getLocalStorage("userInfo")) sendTopic = <SendTopic onChange={this.handleChange} boardInfo={this.state.boardInfo} content={this.state.quote} topicInfo={this.state.topicInfo} />; else sendTopic = <div>您还未登录,无法发言,请先登录。</div>; if (Utility.getLocalStorage("userInfo") && !Utility.getLocalStorage("userInfo").isVerified) sendTopic = <div>您的帐号未认证,无法发言,请先前往 <a href="https://account.cc98.org">https://account.cc98.org</a> 认证激活。</div>; if (Utility.getLocalStorage("userInfo") && Utility.getLocalStorage("userInfo").lockState !== 0) sendTopic = <div>您的帐号被全站禁言。</div>; let tip = null; if (this.state.topicInfo && this.state.topicInfo.state === 1) tip = <div style={{ color: "red", margin: "0.5rem" }}>该帖已被锁定</div>; let topicHtml = <div className="center" > <DocumentTitle title={`${this.state.topicInfo.title || "帖子"} - CC98论坛`} /> <div className="column" style={{ width: "100%" }}> <div className="row" style={{ width: "100%", justifyContent: 'space-between', alignItems: "center" }}> <Category topicInfo={this.state.topicInfo} boardInfo={this.state.boardInfo} topicId={this.match.params.topicid} /> <Pager page={this.state.page} url={pagerUrl} totalPage={this.state.totalPage} /> </div> {tip} </div> {topicInfo} <QuoteContext.Provider value={this.handleQuoteContextChange}> <Reply topicInfo={this.state.topicInfo} page={this.state.page} boardInfo={this.state.boardInfo} quote={this.quote} isHot={false} isTrace={false} postId={null} topicId={this.match.params.topicid} /> </QuoteContext.Provider> <div className="column" style={{ width: "100%" }}> <div className="row" style={{ width: "100%", justifyContent: "space-between", marginTop: "2rem" }}> <Category topicInfo={this.state.topicInfo} boardInfo={this.state.boardInfo} topicId={this.match.params.topicid} /> <Pager page={this.state.page} url={pagerUrl} totalPage={this.state.totalPage} /></div> </div> {sendTopic} <NoticeMessage text="回复成功" id="replyMessage" top="24%" left="46%" /> </div> ; return topicHtml; /* if (this.state.shouldRender) { } else { return <img src="/static/images/waiting.gif"/>; }*/ } } export const ShowTopic = withRouter(Post);
the_stack
'use strict' import * as firebaseServer from '../firebaseServer'; import * as querybase from '../../entry'; import * as helpers from '../helpers'; import * as assert from 'assert'; import * as chai from 'chai'; import * as sinon from 'sinon'; const Querybase = querybase.Querybase; const QuerybaseQuery = querybase.QuerybaseQuery; const _ = querybase.QuerybaseUtils; const expect = chai.expect; // disable warnings // TODO: Create index rules for the firebase database console.warn = () => {}; describe('querybase export', () => { const ref = firebaseServer.ref().child('items'); const indexes = ['color', 'height', 'weight']; it('should create a Querybase ref', () => { const queryRef = querybase.ref(ref, indexes) assert.equal(true, helpers.isQuerybaseRef(queryRef)); }); }); describe('Querybase', () => { const ref = firebaseServer.ref().child('items'); const indexes = ['color', 'height', 'weight']; const expectedIndex = { 'color~~height': 'Blue~~67', 'color~~height~~weight': 'Blue~~67~~130', 'color~~weight': 'Blue~~130', 'height~~weight': '67~~130' }; let queryRef; beforeEach(() => queryRef = new Querybase(ref, indexes)); it('should exist', () => { expect(Querybase).to.exist; }); describe('constructor', () => { it('should throw if no Firebase ref is provided', () => { const errorWrapper = () => new Querybase(null, null); expect(errorWrapper).to.throw(Error); }); it('should throw if no indexes are provided', () => { const errorWrapper = () => new Querybase(ref, null); expect(errorWrapper).to.throw(Error); }); it('should throw if more than 3 indexes are provided', () => { const fourIndexes = ['color', 'height', 'weight', 'location']; const errorWrapper = () => new Querybase(ref, fourIndexes); expect(errorWrapper).to.throw(Error); }); }); describe('key property', () => { it('should throw if no indexes are provided', () => { const querybaseRef = querybase.ref(ref, ['name', 'age']); const key = querybaseRef.key; assert.equal(key, 'items'); }); }); describe('set', () => { it('should call the Firebase set function', () => { sinon.spy(queryRef.ref(), 'set'); queryRef.set({ age: 27, location: 'SF' }); expect(queryRef.ref().set.calledOnce).to.be.ok; queryRef.ref().set.restore(); }); it('should call the indexify function', () => { sinon.spy(queryRef, 'indexify'); queryRef.set({ age: 27, location: 'SF' }); expect(queryRef.indexify.calledOnce).to.be.ok; queryRef.indexify.restore(); }); }); describe('update', () => { it('should call the Firebase update function', () => { sinon.spy(queryRef.ref(), 'update'); queryRef.update({ age: 27, location: 'SF' }); expect(queryRef.ref().update.calledOnce).to.be.ok; queryRef.ref().update.restore(); }); it('should call the indexify function', () => { sinon.spy(queryRef, 'indexify'); queryRef.update({ age: 27, location: 'SF' }); expect(queryRef.indexify.calledOnce).to.be.ok; queryRef.indexify.restore(); }); }); describe('push', () => { it('should call the Firebase push function', () => { sinon.spy(queryRef.ref(), 'push'); queryRef.push({ age: 27, location: 'SF' }); expect(queryRef.ref().push.calledOnce).to.be.ok; queryRef.ref().push.restore(); }); it('should return a Firebase reference', () => { const pushedBase = queryRef.push({ age: 27, location: 'SF' }); assert.equal(true, helpers.isFirebaseRef(pushedBase)); }); it('should call the indexify function if data is passed', () => { sinon.spy(queryRef, 'indexify'); queryRef.push({ age: 27, location: 'SF' }); expect(queryRef.indexify.calledOnce).to.be.ok; queryRef.indexify.restore(); }); it('should not call the indexify function if no data is passed', () => { sinon.spy(queryRef, 'indexify'); queryRef.push(); assert.equal(queryRef.indexify.calledOnce, false); queryRef.indexify.restore(); }); it('should not call the indexify function if one field is passed', () => { sinon.spy(queryRef, 'indexify'); queryRef.push({ age: 27 }); assert.equal(queryRef.indexify.calledOnce, false); queryRef.indexify.restore(); }); }); describe('remove', () => { it('should call the Firebase remove function', () => { sinon.spy(queryRef.ref(), 'remove'); queryRef.remove(); expect(queryRef.ref().remove.calledOnce).to.be.ok; queryRef.ref().remove.restore(); }); }); describe('child', () => { it('should call the Firebase child function', () => { sinon.spy(queryRef.ref(), 'child'); queryRef.child('some/path', ['name', 'color']); expect(queryRef.ref().child.calledOnce).to.be.ok; queryRef.ref().child.restore(); }); it('should return a Querybase ref', () => { const childQueryRef = queryRef.child('some/path', ['name', 'color']); assert.equal(helpers.isQuerybaseRef(childQueryRef), true); }); it('should return a child Querybase ref with new indexes', () => { const childRef = queryRef.child('some/path', ['name', 'color']) assert.equal(childRef.indexOn()[0], 'color'); assert.equal(childRef.indexOn()[1], 'name'); }); it('should throw if no indexes are provided', () => { const errorWrapper = () => queryRef.child('someKey'); expect(errorWrapper).to.throw(Error); }); }); describe('where', () => { it('should return a QuerybaseQuery for a single criteria', () => { const query = queryRef.where('green'); assert.equal(helpers.isQuerybaseQuery(query), true); }); it('should return a Firebase query for an object with a single criteria', () => { const query = queryRef.where({ color: 'green' }); assert.equal(true, helpers.isFirebaseRef(query)); }); it('should create a Firebase query for multiple criteria', () => { const query = queryRef.where({ weight: '120', color: 'green' }); assert.equal(true, helpers.isFirebaseRef(query)); }); it('should warn about using indexOn rules', () => { sinon.spy(queryRef, '_warnAboutIndexOnRule'); const query = queryRef.where({ color: 'green', weight: '120' }); expect(queryRef._warnAboutIndexOnRule.calledOnce).to.be.ok; queryRef._warnAboutIndexOnRule.restore(); }); }); describe('_createQueryPredicate', () => { // not encoded // { color: 'Blue' } it('should create a QueryPredicate for one criteria', () => { const expectedPredicate = { predicate: 'color', value: 'Blue' }; const predicate = queryRef._createQueryPredicate({ color: 'Blue' }); assert.deepEqual(expectedPredicate, predicate); }); // encoded // { height: '67', color: 'Blue' } it('should encode a QueryPredicate for multiple criteria', () => { const expectedPredicate = { predicate: 'querybase~~Y29sb3J+fmhlaWdodA==', value: 'querybase~~Qmx1ZX5+Njc=' }; const predicate = queryRef._createQueryPredicate({ height: 67, color: 'Blue' }); assert.deepEqual(expectedPredicate, predicate); }); }); describe('_createCompositeIndex', () => { it('should create a composite index', () => { const compositeIndex = queryRef._createCompositeIndex(indexes, { weight: 130, height: 67, color: 'Blue' }); assert.deepEqual(compositeIndex, expectedIndex); }); it('should throw if no indexes are provided', () => { const errorWrapper = () => queryRef._createCompositeIndex(); expect(errorWrapper).to.throw(Error); }); it('should throw if no data is provided', () => { const errorWrapper = () => queryRef._createCompositeIndex(['name', 'age']); expect(errorWrapper).to.throw(Error); }); it('should throw if an empty array is provided', () => { const errorWrapper = () => queryRef._createCompositeIndex([]); expect(errorWrapper).to.throw(Error); }); }); describe('_encodeCompositeIndex', () => { it('should encode an object', () => { const expectedEncodedIndex = { 'querybase~~Y29sb3J+fmhlaWdodA==': 'querybase~~Qmx1ZX5+Njc=', 'querybase~~Y29sb3J+fmhlaWdodH5+d2VpZ2h0': 'querybase~~Qmx1ZX5+Njd+fjEzMA==', 'querybase~~Y29sb3J+fndlaWdodA==': 'querybase~~Qmx1ZX5+MTMw', 'querybase~~aGVpZ2h0fn53ZWlnaHQ=': 'querybase~~Njd+fjEzMA==' }; const encodedIndex = queryRef._encodeCompositeIndex(expectedIndex); assert.deepEqual(expectedEncodedIndex, encodedIndex); }); it('should throw if no parameter is provided', () => { const errorWrapper = () => queryRef._encodeCompositeIndex(); expect(errorWrapper).to.throw(Error); }); it('should throw if a non object is provided', () => { const errorWrapper = () => queryRef._encodeCompositeIndex(4); expect(errorWrapper).to.throw(Error); }); }); describe('_createChildOrderedQuery', () => { it('should call the Firebase orderByChild function', () => { sinon.spy(queryRef.ref(), 'orderByChild'); queryRef._createChildOrderedQuery('age'); expect(queryRef.ref().orderByChild.calledOnce).to.be.ok; queryRef.ref().orderByChild.restore(); }); }); describe('_createEqualToQuery', () => { it('should call the Firebase orderByChild function', () => { sinon.spy(queryRef.ref(), 'orderByChild'); queryRef._createEqualToQuery({ predicate: 'age~~name', value: '27~~David' }); expect(queryRef.ref().orderByChild.calledOnce).to.be.ok; queryRef.ref().orderByChild.restore(); }); }); describe('indexify', () => { // _createCompositeIndex // it('should call the _createCompositeIndex', () => { // sinon.spy(queryRef, '_createCompositeIndex'); // queryRef.indexify({ age: '27', name: 'David' }); // expect(queryRef._createCompositeIndex.calledOnce).to.be.ok; // queryRef._createCompositeIndex.restore(); // }); // _encodeCompositeIndex it('should call the _encodeCompositeIndex', () => { sinon.spy(queryRef, '_encodeCompositeIndex'); queryRef.indexify({ age: '27', name: 'David' }); expect(queryRef._encodeCompositeIndex.calledOnce).to.be.ok; queryRef._encodeCompositeIndex.restore(); }); }); });
the_stack
import * as vscode from 'vscode'; import * as path from 'path'; import { SHA256 } from 'crypto-js'; import Config from './domain/config'; import ProjectRepository from './domain/ProjectRepository'; import RecentItems from './recentItems'; import ProjectLocator from './gitProjectLocator'; import DirList from './domain/dirList'; import ProjectQuickPick from './domain/ProjectQuickPick'; const FOLDER = '\uD83D\uDCC2'; const GLOBE = '\uD83C\uDF10'; export default class GitProjectManager { config: Config; state: vscode.Memento; loadedRepoListFromFile: boolean; repoList: ProjectRepository[]; storedLists: Map<any, any>; recentList: RecentItems; /** * Creates an instance of GitProjectManager. * * @param {object} config * @param {Memento} state */ constructor(config: Config, state: vscode.Memento) { this.config = config; this.state = state; this.loadedRepoListFromFile = false; this.repoList = []; this.storedLists = new Map(); this.recentList = new RecentItems(this.state, config.recentProjectListSize); this.updateRepoList = this.updateRepoList.bind(this); this.addRepoInRepoList = this.addRepoInRepoList.bind(this); } getQuickPickList(): ProjectQuickPick[] { this.repoList = this.repoList.sort((a, b) => { return a.name > b.name ? 1 : -1; }); // let homeDir = this.getHomePath().replace(new RegExp(`${path.sep}$`), '') + path.sep; return this.repoList.map(repo => { let description = ''; if (this.config.displayProjectPath || !this.config.checkRemoteOrigin) { let repoDir = repo.directory; // if (repoDir.startsWith(homeDir)) { // repoDir = '~/' + repoDir.substring(homeDir.length); // } description = `${FOLDER} ${repoDir}`; } if (this.config.checkRemoteOrigin) { description = `${GLOBE} ${repo.repository} ` + description; } var item = new ProjectQuickPick(); item.label = repo.name; item.description = description.trim(); item.directory = repo.directory; return item; }); } handleError(error: Error): Error { vscode.window.showErrorMessage(`Error in GPM Manager ${error}`); return error; } get storeDataBetweenSessions() { return this.config.storeRepositoriesBetweenSessions; } saveList() { if (!this.storeDataBetweenSessions) { return; } const lists = Array.from(this.storedLists.entries()).reduce( (storage, [hash, repos]) => ({ ...storage, [hash]: repos }), {}, ); this.state.update('lists', lists); } loadList() { if (!this.storeDataBetweenSessions) { return false; } const list = this.state.get('lists', false); if (!list) { return false; } this.storedLists = new Map(Array.from(Object.entries(list))); this.loadedRepoListFromFile = true; return true; } saveRepositoryInfo(directories: string[]) { this.storedLists.set(this.getDirectoriesHash(directories), this.repoList); this.saveList(); } loadRepositoryInfo() { if (this.loadedRepoListFromFile) { return false; } return this.loadList(); } addRepoInRepoList(repoInfo: ProjectRepository) { let map = this.repoList.map((info) => { return info.directory; }); if (map.indexOf(repoInfo.directory) === -1) { this.repoList.push(repoInfo); } } async getProjectsFolders(subFolder: string = ''): Promise<string[]> { var isFolderConfigured = this.config.baseProjectFolders.length > 0; if (!isFolderConfigured) { throw new Error('You need to configure at least one folder in "gitProjectManager.baseProjectsFolders" before searching for projects.'); } var baseProjectsFolders: string[] = subFolder === '' ? vscode.workspace.getConfiguration('gitProjectManager').get('baseProjectsFolders') || [] : [subFolder]; var resolvedProjectsFolders = baseProjectsFolders.map(path => { return this.resolveEnvironmentVariables(process.platform, path); }); return resolvedProjectsFolders; } getHomePath() { return process.env.HOME || process.env.HOMEPATH; } resolveEnvironmentVariables(processPlatform: string, aPath: string) { var envVarMatcher = processPlatform === 'win32' ? /%([^%]+)%/g : /\$([^\/]+)/g; let resolvedPath = aPath.replace(envVarMatcher, (_, key) => process.env[key] || ''); const homePath = this.getHomePath() || ''; return resolvedPath.charAt(0) === '~' ? path.join(homePath, resolvedPath.substr(1)) : resolvedPath; }; /** * Show the list of found Git projects, and open the choosed project * * @param {Object} opts Aditional options, currently supporting only subfolders * @param {boolean} openInNewWindow If true, will open the selected project in a new windows, regardless of the OpenInNewWindow configuration * * @memberOf GitProjectManager */ async showProjectList(openInNewWindow: boolean, baseFolder?: string) { try { var options = { placeHolder: 'Select a folder to open: (it may take a few seconds to search the folders the first time)' }; var projectsPromise = this.getProjectsList(await this.getProjectsFolders(baseFolder)); var selected = await vscode.window.showQuickPick<ProjectQuickPick>(projectsPromise, options); if (selected) { this.openProject(selected, openInNewWindow); } } catch (e) { vscode.window.showInformationMessage(`Error while showing Project list: ${e}`); } }; /** * Adds all projects added as unversioned in vsCode config * * @param {DirList} dirList */ addUnversionedProjects(dirList: DirList) { let unversioned = this.config.unversionedProjects; unversioned.forEach(proj => dirList.add(proj)); return dirList.dirs; } updateRepoList(dirList: ProjectRepository[], directories: string[]) { dirList.forEach(this.addRepoInRepoList); this.saveRepositoryInfo(directories); return dirList; } async getProjectsList(directories: string[]): Promise<ProjectQuickPick[]> { this.repoList = this.storedLists.get(this.getDirectoriesHash(directories)); if (this.repoList) { return this.getQuickPickList(); } this.clearProjectList(); if (this.loadRepositoryInfo()) { this.repoList = this.storedLists.get(this.getDirectoriesHash(directories)); if (this.repoList) { return this.getQuickPickList(); } } const projectLocator = new ProjectLocator(this.config); await projectLocator.locateGitProjects(directories) .then(dirList => this.addUnversionedProjects(dirList)) .then(dirList => this.updateRepoList(dirList, directories)); return this.getQuickPickList(); }; openProject(pickedObj: ProjectQuickPick | string, openInNewWindow: boolean = false) { let projectPath = this.getProjectPath(pickedObj), uri = vscode.Uri.file(projectPath), newWindow = openInNewWindow || (this.config.openInNewWindow && !!vscode.workspace.workspaceFolders); this.recentList.addProject(projectPath, ''); vscode.commands.executeCommand('vscode.openFolder', uri, newWindow); } getProjectPath(pickedObj: ProjectQuickPick | string): string { if (pickedObj instanceof ProjectQuickPick) { return pickedObj.directory; } return pickedObj; } internalRefresh(folders: string[], suppressMessage: boolean) { this.storedLists = new Map(); this.getProjectsList(folders) .then(() => { if (!suppressMessage) { vscode.window.setStatusBarMessage('Git Project Manager - Project List Refreshed', 3000); } }) .catch((error) => { if (!suppressMessage) { this.handleError(error); } }); } clearProjectList() { this.repoList = []; } /** * Refreshs the current list of projects * @param {boolean} suppressMessage if true, no warning message will be shown. */ refreshList(suppressMessage: boolean = false) { this.clearProjectList(); this.getProjectsFolders() .then((folders) => { this.internalRefresh(folders, suppressMessage); }) .catch((error) => { if (!suppressMessage) { this.handleError(error); } }); }; refreshSpecificFolder() { var options = { placeHolder: 'Select a folder to open: (it may take a few seconds to search the folders the first time)' }; this.getProjectsFolders() .then((list) => { vscode.window.showQuickPick(list, options) .then((selection) => { if (!selection) { return; } this.internalRefresh([selection], false); }); }) .catch((error) => { console.log(error); }); }; openRecentProjects() { let self = this; if (this.recentList.list.length === 0) { vscode.window.showInformationMessage('It seems you haven\'t opened any projects using Git Project Manager extension yet!'); } vscode.window.showQuickPick(this.recentList.list.map(i => { return { label: path.basename(i.projectPath), description: i.projectPath }; })).then(selected => { if (selected) { self.openProject(selected.description); } }); } /** * Calculate a hash of directories list * * @param {String[]} directories * @returns {string} The hash of directories list * * @memberOf GitProjectManager */ getDirectoriesHash(directories: string[]) { return SHA256(directories.join('')).toString(); } showProjectsFromSubFolder() { vscode.window.showQuickPick(this.getProjectsFolders(), { canPickMany: false, placeHolder: 'Pick a folder to see the subfolder projects' }).then((folder: string | undefined) => { if (!folder) { return; } this.showProjectList(false, folder); }); } getChannelPath() { return vscode.env.appName.replace("Visual Studio ", ""); } }
the_stack
'use strict'; // tslint:disable no-unused-expression import * as vscode from 'vscode'; import * as sinon from 'sinon'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import * as path from 'path'; import * as ejs from 'ejs'; import { PreReqView } from '../../extension/webview/PreReqView'; import { View } from '../../extension/webview/View'; import { ExtensionCommands } from '../../ExtensionCommands'; import { Reporter } from '../../extension/util/Reporter'; import { ExtensionUtil } from '../../extension/util/ExtensionUtil'; import { TestUtil } from '../TestUtil'; import { DependencyManager } from '../../extension/dependencies/DependencyManager'; import { GlobalState, DEFAULT_EXTENSION_DATA, ExtensionData } from '../../extension/util/GlobalState'; import { SettingConfigurations } from '../../extension/configurations'; import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter'; import { defaultDependencies, Dependencies } from '../../extension/dependencies/Dependencies'; import { LogType } from 'ibm-blockchain-platform-common'; const should: Chai.Should = chai.should(); chai.use(sinonChai); interface VersionOverrides { docker?: string; node?: string; npm?: string; go?: string; goExtension?: string; java?: string; javaLanguageExtension?: string; javaDebuggerExtension?: string; javaTestRunnerExtension?: string; systemRequirements?: number; openssl?: string; } interface CompleteOverrides { systemRequirements?: boolean; dockerForWindows?: boolean; } const generateDependencies: any = (versions: VersionOverrides = {}, completes: CompleteOverrides = {}): Dependencies => { const dependencies: Dependencies = { ...defaultDependencies.required, ...defaultDependencies.optional }; // Add versions dependencies.node.version = versions.hasOwnProperty('node') ? versions.node : '10.15.3'; dependencies.npm.version = versions.hasOwnProperty('npm') ? versions.npm : '6.4.1'; dependencies.docker.version = versions.hasOwnProperty('docker') ? versions.docker : '17.7.0'; dependencies.go.version = versions.hasOwnProperty('go') ? versions.go : '1.13.0'; dependencies.goExtension.version = versions.hasOwnProperty('goExtension') ? versions.goExtension : '1.0.0'; dependencies.java.version = versions.hasOwnProperty('java') ? versions.java : '1.7.1'; dependencies.javaLanguageExtension.version = versions.hasOwnProperty('javaLanguageExtension') ? versions.javaLanguageExtension : '1.0.0'; dependencies.javaDebuggerExtension.version = versions.hasOwnProperty('javaDebuggerExtension') ? versions.javaDebuggerExtension : '1.0.0'; dependencies.javaTestRunnerExtension.version = versions.hasOwnProperty('javaTestRunnerExtension') ? versions.javaTestRunnerExtension : '1.0.0'; dependencies.systemRequirements.version = versions.hasOwnProperty('systemRequirements') ? versions.systemRequirements : 4; dependencies.openssl.version = versions.hasOwnProperty('openssl') ? versions.openssl : '1.0.2'; // Add complete dependencies.dockerForWindows.complete = versions.hasOwnProperty('dockerForWindows') ? completes.dockerForWindows : true; dependencies.systemRequirements.complete = versions.hasOwnProperty('systemRequirements') ? completes.systemRequirements : true; // Modify html rendering of node version dependencies.node.requiredVersion = '>=10.15.3 || >=12.13.1'; return dependencies; }; describe('PreReqView', () => { const mySandBox: sinon.SinonSandbox = sinon.createSandbox(); let context: vscode.ExtensionContext; let createWebviewPanelStub: sinon.SinonStub; let reporterStub: sinon.SinonStub; let executeCommandStub: sinon.SinonStub; before(async () => { await TestUtil.setupTests(mySandBox); }); beforeEach(async () => { context = GlobalState.getExtensionContext(); executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand'); executeCommandStub.callThrough(); createWebviewPanelStub = mySandBox.stub(vscode.window, 'createWebviewPanel'); View['openPanels'].splice(0, View['openPanels'].length); reporterStub = mySandBox.stub(Reporter.instance(), 'sendTelemetryEvent'); createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: mySandBox.stub(), asWebviewUri: mySandBox.stub() }, reveal: mySandBox.stub(), dispose: mySandBox.stub(), onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); }); afterEach(() => { mySandBox.restore(); }); it('should register and show prereq page', async () => { const preReqView: PreReqView = new PreReqView(context); await preReqView.openView(false); createWebviewPanelStub.should.have.been.called; }); it('should reveal prereq page if already open', async () => { const preReqView: PreReqView = new PreReqView(context); await preReqView.openView(true); await preReqView.openView(true); createWebviewPanelStub.should.have.been.calledOnce; should.equal(createWebviewPanelStub.getCall(1), null); }); describe('getHTMLString', () => { it('should show message that all prerequisites have been installed', async () => { const dependencies: Dependencies = generateDependencies(); const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves(dependencies); const hasPreReqsInstalledStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(true); const preReqView: PreReqView = new PreReqView(context); const webview: any = { asWebviewUri: mySandBox.stub() }; const html: string = await preReqView.getHTMLString(webview); getPreReqVersionsStub.should.have.been.calledOnce; hasPreReqsInstalledStub.should.have.been.calledOnceWith(dependencies); html.should.contain('<div id="complete-panel" class="large-panel">'); // The success message should be visible html.should.contain(`<div id="check-finish-button" class="finish" onclick="finish();">Let's Blockchain!</div>`); // The button should indicate that the dependencies have been installed html.should.contain('<span class="prereqs-number">(0)</span>'); // No missing (required) dependencies html.should.contain(JSON.stringify({ ...defaultDependencies.optional.node, version: '10.15.3' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.npm, version: '6.4.1' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.docker, version: '17.7.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.go, version: '1.13.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.goExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaLanguageExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaDebuggerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaTestRunnerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.systemRequirements, complete: true, version: 4 })); }); it(`shouldn't show message that prerequisites have been installed`, async () => { const dependencies: Dependencies = generateDependencies({ node: undefined, docker: undefined, javaLanguageExtension: undefined }); const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves(dependencies); const hasPreReqsInstalledStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(false); const preReqView: PreReqView = new PreReqView(context); const webview: any = { asWebviewUri: mySandBox.stub() }; const html: string = await preReqView.getHTMLString(webview); getPreReqVersionsStub.should.have.been.calledOnce; hasPreReqsInstalledStub.should.have.been.calledOnceWith(dependencies); html.should.contain('<div id="complete-panel" class="large-panel hidden">'); // The success message should be hidden html.should.contain(`<div id="check-finish-button" class="check" onclick="check();">Check again</div>`); // The button shouldn't indicate that everything has been installed html.should.contain('<span class="prereqs-number">(1)</span>'); // Missing (required) dependencies html.should.not.contain(JSON.stringify({ ...defaultDependencies.optional.node, version: '' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.npm, version: '6.4.1' })); html.should.not.contain(JSON.stringify({ ...defaultDependencies.required.docker, version: '' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.go, version: '1.13.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.goExtension, version: '1.0.0' })); html.should.not.contain(JSON.stringify({ ...defaultDependencies.optional.javaLanguageExtension, version: '' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaDebuggerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaTestRunnerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.systemRequirements, complete: true, version: 4 })); }); it('should be able to pass dependencies and if complete', async () => { const getPreReqVersionsSpy: sinon.SinonSpy = mySandBox.spy(DependencyManager.instance(), 'getPreReqVersions'); mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(true); const preReqView: PreReqView = new PreReqView(context); const webview: any = { asWebviewUri: mySandBox.stub() }; const dependencies: Dependencies = generateDependencies(); const html: string = await preReqView.getHTMLString(webview, dependencies, true); getPreReqVersionsSpy.should.not.have.been.called; html.should.contain('<div id="complete-panel" class="large-panel">'); // The success message should be visible html.should.contain(`<div id="check-finish-button" class="finish" onclick="finish();">Let's Blockchain!</div>`); // The button should indicate that the dependencies have been installed html.should.contain('<span class="prereqs-number">(0)</span>'); // No missing (required) dependencies html.should.contain(JSON.stringify({ ...defaultDependencies.optional.node, version: '10.15.3' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.npm, version: '6.4.1' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.docker, version: '17.7.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.go, version: '1.13.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.goExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaLanguageExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaDebuggerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaTestRunnerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.systemRequirements, complete: true, version: 4 })); }); it('should be able to pass localFabricFunctionality flag', async () => { const getPreReqVersionsSpy: sinon.SinonSpy = mySandBox.spy(DependencyManager.instance(), 'getPreReqVersions'); mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(true); const getSettingsStub: sinon.SinonStub = mySandBox.stub(); const updateSettingsStub: sinon.SinonStub = mySandBox.stub().resolves(); const getConfigurationStub: sinon.SinonStub = mySandBox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: updateSettingsStub }); const preReqView: PreReqView = new PreReqView(context); const webview: any = { asWebviewUri: mySandBox.stub() }; const dependencies: Dependencies = generateDependencies(); const html: string = await preReqView.getHTMLString(webview, dependencies, true, false); getPreReqVersionsSpy.should.not.have.been.called; getSettingsStub.should.not.have.been.calledWith(SettingConfigurations.EXTENSION_LOCAL_FABRIC); html.should.contain('<div id="complete-panel" class="large-panel">'); // The success message should be visible html.should.contain(`<div id="check-finish-button" class="finish" onclick="finish();">Let's Blockchain!</div>`); // The button should indicate that the dependencies have been installed html.should.contain('<span class="prereqs-number">(0)</span>'); // No missing (required) dependencies html.should.contain(JSON.stringify({ ...defaultDependencies.optional.node, version: '10.15.3' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.npm, version: '6.4.1' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.docker, version: '17.7.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.go, version: '1.13.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.goExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaLanguageExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaDebuggerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaTestRunnerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.systemRequirements, complete: true, version: 4 })); }); it('should handle error rendering the webview', async () => { const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves({ // These will all have version set as undefined ...defaultDependencies.required, ...defaultDependencies.optional, }); mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(false); const error: Error = new Error('error happened'); mySandBox.stub(ejs, 'renderFile').yields(error); const preReqView: PreReqView = new PreReqView(context); const webview: any = { asWebviewUri: mySandBox.stub() }; await preReqView.getHTMLString(webview).should.be.rejectedWith(error); getPreReqVersionsStub.should.have.been.calledOnce; }); it('should use the dependencies passed in through the constructor when available', async () => { const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions'); const hasPreReqsInstalledStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled'); const dependencies: Dependencies = generateDependencies(); const preReqView: PreReqView = new PreReqView(context, dependencies); const webview: any = { asWebviewUri: mySandBox.stub() }; const html: string = await preReqView.getHTMLString(webview); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.node, version: '10.15.3' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.npm, version: '6.4.1' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.docker, version: '17.7.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.go, version: '1.13.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.goExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaLanguageExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaDebuggerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.optional.javaTestRunnerExtension, version: '1.0.0' })); html.should.contain(JSON.stringify({ ...defaultDependencies.required.systemRequirements, complete: true, version: 4 })); getPreReqVersionsStub.should.not.be.called; hasPreReqsInstalledStub.should.be.calledWith(dependencies); }); }); describe('openPanelInner', () => { let logSpy: sinon.SinonSpy; let setupCommandsStub: sinon.SinonStub; let completeActivationStub: sinon.SinonStub; beforeEach(async () => { await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, false, vscode.ConfigurationTarget.Global); logSpy = mySandBox.stub(VSCodeBlockchainOutputAdapter.instance(), 'log'); setupCommandsStub = mySandBox.stub(ExtensionUtil, 'setupCommands').resolves(); completeActivationStub = mySandBox.stub(ExtensionUtil, 'completeActivation').resolves(); }); it('should dispose prereq page if the user closes the tab', async () => { mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(false); mySandBox.stub(DependencyManager.instance(), 'isValidDependency').returns(false); const onDidDisposePromises: any[] = []; executeCommandStub.withArgs(ExtensionCommands.OPEN_HOME_PAGE).resolves(); const onDidDisposeStub: sinon.SinonStub = mySandBox.stub(); onDidDisposePromises.push(new Promise((resolve: any): void => { onDidDisposeStub.onCall(0).yields(); onDidDisposeStub.onCall(1).callsFake(async (callback: any) => { await callback(); resolve(); }); })); createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: mySandBox.stub(), asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: onDidDisposeStub, onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); const preReqView: PreReqView = new PreReqView(context); await preReqView.openView(true); await Promise.all(onDidDisposePromises); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); logSpy.should.have.been.calledOnceWith(LogType.WARNING, `Required prerequisites are missing. They must be installed before the extension can be used.`); createWebviewPanelStub.should.have.been.calledOnceWith( 'preReq', 'Prerequisites', vscode.ViewColumn.One, { enableScripts: true, retainContextWhenHidden: true, enableCommandUris: true, localResourceRoots: [ vscode.Uri.file(path.join(context.extensionPath, 'resources')), vscode.Uri.file(path.join(context.extensionPath, 'build')) ] } ); }); it('should dispose prereq page and restore command hijacking', async () => { const hasPreReqsInstalledStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled'); mySandBox.stub(DependencyManager.instance(), 'isValidDependency').returns(false); const onDidDisposePromises: any[] = []; executeCommandStub.withArgs(ExtensionCommands.OPEN_HOME_PAGE).resolves(); const onDidDisposeStub: sinon.SinonStub = mySandBox.stub(); onDidDisposePromises.push(new Promise((resolve: any): void => { onDidDisposeStub.onCall(0).yields(); onDidDisposeStub.onCall(1).callsFake(async (callback: any) => { await callback(); resolve(); }); })); createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: mySandBox.stub(), asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: onDidDisposeStub, onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); const preReqView: PreReqView = new PreReqView(context); preReqView.restoreCommandHijack = true; await preReqView.openView(true); await Promise.all(onDidDisposePromises); hasPreReqsInstalledStub.should.have.been.calledOnce; reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); logSpy.should.not.have.been.calledOnceWith(LogType.WARNING, `Required prerequisites are missing. They must be installed before the extension can be used.`); setupCommandsStub.should.have.been.calledOnce; completeActivationStub.should.have.been.calledOnce; executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_HOME_PAGE); createWebviewPanelStub.should.have.been.calledOnceWith( 'preReq', 'Prerequisites', vscode.ViewColumn.One, { enableScripts: true, retainContextWhenHidden: true, enableCommandUris: true, localResourceRoots: [ vscode.Uri.file(path.join(context.extensionPath, 'resources')), vscode.Uri.file(path.join(context.extensionPath, 'build')) ] } ); }); it('should dispose prereq page if the user closes the tab, restore commands and open home page', async () => { mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(true); mySandBox.stub(DependencyManager.instance(), 'isValidDependency').returns(true); const onDidDisposePromises: any[] = []; executeCommandStub.withArgs(ExtensionCommands.OPEN_HOME_PAGE).resolves(); const onDidDisposeStub: sinon.SinonStub = mySandBox.stub(); onDidDisposePromises.push(new Promise((resolve: any): void => { onDidDisposeStub.onCall(0).yields(); onDidDisposeStub.onCall(1).callsFake(async (callback: any) => { await callback(); resolve(); }); })); createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: mySandBox.stub(), asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: onDidDisposeStub, onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); const preReqView: PreReqView = new PreReqView(context); await preReqView.openView(true); await Promise.all(onDidDisposePromises); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); logSpy.should.not.have.been.calledOnceWith(LogType.WARNING, `Required prerequisites are missing. They must be installed before the extension can be used.`); setupCommandsStub.should.have.been.calledOnce; completeActivationStub.should.have.been.calledOnce; executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_HOME_PAGE); createWebviewPanelStub.should.have.been.calledOnceWith( 'preReq', 'Prerequisites', vscode.ViewColumn.One, { enableScripts: true, retainContextWhenHidden: true, enableCommandUris: true, localResourceRoots: [ vscode.Uri.file(path.join(context.extensionPath, 'resources')), vscode.Uri.file(path.join(context.extensionPath, 'build')) ] } ); }); it('should dispose prereq page if the user closes the tab, restore commands and open home page if bypass prereq setting is true', async () => { await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global); mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled').resolves(false); mySandBox.stub(DependencyManager.instance(), 'isValidDependency').returns(false); const onDidDisposePromises: any[] = []; executeCommandStub.withArgs(ExtensionCommands.OPEN_HOME_PAGE).resolves(); const onDidDisposeStub: sinon.SinonStub = mySandBox.stub(); onDidDisposePromises.push(new Promise((resolve: any): void => { onDidDisposeStub.onCall(0).yields(); onDidDisposeStub.onCall(1).callsFake(async (callback: any) => { await callback(); resolve(); }); })); createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: mySandBox.stub(), asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: onDidDisposeStub, onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); const preReqView: PreReqView = new PreReqView(context); await preReqView.openView(true); await Promise.all(onDidDisposePromises); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); logSpy.should.not.have.been.calledOnceWith(LogType.WARNING, `Required prerequisites are missing. They must be installed before the extension can be used.`); setupCommandsStub.should.have.been.calledOnce; completeActivationStub.should.have.been.calledOnce; executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_HOME_PAGE); createWebviewPanelStub.should.have.been.calledOnceWith( 'preReq', 'Prerequisites', vscode.ViewColumn.One, { enableScripts: true, retainContextWhenHidden: true, enableCommandUris: true, localResourceRoots: [ vscode.Uri.file(path.join(context.extensionPath, 'resources')), vscode.Uri.file(path.join(context.extensionPath, 'build')) ] } ); }); it(`should handle 'finish' message`, async () => { const disposeStub: sinon.SinonStub = mySandBox.stub().returns(undefined); const onDidDisposePromises: any[] = []; onDidDisposePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: 'finish', localFabricFunctionality: true }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, dispose: disposeStub, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); })); const getSettingsStub: sinon.SinonStub = mySandBox.stub(); const updateSettingsStub: sinon.SinonStub = mySandBox.stub().resolves(); const getConfigurationStub: sinon.SinonStub = mySandBox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: updateSettingsStub }); const preReqView: PreReqView = new PreReqView(context); await preReqView.openView(true); await Promise.all(onDidDisposePromises); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); preReqView.restoreCommandHijack.should.equal(true); disposeStub.should.have.been.calledOnce; updateSettingsStub.should.have.been.calledOnceWith(SettingConfigurations.EXTENSION_LOCAL_FABRIC, true, vscode.ConfigurationTarget.Global); }); it(`should handle 'check' message where Docker for Windows has been confirmed`, async () => { const mockDependencies: Dependencies = generateDependencies({}, { systemRequirements: false, dockerForWindows: false }); const hasPreReqsInstalledStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled'); hasPreReqsInstalledStub.resolves(true); const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves(mockDependencies); mySandBox.stub(DependencyManager.instance(), 'isValidDependency').returns(false); const getGlobalStateStub: sinon.SinonStub = mySandBox.stub(GlobalState, 'get').returns(DEFAULT_EXTENSION_DATA); const updateGlobalStateStub: sinon.SinonStub = mySandBox.stub(GlobalState, 'update').resolves(); const expectedNewState: ExtensionData = DEFAULT_EXTENSION_DATA; expectedNewState.dockerForWindows = true; const expectedMockDependencies: Dependencies = mockDependencies; expectedMockDependencies.dockerForWindows.complete = true; const onDidDisposePromises: any[] = []; onDidDisposePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: 'check', dockerForWindows: true, localFabricFunctionality: true, toggle: undefined }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); })); const getSettingsStub: sinon.SinonStub = mySandBox.stub(); const updateSettingsStub: sinon.SinonStub = mySandBox.stub().resolves(); const getConfigurationStub: sinon.SinonStub = mySandBox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: updateSettingsStub }); const preReqView: PreReqView = new PreReqView(context); const getHTMLStringStub: sinon.SinonStub = mySandBox.stub(preReqView, 'getHTMLString').resolves(); await preReqView.openView(true); await Promise.all(onDidDisposePromises); updateSettingsStub.should.have.been.calledOnceWith(SettingConfigurations.EXTENSION_LOCAL_FABRIC, true, vscode.ConfigurationTarget.Global); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); getPreReqVersionsStub.should.have.been.called; getGlobalStateStub.should.have.been.calledOnce; updateGlobalStateStub.should.have.been.calledOnceWithExactly(expectedNewState); hasPreReqsInstalledStub.should.have.been.calledWith(expectedMockDependencies); getHTMLStringStub.should.have.been.calledWith(sinon.match({ asWebviewUri: sinon.match.any }), expectedMockDependencies, true, true); logSpy.should.have.been.calledWith(LogType.SUCCESS, undefined, 'Finished checking installed dependencies'); logSpy.should.not.have.been.calledWith(LogType.INFO, `Local Fabric functionality set to 'true'.`); }); it(`should handle 'check' message where System Requirements has been confirmed`, async () => { const mockDependencies: Dependencies = generateDependencies({}, { systemRequirements: false, dockerForWindows: false }); const hasPreReqsInstalledStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled'); hasPreReqsInstalledStub.resolves(true); const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves(mockDependencies); mySandBox.stub(DependencyManager.instance(), 'isValidDependency').returns(false); const getGlobalStateStub: sinon.SinonStub = mySandBox.stub(GlobalState, 'get').returns(DEFAULT_EXTENSION_DATA); const updateGlobalStateStub: sinon.SinonStub = mySandBox.stub(GlobalState, 'update').resolves(); const expectedNewState: ExtensionData = DEFAULT_EXTENSION_DATA; const expectedMockDependencies: any = mockDependencies; expectedMockDependencies.systemRequirements.complete = true; const onDidDisposePromises: any[] = []; onDidDisposePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: 'check', systemRequirements: true, localFabricFunctionality: false, toggle: 'true' }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); })); const getSettingsStub: sinon.SinonStub = mySandBox.stub(); const updateSettingsStub: sinon.SinonStub = mySandBox.stub().resolves(); const getConfigurationStub: sinon.SinonStub = mySandBox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: updateSettingsStub }); const preReqView: PreReqView = new PreReqView(context); const getHTMLStringStub: sinon.SinonStub = mySandBox.stub(preReqView, 'getHTMLString').resolves(); await preReqView.openView(true); await Promise.all(onDidDisposePromises); updateSettingsStub.should.have.been.calledOnceWith(SettingConfigurations.EXTENSION_LOCAL_FABRIC, false, vscode.ConfigurationTarget.Global); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); getPreReqVersionsStub.should.have.been.called; getGlobalStateStub.should.have.been.calledOnce; updateGlobalStateStub.should.have.been.calledOnceWithExactly(expectedNewState); hasPreReqsInstalledStub.should.have.been.calledWith(expectedMockDependencies); getHTMLStringStub.should.have.been.calledWith(sinon.match({ asWebviewUri: sinon.match.any }), expectedMockDependencies, true, false); logSpy.should.have.been.calledWith(LogType.INFO, `Local Fabric functionality set to 'false'.`); logSpy.should.have.been.calledWith(LogType.SUCCESS, undefined, 'Finished checking installed dependencies'); }); it(`should handle 'check' message where neither System Requirements nor Docker on Windows have been confirmed`, async () => { const mockDependencies: Dependencies = generateDependencies({}, { systemRequirements: false, dockerForWindows: false }); const hasPreReqsInstalledStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled'); hasPreReqsInstalledStub.resolves(true); const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves(mockDependencies); mySandBox.stub(DependencyManager.instance(), 'isValidDependency').returns(false); const getGlobalStateStub: sinon.SinonStub = mySandBox.stub(GlobalState, 'get').returns(DEFAULT_EXTENSION_DATA); const updateGlobalStateStub: sinon.SinonStub = mySandBox.stub(GlobalState, 'update').resolves(); const expectedMockDependencies: any = mockDependencies; expectedMockDependencies.systemRequirements.complete = true; const onDidDisposePromises: any[] = []; onDidDisposePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: 'check', localFabricFunctionality: false, toggle: 'true' }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); })); const getSettingsStub: sinon.SinonStub = mySandBox.stub(); const updateSettingsStub: sinon.SinonStub = mySandBox.stub().resolves(); const getConfigurationStub: sinon.SinonStub = mySandBox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: updateSettingsStub }); const preReqView: PreReqView = new PreReqView(context); const getHTMLStringStub: sinon.SinonStub = mySandBox.stub(preReqView, 'getHTMLString').resolves(); await preReqView.openView(true); await Promise.all(onDidDisposePromises); updateSettingsStub.should.have.been.calledOnceWith(SettingConfigurations.EXTENSION_LOCAL_FABRIC, false, vscode.ConfigurationTarget.Global); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); getPreReqVersionsStub.should.have.been.called; getGlobalStateStub.should.have.not.been.called; updateGlobalStateStub.should.have.not.been.called; hasPreReqsInstalledStub.should.have.been.calledWith(expectedMockDependencies); getHTMLStringStub.should.have.been.calledWith(sinon.match({ asWebviewUri: sinon.match.any }), expectedMockDependencies, true, false); logSpy.should.have.been.calledWith(LogType.INFO, `Local Fabric functionality set to 'false'.`); logSpy.should.have.been.calledWith(LogType.SUCCESS, undefined, 'Finished checking installed dependencies'); }); it(`should handle 'skip' message where dependencies are missing`, async () => { const mockDependencies: Dependencies = generateDependencies({ node: undefined, npm: undefined }); const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves(mockDependencies); const isValidDependency: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'isValidDependency'); isValidDependency.returns(true); isValidDependency.withArgs({ ...defaultDependencies.optional.node }).returns(false); isValidDependency.withArgs({ ...defaultDependencies.optional.npm}).returns(false); const disposeStub: sinon.SinonStub = mySandBox.stub(); const onDidDisposePromises: any[] = []; onDidDisposePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: 'skip', localFabricFunctionality: true }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, dispose: disposeStub, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); })); const preReqView: PreReqView = new PreReqView(context); const getHTMLStringStub: sinon.SinonStub = mySandBox.stub(preReqView, 'getHTMLString').resolves(); const getSettingsStub: sinon.SinonStub = mySandBox.stub(); const updateSettingsStub: sinon.SinonStub = mySandBox.stub().resolves(); const getConfigurationStub: sinon.SinonStub = mySandBox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: updateSettingsStub }); await preReqView.openView(true); await Promise.all(onDidDisposePromises); preReqView.restoreCommandHijack.should.equal(true); reporterStub.getCall(0).should.have.been.calledWithExactly('openedView', {name: 'Prerequisites'}); reporterStub.getCall(1).should.have.been.calledWithExactly('skipPreReqs', {node: 'missing', npm: 'missing'}); getHTMLStringStub.should.have.been.calledOnce; disposeStub.should.have.been.calledOnce; updateSettingsStub.getCall(0).should.have.been.calledWithExactly(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global); updateSettingsStub.getCall(1).should.have.been.calledWithExactly(SettingConfigurations.EXTENSION_LOCAL_FABRIC, true, vscode.ConfigurationTarget.Global); getPreReqVersionsStub.should.have.been.called; }); it(`should handle 'skip' message where all dependencies are installed`, async () => { const mockDependencies: Dependencies = generateDependencies(); const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions').resolves(mockDependencies); const isValidDependency: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'isValidDependency'); isValidDependency.returns(true); const disposeStub: sinon.SinonStub = mySandBox.stub(); const onDidDisposePromises: any[] = []; onDidDisposePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: 'skip', localFabricFunctionality: false }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, dispose: disposeStub, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); })); const preReqView: PreReqView = new PreReqView(context); const getHTMLStringStub: sinon.SinonStub = mySandBox.stub(preReqView, 'getHTMLString').resolves(); const getSettingsStub: sinon.SinonStub = mySandBox.stub(); const updateSettingsStub: sinon.SinonStub = mySandBox.stub().resolves(); const getConfigurationStub: sinon.SinonStub = mySandBox.stub(vscode.workspace, 'getConfiguration'); getConfigurationStub.returns({ get: getSettingsStub, update: updateSettingsStub }); await preReqView.openView(true); await Promise.all(onDidDisposePromises); preReqView.restoreCommandHijack.should.equal(true); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); getHTMLStringStub.should.have.been.calledOnce; disposeStub.should.have.been.calledOnce; updateSettingsStub.getCall(0).should.have.been.calledWithExactly(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global); updateSettingsStub.getCall(1).should.have.been.calledWithExactly(SettingConfigurations.EXTENSION_LOCAL_FABRIC, false, vscode.ConfigurationTarget.Global); getPreReqVersionsStub.should.have.been.called; }); it(`should handle unknown command`, async () => { const getPreReqVersionsStub: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'getPreReqVersions'); const isValidDependency: sinon.SinonStub = mySandBox.stub(DependencyManager.instance(), 'isValidDependency'); isValidDependency.returns(true); const onDidDisposePromises: any[] = []; onDidDisposePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ title: 'Prerequisites', webview: { onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: 'unknown-command' }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub(), _isDisposed: false }); })); const preReqView: PreReqView = new PreReqView(context); const getHTMLStringStub: sinon.SinonStub = mySandBox.stub(preReqView, 'getHTMLString').resolves(); await preReqView.openView(true); await Promise.all(onDidDisposePromises); reporterStub.should.have.been.calledOnceWithExactly('openedView', {name: 'Prerequisites'}); getHTMLStringStub.should.have.been.calledOnce; getPreReqVersionsStub.should.not.have.been.called; }); }); });
the_stack
import { action, computed, flow, makeObservable, observable, runInAction, } from "mobx"; import { ChainInfoInner, ChainStore as BaseChainStore, } from "@keplr-wallet/stores"; import { ChainInfo } from "@keplr-wallet/types"; import { ChainInfoWithEmbed, GetChainInfosMsg, RemoveSuggestedChainInfoMsg, TryUpdateChainMsg, } from "@keplr-wallet/background"; import { BACKGROUND_PORT, MessageRequester } from "@keplr-wallet/router"; import { KVStore, toGenerator } from "@keplr-wallet/common"; import { AppChainInfo } from "../../config"; import { ChainIdHelper } from "@keplr-wallet/cosmos"; import { Vibration } from "react-native"; import { stableSort } from "../../utils/stable-sort"; class ObservableKVStore<Value> { @observable.ref protected _value: Value | undefined; constructor( protected readonly kvStore: KVStore, protected readonly _key: string, protected readonly storeOptions: { onInit?: () => void; } = {} ) { makeObservable(this); this.init(); } async init() { const value = await this.kvStore.get<Value>(this.key); runInAction(() => { this._value = value; }); if (this.storeOptions.onInit) { this.storeOptions.onInit(); } } get key(): string { return this._key; } get value(): Value | undefined { return this._value; } async setValue(value: Value | undefined) { runInAction(() => { this._value = value; }); await this.kvStore.set(this.key, value); } } export class ChainStore extends BaseChainStore< ChainInfoWithEmbed & AppChainInfo > { @observable protected selectedChainId: string; @observable protected _isInitializing: boolean = false; protected deferChainIdSelect: string = ""; protected chainInfoInUIConfig: ObservableKVStore<{ // Any chains that's not disabled is classified as an enabled chain. // This array manages the sorting order of enabled chain(anything not in the disabledChains) used in the UI. // Anything not included in neither sortedEnabledChains and disabledChains would go to the very end of enabled chains in the UI. // Array of chain identifiers sortedEnabledChains: string[]; // This array is what actually controls the enabled and disabled chains. // This array also controls the sorting order of the disabled chains showed in the UI. // Array of chain identifiers disabledChains: string[]; }>; constructor( embedChainInfos: ChainInfo[], protected readonly requester: MessageRequester, protected readonly kvStore: KVStore ) { super( embedChainInfos.map((chainInfo) => { return { ...chainInfo, ...{ embeded: true, }, }; }) ); this.selectedChainId = embedChainInfos[0].chainId; this.chainInfoInUIConfig = new ObservableKVStore( kvStore, "chain_info_in_ui_config", { onInit: () => { if (!this.chainInfoInUIConfig.value) { this.chainInfoInUIConfig.setValue({ sortedEnabledChains: this.chainInfos .filter((chainInfo) => !chainInfo.raw.hideInUI) .map((chainInfo) => { const chainIdentifier = ChainIdHelper.parse( chainInfo.chainId ); return chainIdentifier.identifier; }), disabledChains: [], }); } }, } ); makeObservable(this); this.init(); } get isInitializing(): boolean { return this._isInitializing; } @computed get chainInfosInUI() { return this.enabledChainInfosInUI; } @computed get chainInfosWithUIConfig() { return this.enabledChainInfosInUI .map((chainInfo) => { return { chainInfo, disabled: false, }; }) .concat( this.disabledChainInfosInUI.map((chainInfo) => { return { chainInfo, disabled: true, }; }) ); } @computed protected get enabledChainInfosInUI() { const chainSortInfo: Record<string, number | undefined> = this.chainInfoInUIConfig.value?.sortedEnabledChains.reduce< Record<string, number | undefined> >((previous, current, index) => { previous[current] = index; return previous; }, {}) ?? {}; const disabledChainsMap: Record<string, boolean | undefined> = this.chainInfoInUIConfig.value?.disabledChains.reduce< Record<string, boolean | undefined> >((previous, current) => { previous[current] = true; return previous; }, {}) ?? {}; const chainSortFn = ( chainInfo1: ChainInfoInner, chainInfo2: ChainInfoInner ): number => { const chainIdentifier1 = ChainIdHelper.parse(chainInfo1.chainId); const chainIdentifier2 = ChainIdHelper.parse(chainInfo2.chainId); const index1 = chainSortInfo[chainIdentifier1.identifier]; const index2 = chainSortInfo[chainIdentifier2.identifier]; if (index1 == null) { if (index2 == null) { return 0; } else { return 1; } } if (index2 == null) { return -1; } return index1 < index2 ? -1 : 1; }; return stableSort( this.chainInfos .filter((chainInfo) => !chainInfo.raw.hideInUI) .filter( (chainInfo) => !disabledChainsMap[ ChainIdHelper.parse(chainInfo.chainId).identifier ] ), chainSortFn ); } @computed protected get disabledChainInfosInUI() { const chainSortInfo: Record<string, number | undefined> = this.chainInfoInUIConfig.value?.disabledChains.reduce< Record<string, number | undefined> >((previous, current, index) => { previous[current] = index; return previous; }, {}) ?? {}; const disabledChainsMap: Record<string, boolean | undefined> = this.chainInfoInUIConfig.value?.disabledChains.reduce< Record<string, boolean | undefined> >((previous, current) => { previous[current] = true; return previous; }, {}) ?? {}; const chainSortFn = ( chainInfo1: ChainInfoInner, chainInfo2: ChainInfoInner ): number => { const chainIdentifier1 = ChainIdHelper.parse(chainInfo1.chainId); const chainIdentifier2 = ChainIdHelper.parse(chainInfo2.chainId); const index1 = chainSortInfo[chainIdentifier1.identifier]; const index2 = chainSortInfo[chainIdentifier2.identifier]; if (index1 == null) { if (index2 == null) { return 0; } else { return 1; } } if (index2 == null) { return -1; } return index1 < index2 ? -1 : 1; }; return stableSort( this.chainInfos .filter((chainInfo) => !chainInfo.raw.hideInUI) .filter( (chainInfo) => disabledChainsMap[ChainIdHelper.parse(chainInfo.chainId).identifier] ), chainSortFn ); } setChainInfosInUIOrder(chainIds: string[]) { chainIds = chainIds.map( (chainId) => ChainIdHelper.parse(chainId).identifier ); const enabledChainsMap: Record< string, boolean | undefined > = this.enabledChainInfosInUI.reduce<Record<string, boolean | undefined>>( (previous, current) => { previous[ChainIdHelper.parse(current.chainId).identifier] = true; return previous; }, {} ); const disabledChainsMap: Record< string, boolean | undefined > = this.disabledChainInfosInUI.reduce<Record<string, boolean | undefined>>( (previous, current) => { previous[ChainIdHelper.parse(current.chainId).identifier] = true; return previous; }, {} ); // No need to wait this.chainInfoInUIConfig.setValue({ sortedEnabledChains: chainIds.filter( (chainIdentifier) => enabledChainsMap[chainIdentifier] ), disabledChains: chainIds.filter( (chainIdentifier) => disabledChainsMap[chainIdentifier] ), }); } toggleChainInfoInUI(chainId: string) { chainId = ChainIdHelper.parse(chainId).identifier; if (this.chainInfoInUIConfig.value) { const i = this.chainInfoInUIConfig.value.disabledChains.indexOf(chainId); if (i >= 0) { const disabledChains = this.chainInfoInUIConfig.value.disabledChains.slice(); disabledChains.splice(i, 1); // No need to wait this.chainInfoInUIConfig.setValue({ sortedEnabledChains: [ ...this.chainInfoInUIConfig.value.sortedEnabledChains, chainId, ], disabledChains: disabledChains, }); } else { const chainInfosInUI = this.chainInfosInUI; if (chainInfosInUI.length === 1) { // Can't turn off all chain. Vibration.vibrate(); return; } if (ChainIdHelper.parse(this.current.chainId).identifier === chainId) { // If user wants to turn off the selected chain, // change the selected chain. const other = chainInfosInUI.find( (chainInfo) => ChainIdHelper.parse(chainInfo.chainId).identifier !== chainId ); if (other) { this.selectChain(other.chainId); // No need to wait this.saveLastViewChainId(); } } const sortedEnabledChains = this.chainInfoInUIConfig.value.sortedEnabledChains.slice(); const i = this.chainInfoInUIConfig.value.sortedEnabledChains.indexOf( chainId ); if (i >= 0) { sortedEnabledChains.splice(i, 1); } // No need to wait this.chainInfoInUIConfig.setValue({ sortedEnabledChains, disabledChains: [ chainId, ...this.chainInfoInUIConfig.value.disabledChains, ], }); } } } @action selectChain(chainId: string) { if (this._isInitializing) { this.deferChainIdSelect = chainId; } this.selectedChainId = chainId; } @computed get current(): ChainInfoWithEmbed { if (this.hasChain(this.selectedChainId)) { return this.getChain(this.selectedChainId).raw; } return this.chainInfos[0].raw; } async saveLastViewChainId() { // Save last view chain id to kv store await this.kvStore.set<string>("last_view_chain_id", this.selectedChainId); } @flow protected *init() { this._isInitializing = true; yield this.getChainInfosFromBackground(); // Get last view chain id from kv store const lastViewChainId = yield* toGenerator( this.kvStore.get<string>("last_view_chain_id") ); if (!this.deferChainIdSelect) { if (lastViewChainId) { this.selectChain(lastViewChainId); } } this._isInitializing = false; if (this.deferChainIdSelect) { this.selectChain(this.deferChainIdSelect); this.deferChainIdSelect = ""; } } @flow protected *getChainInfosFromBackground() { const msg = new GetChainInfosMsg(); const result = yield* toGenerator( this.requester.sendMessage(BACKGROUND_PORT, msg) ); this.setChainInfos(result.chainInfos); } @flow *removeChainInfo(chainId: string) { const msg = new RemoveSuggestedChainInfoMsg(chainId); const chainInfos = yield* toGenerator( this.requester.sendMessage(BACKGROUND_PORT, msg) ); this.setChainInfos(chainInfos); } @flow *tryUpdateChain(chainId: string) { const msg = new TryUpdateChainMsg(chainId); yield this.requester.sendMessage(BACKGROUND_PORT, msg); yield this.getChainInfosFromBackground(); } }
the_stack
import loadStatsBasketball, { BasketballStats } from "./loadStats.basketball"; import { helpers, PHASE, PLAYER } from "../../../common"; import type { GetLeagueOptions, PlayerContract, PlayerInjury, } from "../../../common/types"; import { LATEST_SEASON, LATEST_SEASON_WITH_DRAFT_POSITIONS } from "./getLeague"; import getOnlyRatings from "./getOnlyRatings"; import type { Basketball, Ratings } from "./loadData.basketball"; import nerfDraftProspect from "./nerfDraftProspect"; import oldAbbrevTo2020BBGMAbbrev from "./oldAbbrevTo2020BBGMAbbrev"; import setDraftProspectRatingsBasedOnDraftPosition from "./setDraftProspectRatingsBasedOnDraftPosition"; import { getEWA } from "../../util/advStats.basketball"; const MINUTES_PER_GAME = 48; const formatPlayerFactory = async ( basketball: Basketball, options: GetLeagueOptions, season: number, teams: { tid: number; srID?: string; }[], initialPid: number, ) => { let pid = initialPid; let basketballStats: BasketballStats | undefined; if (options.type === "real" && options.realStats !== "none") { basketballStats = await loadStatsBasketball(); } const tidCache: Record<string, number | undefined> = {}; const getTidNormal = (abbrev?: string): number | undefined => { if (abbrev === undefined) { return; } if (tidCache.hasOwnProperty(abbrev)) { return tidCache[abbrev]; } const t = teams.find( t => t.srID !== undefined && oldAbbrevTo2020BBGMAbbrev(t.srID) === abbrev, ); const tid = t?.tid; tidCache[abbrev] = tid; return tid; }; return ( ratingsInput: Ratings[] | Ratings, { draftProspect, legends, hasQueens, randomDebuts, }: { draftProspect?: boolean; legends?: boolean; hasQueens?: boolean; randomDebuts?: boolean; } = {}, ) => { const allRatings = Array.isArray(ratingsInput) ? ratingsInput : [ratingsInput]; const ratings = allRatings.at(-1); const slug = ratings.slug; const bio = basketball.bios[slug]; if (!bio) { throw new Error(`No bio found for "${slug}"`); } // For alexnoob draft prospects who already have their draft ratings set for the correct season, as opposed to other rookies who need them set based on their rookie ratings const draftRatingsAlreadySet = bio.draftYear === ratings.season; let draft; if (draftProspect || legends) { draft = { tid: -1, originalTid: -1, round: 0, pick: 0, year: legends ? season - 1 : draftRatingsAlreadySet ? ratings.season : ratings.season - 1, }; } else { let draftTid; const draftTeam = teams.find( t => t.srID !== undefined && oldAbbrevTo2020BBGMAbbrev(t.srID) === bio.draftAbbrev, ); if (draftTeam) { draftTid = draftTeam.tid; } else { draftTid = -1; } draft = { tid: draftTid, originalTid: draftTid, round: bio.draftRound, pick: bio.draftPick, year: bio.draftYear, }; } let tid: number; let jerseyNumber: string | undefined; if (draftProspect) { tid = PLAYER.UNDRAFTED; } else if (!legends && ratings.season < season) { tid = PLAYER.RETIRED; } else { tid = PLAYER.FREE_AGENT; let statsRow; if (options.type === "real" && options.phase >= PHASE.PLAYOFFS) { // Search backwards - last team a player was on that season for (let i = basketball.teams.length - 1; i >= 0; i--) { const row = basketball.teams[i]; if ( row.slug === slug && row.season === ratings.season && (row.phase === undefined || options.phase >= row.phase) ) { statsRow = row; break; } } } else { // Search forwards - first team a player was on that season statsRow = basketball.teams.find( row => row.slug === slug && row.season === ratings.season, ); } const abbrev = statsRow ? statsRow.abbrev : ratings.abbrev_if_new_row; if (statsRow) { jerseyNumber = statsRow.jerseyNumber; } if (legends) { const team = teams.find(t => { if (hasQueens && abbrev === "NOL" && ratings.season < 2003) { return ( t.srID !== undefined && oldAbbrevTo2020BBGMAbbrev(t.srID) === "CHA" ); } return ( t.srID !== undefined && oldAbbrevTo2020BBGMAbbrev(t.srID) === abbrev ); }); tid = team ? team.tid : PLAYER.FREE_AGENT; } else { const newTid = getTidNormal(abbrev); if (newTid !== undefined) { tid = newTid; } } } if (jerseyNumber === undefined && tid !== PLAYER.RETIRED) { // Fallback (mostly for draft prospects) - pick first number in database const statsRow2 = basketball.teams.find(row => row.slug === slug); if (statsRow2) { jerseyNumber = statsRow2.jerseyNumber; } } if (tid >= PLAYER.FREE_AGENT && !draftProspect) { // Ensure draft year is before the current season, because for some players like Irv Rothenberg this is not true if ( draft.year > season || (draft.year === season && (options.type === "legends" || options.phase <= PHASE.DRAFT)) ) { draft = { tid: -1, originalTid: -1, round: 0, pick: 0, year: season - 1, }; } } let contract: PlayerContract | undefined; let awards; let salaries; if (legends) { contract = { amount: 6000, exp: season + 3, }; } else if (!randomDebuts) { const salaryRows = basketball.salaries.filter(row => { if (row.slug !== slug) { return false; } // Auto-apply extensions, otherwise will feel weird if (season >= LATEST_SEASON) { return true; } return row.start <= season; }); if (salaryRows.length > 0 && !draftProspect) { // Complicated stuff rather than just taking last entry because these can be out of order, particularly due to merging data sources. But still search backwards let salaryRow; for (let i = salaryRows.length - 1; i >= 0; i--) { const row = salaryRows[i]; if (row.start <= season && row.exp >= season) { salaryRow = row; break; } } if (season >= LATEST_SEASON) { // Auto-apply extensions, otherwise will feel weird const salaryRowExtension = salaryRows.find(row => row.start > season); if (salaryRowExtension) { salaryRow = salaryRowExtension; } } if (salaryRow) { contract = { amount: salaryRow.amount / 1000, exp: salaryRow.exp, }; if (contract.exp > season + 4) { // Bound at 5 year contract contract.exp = season + 4; } if (salaryRow.start === draft.year + 1) { contract.rookie = true; } } salaries = []; for (const row of salaryRows) { for (let season = row.start; season <= row.exp; season++) { salaries.push({ amount: row.amount / 1000, season, }); } } } const allAwards = basketball.awards[slug]; const awardsCutoffSeason = options.type === "real" && options.phase > PHASE.PLAYOFFS ? season + 1 : season; awards = allAwards && !draftProspect ? helpers.deepCopy( allAwards.filter( award => award.season < awardsCutoffSeason || (options.type === "real" && options.phase === PHASE.PLAYOFFS && award.season < awardsCutoffSeason + 1 && (award.type.includes("All-Star") || award.type === "Slam Dunk Contest Winner" || award.type === "Three-Point Contest Winner")), ), ) : undefined; } let bornYear; if (legends) { const age = ratings.season - bio.bornYear; bornYear = season - age; } else { bornYear = bio.bornYear; } // Whitelist, to get rid of any other columns const processedRatings = allRatings.map(row => getOnlyRatings(row, true)); const addDummyRookieRatings = !draftProspect && options.type === "real" && (options.realStats === "all" || options.realStats === "allActive" || options.realStats === "allActiveHOF") && processedRatings[0].season !== draft.year; if (addDummyRookieRatings) { processedRatings.unshift({ ...processedRatings[0], season: draft.year, }); } if (draftProspect || addDummyRookieRatings) { const currentRatings = processedRatings[0]; if (!draftRatingsAlreadySet) { nerfDraftProspect(currentRatings); } if ( options.type === "real" && options.realDraftRatings === "draft" && draft.year <= LATEST_SEASON_WITH_DRAFT_POSITIONS ) { const age = currentRatings.season! - bornYear; setDraftProspectRatingsBasedOnDraftPosition(currentRatings, age, bio); } } const name = legends ? `${bio.name} ${ratings.season}` : bio.name; type StatsRow = Omit< BasketballStats[number], "slug" | "abbrev" | "playoffs" > & { playoffs: boolean; tid: number; minAvailable: number; ewa: number; }; let stats: StatsRow[] | undefined; if (options.type === "real" && basketballStats) { let statsTemp: BasketballStats | undefined; const statsSeason = options.phase > PHASE.REGULAR_SEASON ? options.season : options.season - 1; const includePlayoffs = options.phase !== PHASE.PLAYOFFS; if (options.realStats === "lastSeason") { statsTemp = basketballStats.filter( row => row.slug === slug && row.season === statsSeason && (includePlayoffs || !row.playoffs), ); } else if ( options.realStats === "allActiveHOF" || options.realStats === "allActive" || options.realStats === "all" ) { statsTemp = basketballStats.filter( row => row.slug === slug && row.season <= statsSeason && (includePlayoffs || !row.playoffs || row.season < statsSeason), ); } if (statsTemp && statsTemp.length > 0) { stats = statsTemp.map(row => { let tid = getTidNormal(row.abbrev); if (tid === undefined) { // Team was disbanded tid = PLAYER.DOES_NOT_EXIST; } const newRow: StatsRow = { ...row, playoffs: !!row.playoffs, tid, minAvailable: (row.gp ?? 0) * MINUTES_PER_GAME, ewa: getEWA(row.per ?? 0, row.min ?? 0, bio.pos), }; delete (newRow as any).slug; delete (newRow as any).abbrev; return newRow; }); } } const hof = !!awards && awards.some(award => award.type === "Inducted into the Hall of Fame"); const retiredYear = tid === PLAYER.RETIRED ? ratings.season : Infinity; const diedYear = tid === PLAYER.RETIRED ? bio.diedYear : undefined; pid += 1; return { pid, name, pos: bio.pos, college: bio.college, born: { year: bornYear, loc: bio.country, }, diedYear, weight: bio.weight, hgt: bio.height, tid, imgURL: "/img/blank-face.png", real: true, draft, ratings: processedRatings, stats, injury: undefined as PlayerInjury | undefined, contract, salaries, awards, jerseyNumber, hof, retiredYear, srID: ratings.slug, }; }; }; export default formatPlayerFactory;
the_stack
import * as React from 'react'; import { shallowEqual } from 'react-redux'; import { getTextResourceByKey } from 'altinn-shared/utils'; import { ILabelSettings, ITextResource, Triggers, IComponentValidations, } from 'src/types'; import { Grid, makeStyles } from '@material-ui/core'; import classNames from 'classnames'; import components from '.'; import FormDataActions from '../features/form/data/formDataActions'; import { IDataModelBindings, IGrid, IGridStyling, ITextResourceBindings, } from '../features/form/layout'; import RuleActions from '../features/form/rules/rulesActions'; import { setCurrentSingleFieldValidation } from '../features/form/validation/validationSlice'; import { makeGetFocus, makeGetHidden } from '../selectors/getLayoutData'; import Label from '../features/form/components/Label'; import Legend from '../features/form/components/Legend'; import { renderValidationMessagesForComponent } from '../utils/render'; import { getFormDataForComponent, isSimpleComponent, componentHasValidationMessages, getTextResource, isComponentValid, selectComponentTexts, } from '../utils/formComponentUtils'; import { FormLayoutActions } from '../features/form/layout/formLayoutSlice'; import Description from '../features/form/components/Description'; import { useAppDispatch, useAppSelector } from 'src/common/hooks'; import { ILanguage } from 'altinn-shared/types'; export interface IGenericComponentProps { id: string; type: string; textResourceBindings: ITextResourceBindings; dataModelBindings: IDataModelBindings; componentValidations?: IComponentValidations; readOnly?: boolean; required?: boolean; labelSettings?: ILabelSettings; grid?: IGrid; triggers?: Triggers[]; hidden?: boolean; } const useStyles = makeStyles((theme) => ({ container: { '@media print': { display: 'flex !important', }, }, xs: { 'border-bottom': '1px dashed #949494', }, sm: { [theme.breakpoints.up('sm')]: { 'border-bottom': '1px dashed #949494', }, }, md: { [theme.breakpoints.up('md')]: { 'border-bottom': '1px dashed #949494', }, }, lg: { [theme.breakpoints.up('lg')]: { 'border-bottom': '1px dashed #949494', }, }, xl: { [theme.breakpoints.up('xl')]: { 'border-bottom': '1px dashed #949494', }, }, })); export function GenericComponent(props: IGenericComponentProps) { const { id, ...passThroughProps } = props; const dispatch = useAppDispatch(); const classes = useStyles(props); const GetHiddenSelector = makeGetHidden(); const GetFocusSelector = makeGetFocus(); const [isSimple, setIsSimple] = React.useState(true); const [hasValidationMessages, setHasValidationMessages] = React.useState(false); const formData = useAppSelector( state => getFormDataForComponent(state.formData.formData, props.dataModelBindings), shallowEqual, ); const currentView: string = useAppSelector( state => state.formLayout.uiConfig.currentView, ); const isValid = useAppSelector(state => isComponentValid( state.formValidations.validations[currentView]?.[props.id], ), ); const language = useAppSelector(state => state.language.language); const textResources: ITextResource[] = useAppSelector(state => state.textResources.resources); const texts: any = useAppSelector(state => selectComponentTexts( state.textResources.resources, props.textResourceBindings, ), ); const hidden = useAppSelector(state => props.hidden || GetHiddenSelector(state, props)); const shouldFocus = useAppSelector(state => GetFocusSelector(state, props)); const componentValidations = useAppSelector( state => state.formValidations.validations[currentView]?.[props.id], shallowEqual, ); React.useEffect(() => { setIsSimple(isSimpleComponent(props.dataModelBindings, props.type)); }, []); React.useEffect(() => { setHasValidationMessages( componentHasValidationMessages(componentValidations), ); }, [componentValidations]); if (hidden) { return null; } const handleDataUpdate = (value: any, key = 'simpleBinding') => { if (!props.dataModelBindings || !props.dataModelBindings[key]) { return; } if (props.readOnly) { return; } if (formData instanceof Object) { if (formData[key] && formData[key] === value) { // data unchanged, do nothing return; } } else if (formData && formData === value) { // data unchanged, do nothing return; } const dataModelBinding = props.dataModelBindings[key]; if (props.triggers && props.triggers.includes(Triggers.Validation)) { dispatch( setCurrentSingleFieldValidation({ dataModelBinding, componentId: props.id, layoutId: currentView, }), ); } dispatch( FormDataActions.updateFormData({ field: dataModelBinding, data: value, componentId: props.id, }), ); RuleActions.checkIfRuleShouldRun( props.id, props.dataModelBindings[key], value, ); }; const handleFocusUpdate = (componentId: string, step?: number) => { dispatch( FormLayoutActions.updateFocus({ currentComponentId: componentId, step: step || 0, }), ); }; const getValidationsForInternalHandling = () => { if ( props.type === 'AddressComponent' || props.type === 'Datepicker' || props.type === 'FileUpload' ) { return componentValidations; } return null; }; // some components handle their validations internally (i.e merge with internal validation state) const internalComponentValidations = getValidationsForInternalHandling(); if (internalComponentValidations !== null) { passThroughProps.componentValidations = internalComponentValidations; } const RenderComponent = components.find( (componentCandidate) => componentCandidate.name === props.type, ).Tag; const RenderLabel = () => { return ( <RenderLabelScoped props={props} passThroughProps={passThroughProps} language={language} texts={texts} /> ); }; const RenderDescription = () => { // eslint-disable-next-line react/prop-types if (!props.textResourceBindings.description) { return null; } return ( <Description // eslint-disable-next-line react/prop-types key={`description-${props.id}`} description={texts.description} id={id} {...passThroughProps} /> ); }; const RenderLegend = () => { return ( <Legend // eslint-disable-next-line react/prop-types key={`legend-${props.id}`} labelText={texts.title} descriptionText={texts.description} helpText={texts.help} language={language} {...props} {...passThroughProps} /> ); }; const getText = () => { if (props.type === 'Header') { // disabled markdown parsing return getTextResourceByKey( props.textResourceBindings.title, textResources, ); } return texts.title; }; const getTextResourceWrapper = (key: string) => { return getTextResource(key, textResources); }; const getTextResourceAsString = (key: string) => { return getTextResourceByKey(key, textResources); }; const componentProps = { handleDataChange: handleDataUpdate, handleFocusUpdate, getTextResource: getTextResourceWrapper, getTextResourceAsString, formData, isValid, language, id, shouldFocus, text: getText(), label: RenderLabel, legend: RenderLegend, ...passThroughProps, }; const noLabelComponents: string[] = [ 'Header', 'Paragraph', 'Image', 'Submit', 'ThirdParty', 'AddressComponent', 'Button', 'Checkboxes', 'RadioButtons', 'AttachmentList', 'InstantiationButton' ]; return ( <Grid item={true} container={true} xs={props.grid?.xs || 12} sm={props.grid?.sm || false} md={props.grid?.md || false} lg={props.grid?.lg || false} xl={props.grid?.xl || false} key={`grid-${props.id}`} className={ classNames('form-group', 'a-form-group', classes.container, gridToHiddenProps(props.grid?.labelGrid, classes)) } alignItems='baseline' > {!noLabelComponents.includes(props.type) && ( <Grid item={true} xs={props.grid?.labelGrid?.xs || 12} sm={props.grid?.labelGrid?.sm || false} md={props.grid?.labelGrid?.md || false} lg={props.grid?.labelGrid?.lg || false} xl={props.grid?.labelGrid?.xl || false} > <RenderLabelScoped props={props} passThroughProps={passThroughProps} language={language} texts={texts} /> <RenderDescription key={`description-${props.id}`} /> </Grid> )} <Grid key={`form-content-${props.id}`} item={true} id={`form-content-${props.id}`} xs={props.grid?.innerGrid?.xs || 12} sm={props.grid?.innerGrid?.sm || false} md={props.grid?.innerGrid?.md || false} lg={props.grid?.innerGrid?.lg || false} xl={props.grid?.innerGrid?.xl || false} > <RenderComponent {...componentProps} /> {isSimple && hasValidationMessages && renderValidationMessagesForComponent( componentValidations?.simpleBinding, props.id, )} </Grid> </Grid> ); } interface IRenderLabelProps { texts: any; language: ILanguage; props: any; passThroughProps: any; } const RenderLabelScoped = (props: IRenderLabelProps) => { return ( <Label key={`label-${props.props.id}`} labelText={props.texts.title} helpText={props.texts.help} language={props.language} {...props.props} {...props.passThroughProps} /> ); }; const gridToHiddenProps = (labelGrid: IGridStyling, classes: ReturnType<typeof useStyles>) => { if (!labelGrid) return undefined; return { [classes.xs]: labelGrid.xs > 0 && labelGrid.xs < 12, [classes.sm]: labelGrid.sm > 0 && labelGrid.sm < 12, [classes.md]: labelGrid.md > 0 && labelGrid.md < 12, [classes.lg]: labelGrid.lg > 0 && labelGrid.lg < 12, [classes.xl]: labelGrid.xl > 0 && labelGrid.xl < 12, }; }; export default GenericComponent;
the_stack
import { AxisRenderer, IAxisRendererSettings, IAxisRendererPrivate } from "./AxisRenderer"; import { p100 } from "../../../core/util/Percent"; import type { IPoint } from "../../../core/util/IPoint"; import * as $type from "../../../core/util/Type"; import * as $utils from "../../../core/util/Utils"; import type { AxisLabel } from "./AxisLabel"; import type { Grid } from "./Grid"; import type { AxisTick } from "./AxisTick"; import type { Graphics } from "../../../core/render/Graphics"; import type { Tooltip } from "../../../core/render/Tooltip"; import type { Template } from "../../../core/util/Template"; import type { AxisBullet } from "./AxisBullet"; import { Rectangle } from "../../../core/render/Rectangle"; export interface IAxisRendererXSettings extends IAxisRendererSettings { /** * If set to `true` the axis will be drawn on the opposite side of the plot * area. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Axis_position} for more info * @default false */ opposite?: boolean; /** * If set to `true`, all axis elements (ticks, labels) will be drawn inside * plot area. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Labels_ticks_inside_plot_area} for more info * @default false */ inside?: boolean; } export interface IAxisRendererXPrivate extends IAxisRendererPrivate { } /** * Used to render horizontal axis. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/#Axis_renderer} for more info * @important */ export class AxisRendererX extends AxisRenderer { public static className: string = "AxisRendererX"; public static classNames: Array<string> = AxisRenderer.classNames.concat([AxisRendererX.className]); declare public _settings: IAxisRendererXSettings; declare public _privateSettings: IAxisRendererXPrivate; declare public readonly labelTemplate: Template<AxisLabel>; public thumb: Rectangle = Rectangle.new(this._root, { width: p100, themeTags: ["axis", "x", "thumb"] }); public _afterNew() { this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["renderer", "x"]); super._afterNew(); this.setPrivateRaw("letter", "X"); const gridTemplate = this.grid.template; gridTemplate.set("height", p100); gridTemplate.set("width", 0); gridTemplate.set("draw", (display, graphics) => { display.moveTo(0, 0); display.lineTo(0, graphics.height()); }); this.set("draw", (display, graphics) => { display.moveTo(0, 0); display.lineTo(graphics.width(), 0); }); } public _changed() { super._changed(); const axis = this.axis; if (this.isDirty("inside")) { axis.markDirtySize(); } const opposite = "opposite" if (this.isDirty(opposite)) { const chart = this.chart; if (chart) { const axisChildren = axis.children; if (this.get(opposite)) { const children = chart.topAxesContainer.children; if (children.indexOf(axis) == -1) { children.insertIndex(0, axis); } axisChildren.moveValue(this); axis.addTag(opposite); } else { const children = chart.bottomAxesContainer.children; if (children.indexOf(axis) == -1) { children.moveValue(axis); } axisChildren.moveValue(this, 0); axis.removeTag(opposite); } axis.markDirtySize(); } axis.ghostLabel._applyThemes(); } this.thumb.setPrivate("height", axis.labelsContainer.height()); } protected _getPan(point1: IPoint, point2: IPoint): number { return (point2.x - point1.x) / this.width(); } public toAxisPosition(position: number): number { const start = this._start || 0; const end = this._end || 1; position -= this._ls; position = position * (end - start) / this._lc; if (!this.get("inversed")) { position = start + position; } else { position = end - position; } return position; } public _updateLC() { const axis = this.axis; const parent = axis.parent; if (parent) { const w = parent.innerWidth(); this._lc = this.axisLength() / w; this._ls = (axis.x() - parent.get("paddingLeft", 0)) / w; } } public _updatePositions() { const axis = this.axis; axis.gridContainer.set("x", axis.x() - $utils.relativeToValue(axis.get("centerX", 0), axis.width()) - axis.parent!.get("paddingLeft", 0)); axis.bulletsContainer.set("y", this.y()); const chart = axis.chart; if (chart) { const plotContainer = chart.plotContainer; const axisHeader = axis.axisHeader; let width = axis.get("marginLeft", 0); let x = axis.x() - width; const parent = axis.parent; if (parent) { x -= parent.get("paddingLeft", 0); } if (axisHeader.children.length > 0) { width = axis.axisHeader.width(); axis.set("marginLeft", width); } else { axisHeader.set("width", width); } axisHeader.setAll({ x: x, y: -1, height: plotContainer.height() + 2 }); } } /** * @ignore */ public processAxis() { super.processAxis(); const axis = this.axis; axis.set("width", p100); const verticalLayout = this._root.verticalLayout; axis.set("layout", verticalLayout); axis.labelsContainer.set("width", p100); axis.axisHeader.setAll({ layout: verticalLayout }); } /** * @ignore */ public axisLength(): number { return this.axis.width(); } /** * Converts axis relative position to actual coordinate in pixels. * * @param position Position * @return Point */ public positionToPoint(position: number): IPoint { return { x: this.positionToCoordinate(position), y: 0 }; } /** * @ignore */ public updateTick(tick?: AxisTick, position?: number, endPosition?: number, count?: number) { if (tick) { if (!$type.isNumber(position)) { position = 0; } let location = 0.5; if ($type.isNumber(count) && count > 1) { location = tick.get("multiLocation", location) } else { location = tick.get("location", location) } if ($type.isNumber(endPosition) && endPosition != position) { position = position + (endPosition - position) * location; } tick.set("x", this.positionToCoordinate(position)); let length = tick.get("length", 0); const inside = tick.get("inside", this.get("inside", false)); if (this.get("opposite")) { tick.set("y", p100); if (!inside) { length *= -1 } } else { tick.set("y", 0); if (inside) { length *= -1 } } tick.set("draw", (display) => { display.moveTo(0, 0); display.lineTo(0, length); }) this.toggleVisibility(tick, position, tick.get("minPosition", 0), tick.get("maxPosition", 1)); } } /** * @ignore */ public updateLabel(label?: AxisLabel, position?: number, endPosition?: number, count?: number) { if (label) { let location = 0.5; if ($type.isNumber(count) && count > 1) { location = label.get("multiLocation", location) } else { location = label.get("location", location) } if (!$type.isNumber(position)) { position = 0; } const inside = label.get("inside", this.get("inside", false)); const opposite = this.get("opposite"); if (opposite) { if (!inside) { label.set("position", "relative"); label.set("y", p100); } else { label.set("position", "absolute"); label.set("y", 0) } } else { if (!inside) { label.set("y", undefined); label.set("position", "relative"); } else { label.set("y", 0) label.set("position", "absolute"); } } if ($type.isNumber(endPosition) && endPosition != position) { position = position + (endPosition - position) * location; } label.set("x", this.positionToCoordinate(position)); this.toggleVisibility(label, position, label.get("minPosition", 0), label.get("maxPosition", 1)); } } /** * @ignore */ public updateGrid(grid?: Grid, position?: number, endPosition?: number) { if (grid) { if (!$type.isNumber(position)) { position = 0; } let location = grid.get("location", 0.5); if ($type.isNumber(endPosition) && endPosition != position) { position = position + (endPosition - position) * location; } grid.set("x", Math.round(this.positionToCoordinate(position))); this.toggleVisibility(grid, position, 0, 1); } } /** * @ignore */ public updateBullet(bullet?: AxisBullet, position?: number, endPosition?: number) { if (bullet) { const sprite = bullet.get("sprite"); if (sprite) { if (!$type.isNumber(position)) { position = 0; } let location = bullet.get("location", 0.5); if ($type.isNumber(endPosition) && endPosition != position) { position = position + (endPosition - position) * location; } sprite.set("x", this.positionToCoordinate(position)); this.toggleVisibility(sprite, position, 0, 1); } } } /** * @ignore */ public updateFill(fill?: Graphics, position?: number, endPosition?: number) { if (fill) { if (!$type.isNumber(position)) { position = 0; } if (!$type.isNumber(endPosition)) { endPosition = 1; } let x0 = this.positionToCoordinate(position); let x1 = this.positionToCoordinate(endPosition); this.fillDrawMethod(fill, x0, x1); } } protected fillDrawMethod(fill: Graphics, x0: number, x1: number) { fill.set("draw", (display) => { //display.drawRect(x0, 0, x1 - x0, this.axis!.gridContainer.height()); // using for holes, so can not be rectangle const h = this.axis!.gridContainer.height(); const w = this.width(); if (x1 < x0) { [x1, x0] = [x0, x1]; } if (x0 > w || x1 < 0) { return; } x0 = Math.max(0, x0); x1 = Math.min(w, x1); display.moveTo(x0, 0); display.lineTo(x1, 0); display.lineTo(x1, h); display.lineTo(x0, h); display.lineTo(x0, 0); }) } /** * @ignore */ public positionTooltip(tooltip: Tooltip, position: number) { this._positionTooltip(tooltip, { x: this.positionToCoordinate(position), y: 0 }) } /** * @ignore */ public updateTooltipBounds(tooltip: Tooltip) { const inside = this.get("inside"); const num = 100000; let global = this._display.toGlobal({ x: 0, y: 0 }); let x = global.x; let y = 0; let w = this.axisLength(); let h = num; let pointerOrientation: "up" | "down" = "up"; if (this.get("opposite")) { if (inside) { pointerOrientation = "up"; y = global.y; h = num; } else { pointerOrientation = "down"; y = global.y - num; h = num; } } else { if (inside) { pointerOrientation = "down"; y = global.y - num; h = num; } else { pointerOrientation = "up"; y = global.y; h = num; } } const bounds = { left: x, right: x + w, top: y, bottom: y + h }; const oldBounds = tooltip.get("bounds"); if (!$utils.sameBounds(bounds, oldBounds)) { tooltip.set("bounds", bounds); tooltip.set("pointerOrientation", pointerOrientation); } } }
the_stack
import { strict as assert } from "assert"; import crypto from "crypto"; import got from "got"; import { ZonedDateTime, LocalDateTime, ZoneOffset } from "@js-joda/core"; import { log } from "../log"; import { mtimeDiffSeconds, mtimeDeadlineInSeconds, mtime, sleep } from "../mtime"; import { timestampToRFC3339Nano, rndstringFast, rndstringFastBoringFill, httpTimeoutSettings, logHTTPResponse } from "../util"; import { LogSample, LogSampleTimestamp, LogSeriesFragment, LogSeriesFragmentStats, logqlLabelString } from "./index"; import { TimeseriesBase, LabelSet, WalltimeCouplingOptions } from "../series"; // Note: maybe expose raw labels later on again. export interface LogSeriesOpts { // think: n log entries per stream/series fragment n_samples_per_series_fragment: number; n_chars_per_msg: number; starttime: ZonedDateTime; // The time difference between adjacent log samples in a series fragment, in // nanoseconds. Expected to be an integer. Defined via the substraction of // timestamps: T_(i+1) - T_i sample_time_increment_ns: number; includeTimeInMsg: boolean; uniqueName: string; labelset: LabelSet | undefined; compressability: string; // if undefined: do not couple to wall time wtopts?: WalltimeCouplingOptions; // Supposed to contain a prometheus counter object, providing an inc() method. counterForwardLeap?: any; } type TypeHttpHeaderDict = Record<string, string>; type TypeQueryParamDict = Record<string, string>; type CustomQueryFuncSigType = ( arg0: string, arg1: TypeHttpHeaderDict, arg2: TypeQueryParamDict, arg3: number, arg4: number, arg5: LogSeries ) => Promise<LokiQueryResult>; export interface LogSeriesFetchAndValidateOpts { querierBaseUrl: string; additionalHeaders: Record<string, string>; //inspectEveryNthEntry?: number | undefined; customLokiQueryFunc?: CustomQueryFuncSigType; } //export class LogSeries extends TimeseriesBase { export class LogSeries extends TimeseriesBase<LogSeriesFragment> { private currentSeconds: number; private currentNanos: number; private includeTimeInMsg: boolean; private firstEntryGenerated: boolean; private genChars: (n: number) => string; n_chars_per_msg: number; nFragmentsSuccessfullySentSinceLastValidate: number; constructor(opts: LogSeriesOpts) { super(opts); this.currentSeconds = opts.starttime.toEpochSecond(); this.currentNanos = opts.starttime.nano(); this.firstEntryGenerated = false; this.n_chars_per_msg = opts.n_chars_per_msg; this.nFragmentsConsumed = 0; this.includeTimeInMsg = opts.includeTimeInMsg; // when using the dummystream to generate data and actually POST it // to an API use this counter to keep track of the number of fragments // successfully sent. This is public because of external push func. this.nFragmentsSuccessfullySentSinceLastValidate = 0; if (this.sample_time_increment_ns > 999999999) throw Error("sample_time_increment_ns must be smaller than 1 s"); if (this.includeTimeInMsg && this.n_chars_per_msg < 19) { throw Error("timestamp consumes 18+1 characters"); } switch (opts.compressability) { case "min": this.genChars = rndstringFast; break; case "max": this.genChars = (n: number) => { return "a".repeat(n); }; break; case "medium": this.genChars = (n: number) => { // "half random", "half always-the-same" // fast floored integer division: // (11/2>>0) -> 5 // remainder: 11 % 2 -> 1 // example for n=10: // rndstringFastBoringFill(5, 5) // example for n=11: // rndstringFastBoringFill(5, 6) // Note(JP): this could be further optimized by making n not be // dynamic (because considering `includeTimeInMsg` and the rest of // the static dummystream config this is predictable, n does not need // to be dynamically evaluated upon _each_ function call here). return rndstringFastBoringFill( (n / 2) >> 0, ((n / 2) >> 0) + (n % 2) ); }; break; default: throw new Error(`bad compressability value: ${opts.compressability}`); } } // public addToNFragmentsTotal(n: number) { // this.opts.n_fragments_total += n; // this.n_fragments_total += n; // } protected buildLabelSetFromOpts(opts: LogSeriesOpts): LabelSet { let ls: LabelSet; if (opts.labelset !== undefined) { ls = opts.labelset; ls.looker_uniquename = opts.uniqueName; } else { ls = { looker_uniquename: opts.uniqueName }; } return ls; } public promQueryString(): string { return `{looker_uniquename="${this.uniqueName}"}`; } private buildMsgText(): string { let text: string; if (!this.includeTimeInMsg) text = this.genChars(this.n_chars_per_msg); else { // build integer string, indicating the number of nanoseconds passed // since epoch, as is common in the Loki ecosystem. const timestring = `${this.currentSeconds}${this.currentNanos .toString() .padStart(9, "0")}`; // Note(JP): timestring is known to be 19 chars long. Also note that in // this case the "compressability" aspect changes, depending on the ratio // between the desired message length and the length of this timestring. // From a message length of 100 onwards I believer it is fair to say // that "max" compressability is still a very high compressability even // when the message is prefixed with this timestring. text = `${timestring}:${this.genChars(this.n_chars_per_msg - 19)}`; } return text; } // Note(JP): this is OK to lose precision compared to the internal two // var-based representation (though I don't understand enough of JavaScripts // number type to know if this actually may lose precision. protected lastSampleSecondsSinceEpoch(): number { return this.currentSeconds + this.currentNanos / 10 ** 9; } protected nextSample(): LogSample { // don't bump time before first entry was generated. if (this.firstEntryGenerated) { this.currentNanos += this.sample_time_increment_ns; if (this.currentNanos > 999999999) { this.currentNanos = this.currentNanos - 10 ** 9; this.currentSeconds += 1; } } const ts: LogSampleTimestamp = { seconds: this.currentSeconds, nanos: this.currentNanos }; // of course this only needs to be run once, and I hope that the compiler // optimizes this away. this.firstEntryGenerated = true; return new LogSample(this.buildMsgText(), ts); } // no stop criterion protected generateNextFragment(): LogSeriesFragment { const f = new LogSeriesFragment( this.labels, this.nFragmentsConsumed + 1, this ); for (let i = 0; i < this.n_samples_per_series_fragment; i++) { f.addSample(this.nextSample()); } this.nFragmentsConsumed += 1; return f; } /** * Unbuffered POST to Loki (generate/post/generate/post sequentially in that * order, and do not retry upon POST errors, except for 429 responses. * * @param lokiBaseUrl */ public async postFragmentsToLoki( nFragments: number, lokiBaseUrl: string, additionalHeaders?: Record<string, string> ) { // For now: one HTTP request per fragment for (let i = 1; i <= nFragments; i++) { let fragment: LogSeriesFragment; while (true) { const [shiftIntoPastSeconds, f] = this.generateNextFragmentOrSkip(); if (f !== undefined) { fragment = f; break; } log.debug( `${this}: current lag compared to wall time ` + `(${shiftIntoPastSeconds.toFixed(1)} s)` + "is too small. Delay fragment generation." ); await sleep(5); } const t0 = mtime(); const pushrequest = fragment.serialize(); const genduration = mtimeDiffSeconds(t0); // Control log verbosity if (fragment.index < 5 || fragment.index % 10 === 0) { log.info( "Generated PR for stream %s in %s s, push %s MiB (%s entries)", this.uniqueName, genduration.toFixed(2), pushrequest.dataLengthMiB.toFixed(4), // for now: assume that there is _one_ fragment here pushrequest.fragments[0].sampleCount() ); } await pushrequest.postWithRetryOrError(lokiBaseUrl, 3, additionalHeaders); if (this.shouldBeValidated()) { assert(this.postedFragmentsSinceLastValidate); this.postedFragmentsSinceLastValidate.push(fragment); } } } protected leapForward(n: bigint): void { // invariant: this must not be called when `this.walltimeCouplingOptions` // is undefined. assert(this.walltimeCouplingOptions); // `currentSeconds` is of type `number` but must always hold an integer // value. To make this explicit and to get some compiler support, require // `n` to be passed as type `bigint`. this.currentSeconds += Number(n); } public currentTime(): ZonedDateTime { // Return the time corresponding to the last generated entry. // First, construct datetime object with 1 s resoltution. const tsSecondResolution = LocalDateTime.ofEpochSecond( this.currentSeconds, ZoneOffset.UTC ); // Now construct datetime object with ns resolution using the previous // object. const tsNanoSecondResolution = LocalDateTime.of( tsSecondResolution.year(), tsSecondResolution.month(), tsSecondResolution.dayOfMonth(), tsSecondResolution.hour(), tsSecondResolution.minute(), tsSecondResolution.second(), this.currentNanos ); return tsNanoSecondResolution.atZone(ZoneOffset.UTC); } public currentTimeRFC3339Nano(): string { return timestampToRFC3339Nano(this.currentTime()); } private queryParamsForFragment(fragment: LogSeriesFragment) { // Confirm that fragment is 'closed' (serialized, has stats), and override // type from `LogStreamFragmentStats | MetricSeriesFragmentStats` to just // `MetricSeriesFragmentStats`. assert(fragment.stats); const stats = fragment.stats as LogSeriesFragmentStats; if (stats.sampleCount > 60000) { throw new Error( "too many samples to fetch in one go -- needs feature: N queries per fragment" ); } const qparams: TypeQueryParamDict = { query: logqlLabelString(this.labels), direction: "FORWARD", limit: stats.sampleCount.toString(), start: stats.timeOfFirstEntry.toString(), // end is not inclusive, i.e. if we set `end` to e.g. 1582211051130000099 // then the last entry returned would be from 1582211051130000098 even if // there is one at 1582211051130000099. So, bump this by one nanosecond // to get N entries returned in the happy case. end: (stats.timeOfLastEntry + BigInt(1)).toString() }; log.debug("query params: %s", qparams); return qparams; } protected async fetchAndValidateFragment( fragment: LogSeriesFragment, opts: LogSeriesFetchAndValidateOpts ): Promise<number> { assert(fragment.stats); const stats = fragment.stats as LogSeriesFragmentStats; const qparams = this.queryParamsForFragment(fragment); let result: LokiQueryResult; if (opts.customLokiQueryFunc !== undefined) { result = await opts.customLokiQueryFunc( opts.querierBaseUrl, opts.additionalHeaders, qparams, Number(stats.sampleCount), fragment.index, this // pass dummystream object to func for better error reporting ); } else { // used by e.g. test-remote project (can change) result = await waitForLokiQueryResult( opts.querierBaseUrl, opts.additionalHeaders, qparams, Number(stats.sampleCount), false, 1, false // disable building hash over payload ); } // TODO: compare stats derived from the query result with the .stats // propery on the fragment. const logTextHash = crypto.createHash("md5"); for (const e of result.entries) { // Update log text hash with the UTF-8-encoded version of the text. From // docs: "If encoding is not provided, and the data is a string, an // encoding of 'utf8' is enforced" logTextHash.update(e[1]); } const textmd5fromq = logTextHash.digest("hex"); if (stats.textmd5 !== textmd5fromq) { throw new Error( "log time series fragment text checksum mismatch: " + `series: ${fragment.parent!.promQueryString} ` + `fragment: ${fragment.index} + \n fragment stats: ` + JSON.stringify(stats, null, 2) + `\nchecksum from query result: ${textmd5fromq}` ); } return result.entries.length; } } export interface LokiQueryResult { entries: Array<[string, string]>; labels: LabelSet; textmd5: string; } /** * Expected to throw got.RequestError, handle in caller if desired. */ async function queryLoki( baseUrl: string, queryParams: URLSearchParams, additionalHeaders: TypeHttpHeaderDict ) { /* Notes, in no particular order: - Note that Loki seems to set `'Content-Type': 'text/plain; charset=utf-8'` even when it sends a JSON document in the response body. Submit a bug report, and at some point test that this is not the case anymore here. */ const url = `${baseUrl}/loki/api/v1/query_range`; const options = { throwHttpErrors: false, searchParams: queryParams, timeout: httpTimeoutSettings, headers: additionalHeaders, https: { rejectUnauthorized: false } // insecure TLS for now }; // Note: this may throw got.RequestError for request timeout errors. const response = await got(url, options); if (response.statusCode !== 200) logHTTPResponse(response); return JSON.parse(response.body); } async function waitForLokiQueryResult( lokiQuerierBaseUrl: string, additionalHeaders: TypeHttpHeaderDict, queryParams: TypeQueryParamDict, expectedSampleCount: number | undefined, logDetails = true, expectedStreamCount = 1, buildhash = true, maxWaitSeconds = 30 ): Promise<LokiQueryResult> { const deadline = mtimeDeadlineInSeconds(maxWaitSeconds); if (logDetails) { log.info( `Enter Loki query loop, wait for expected result, deadline ${maxWaitSeconds} s. Query parameters: ${JSON.stringify( queryParams, Object.keys(queryParams).sort(), 2 )}` ); } const qparms = new URLSearchParams(queryParams); let queryCount = 0; const t0 = mtime(); // `break`ing out the loop enters the error path, returning indicates // success. while (true) { if (mtime() > deadline) { log.error("query deadline hit"); break; } queryCount += 1; let result: any; try { result = await queryLoki(lokiQuerierBaseUrl, qparms, additionalHeaders); } catch (e: any) { // handle any error that happened during http request processing if (e instanceof got.RequestError) { log.info( `waitForLokiQueryResult() loop: http request failed: ${e.message} -- ignore, proceed with next iteration` ); continue; } else if (e instanceof SyntaxError) { // JSON.parse() failed on loki response (e.g. 500 error) log.warning( `waitForLokiQueryResult() loop: http parse response failed: ${e.message} -- ignore, proceed with next iteration` ); continue; } else { // Throw any other error, mainly programming error. throw e; } } if (result.status === undefined) { log.warning( "no `status` property in response doc: %s", JSON.stringify(result) ); await sleep(1); continue; } if (result.status !== "success") { log.warning( "status property is not `success`: %s", JSON.stringify(result.status) ); await sleep(1); continue; } // Plan for the following structure. // { // "status": "success", // "data": { // "resultType": "streams", // "result": [ // { // "stream": { // "filename": "/var/log/myproject.log", // "job": "varlogs", // "level": "info" // }, // "values": [ // [ // "1569266497240578000", // "foo" // ], // [ // "1569266492548155000", // "bar" // ] // ] // } // ], // "stats": { // ... // } // } // } const streams = result.data.result; if (streams.length === 0) { if (queryCount % 10 === 0) { log.info("queried %s times, no log entries seen yet", queryCount); } await sleep(0.5); continue; } if (logDetails) log.info( "query %s response data:\n%s", queryCount, JSON.stringify(result, null, 2) ); // Note: 0 is a special case for "don't check the count!" // Conditionally check for number of expected label sets / "streams". if (expectedStreamCount !== 0) { assert.equal(streams.length, expectedStreamCount); } // Even if we got multiple streams here go with just one of them. assert("values" in streams[0]); const sampleCount = streams[0]["values"].length; log.info( "expected nbr of query results: %s, got %s", expectedSampleCount, sampleCount ); // Expect N log entries in the stream. if ( expectedSampleCount === undefined || sampleCount === expectedSampleCount ) { log.info( "got expected result in query %s after %s s", queryCount, mtimeDiffSeconds(t0).toFixed(2) ); const labels: LabelSet = streams[0].stream; //logqlKvPairTextToObj(data["streams"][0]["labels"]); //log.info("labels on returned log record:\n%s", labels); // Build a hash over all log message contents in this stream, in the // the order as returned by Loki. Can be used to verify that the same // payload data came out of the system as was put into it. Note: text // is encoded as utf-8 implicitly before hashing. let textmd5 = "disabled"; if (buildhash) { const logTextHash = crypto.createHash("md5"); for (const entry of streams[0]["values"]) { // entry[0] is the timestamp (ns precision integer as string) // entry[1] is the log line logTextHash.update(entry[1]); } textmd5 = logTextHash.digest("hex"); } const result: LokiQueryResult = { entries: streams[0]["values"], labels: labels, textmd5: textmd5 }; return result; } if (sampleCount < expectedSampleCount) { log.info("not enough entries returned yet, waiting"); await sleep(1); continue; } else throw new Error("too many entries returned in query result"); } throw new Error(`Expectation not fulfilled within ${maxWaitSeconds} s`); }
the_stack
import React from 'react' import { Events, Tab } from '@kui-shell/core' // Component Imports import { ActionGroup, Form, FormGroup, TextInput, Checkbox, FormSelect, FormSelectOption, Switch as Toggle } from '@patternfly/react-core' import { Button, Tag } from '@kui-shell/plugin-client-common' // UI Style imports import '../../src/web/scss/static/exprForm.scss' // Functionality Imports import GetKubeInfo from '../components/cluster-info' import { GetMetricConfig } from '../components/metric-config' import getRequestModel from '../utility/get-iter8-req' import { Formstate } from '../modes/state-models' import { experimentTypes } from '../utility/variables' import MultiSelect from './MultiSelect' /* * Data models for the state object in ExprForm */ type Props = Tab export default class ExprBase extends React.Component<Props, Formstate> { // imported class of methods from /components private kubeMethods = new GetKubeInfo() private GetMetricConfig = new GetMetricConfig() // Lists of dropdown menu items private args: Props public constructor(props: Props) { super(props) this.args = props this.state = { showCriteria: false, // determines the visibility of metric config section invalidCandidate: false, // determines whether candidates values are valid name: '', // name of the experiment type: experimentTypes.hil, // type of experiment: HIL vs automated namespace: '', // namespace of microservice service: '', // service name of microservice baseline: '', // baseline deployment of microservice candidates: [], // list of candidates deployment names of microservice criteria: [{ name: '', type: '', reward: false, limitType: '', limitValue: 0 }], // metric attributes disableReward: false, // disables the reward select for selected metrics edgeService: true, hostGateways: [], invalidHostGateways: false, nsList: [], svcList: [], deployList: [], countMetricsList: [], ratioMetricsList: [], totalMetricsList: [] } setTimeout(async () => { const [nsList] = await Promise.all([this.kubeMethods.getNamespace(this.args)]) this.setState({ nsList }) }) setTimeout(async () => { const [countMetricsList] = await Promise.all([this.GetMetricConfig.getCounterMetrics(this.args)]) this.setState({ countMetricsList }) }) setTimeout(async () => { const [ratioMetricsList] = await Promise.all([this.GetMetricConfig.getRatioMetrics(this.args)]) this.setState({ ratioMetricsList }) }) // Bound NON-lambda functions to component's scope this.submitForm = this.submitForm.bind(this) this.handleNameChange = this.handleNameChange.bind(this) this.addCriterion = this.addCriterion.bind(this) } public componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { console.error(error, errorInfo) } /* * ==== Basic Experiment State Handlers ===== */ private handleNameChange(event) { console.log(event.target.value) this.setState({ name: event.target.value }) } private handleAddCand = value => { // Convert all input items into an iterable array const versionValue = value.map(data => { return data.text }) // Check for invalid selections for (let i = 0; i < versionValue.length; i++) { if (this.state.baseline === versionValue[i]) { versionValue.splice(i, 1) this.setState({ invalidCandidate: true, candidates: versionValue }) return } } this.setState({ invalidCandidate: false, candidates: versionValue }) } private handleSplitCand(value) { const candList = value.target.value.split(',') const obj = [] for (let i = 0; i < candList.length; i++) { obj.push({ id: `c-${i}`, text: candList[i].trim() }) } this.handleAddCand(obj) } private handleSelectExpType = (value: string) => { console.log('Running ' + value + ' Experiment') } private handleAddNs = (value: string) => { if (value == null) { this.setState({ namespace: '', service: '', baseline: '', candidates: [] }) const svcList = [] this.setState({ svcList }) } else { this.setState({ namespace: value, service: '', baseline: '', candidates: [] }) setTimeout(async () => { const [svcList] = await Promise.all([this.kubeMethods.getSvc(value, this.args)]) this.setState({ svcList }) }) } this.setState({ deployList: [] }) } private handleAddSvc = (value: string) => { if (value == null) { this.setState({ service: '', baseline: '', candidates: [] }) const deployList = [] this.setState({ deployList }) } else { this.setState({ service: value, baseline: '', candidates: [] }) setTimeout(async () => { const [deployList] = await Promise.all([this.kubeMethods.getDeployment(this.state.namespace, value, this.args)]) this.setState({ deployList }) }) } } private handleEdgeServiceChange = (value: boolean) => { if (value === true) { this.setState({ edgeService: true }) } else { this.setState({ edgeService: false }) this.setState({ invalidHostGateways: false }) } } private addHostGatewayPairs = (value: string) => { const hostgateway = value.split(';') const obj = [] let temp = [] for (let i = 0; i < hostgateway.length; i++) { temp = hostgateway[i].trim().split(',') temp[0] = typeof temp[0] === typeof '' ? temp[0].trim() : '' temp[1] = typeof temp[1] === typeof '' ? temp[1].trim() : '' if (temp[0] === '' || temp[1] === '') { continue } obj.push({ name: temp[0], gateway: temp[1] }) } if (obj.length === 0) { this.setState({ invalidHostGateways: true }) } else { this.setState({ invalidHostGateways: false }) this.setState({ hostGateways: obj }) } } private handleAddBase = (value: string) => { if (value == null) this.setState({ baseline: '', candidates: [] }) else this.setState({ baseline: value, candidates: [] }) } /* * ==== Metric Configuration Handler Functions ==== */ // Method for Add Metric (+) button private addCriterion() { this.setState({ totalMetricsList: this.state.countMetricsList.concat(this.state.ratioMetricsList) }) if (this.state.showCriteria) { // If a criterion is already shown, add a new criterion this.setState(prevState => ({ criteria: [...prevState.criteria, { name: '', type: '', reward: false, limitType: '', limitValue: 0 }] })) } else { // If no criteria has been addded, add the first criterion this.setState({ showCriteria: true }) } } // Removes the metric field from the state private deleteCriterion = idx => { this.setState(state => { const criteria = state.criteria.filter((m, i) => i !== idx) return { criteria } }) } // Handles metric selection from dropdown private handleMetricName = (value, idx) => { let metricName let metricType // Removal of a selected value if (value == null) { metricName = '' metricType = '' } // Check for metric type (ratio/counter) else { metricName = value.name metricType = 'Ratio' // TODO: handle error for (let i = 0; i < this.state.countMetricsList.length; i++) { if (this.state.countMetricsList[i].name === value.name) metricType = 'Counter' } } const newMetric = [...this.state.criteria] newMetric[idx] = { ...newMetric[idx], name: metricName, type: metricType } this.setState({ criteria: newMetric }) } // Updates states based on limit type changes private handleLimitTypeChange = (value: boolean, idx: number) => { const limitType = value ? 'relative' : 'absolute' const newMetric = [...this.state.criteria] newMetric[idx] = { ...newMetric[idx], limitType: limitType } this.setState({ criteria: newMetric }) } // Update the state for limit value private handleLimitValChange = (value: string, idx: number) => { const limitValue = value === '' ? 0 : parseFloat(value) const newMetric = [...this.state.criteria] newMetric[idx] = { ...newMetric[idx], limitValue: limitValue } this.setState({ criteria: newMetric }) } // Disables all the other checkboxes private handleRewardChange = (idx: number) => { const newMetric = [...this.state.criteria] newMetric[idx] = { ...newMetric[idx], reward: !newMetric[idx].reward } this.setState(prevState => ({ criteria: newMetric, disableReward: !prevState.disableReward })) } /* * ==== Form Submission Handlers ==== */ private submitForm() { const d = new Date(Date.now() - 20000) const time = d.toISOString() const jsonOutput = getRequestModel(time, this.state, this.args) // Transmit data to Decision form using eventBus Events.eventChannelUnsafe.emit('/get/decision', jsonOutput) } // Cancels form submission event caused by "Enter" press private preventFormRefresh(event) { event.preventDefault() document.getElementById('submitform').setAttribute('disabled', '') document.getElementById('addcriterion').setAttribute('disabled', '') } public render() { const { criteria } = this.state return ( <div className="padding-content scrollable scrollable-auto"> <h2>iter8 Experiment Configurations</h2> <Form className="plugin-iter8-formProps" onSubmit={this.preventFormRefresh}> <FormGroup style={{ width: 350 }} label="Name" helperText="Name to identify the experiment" helperTextInvalid="This is a required field" isRequired fieldId="exprForm-id-2" > <TextInput id="experiment-name" placeholder="Eg: experiment_v1_v2" onChange={this.handleNameChange} type="text" ></TextInput> </FormGroup> <FormGroup style={{ width: 350 }} label="Experiment Type" helperText="Type of experiment to be conducted" isRequired fieldId="exprForm-id-3" > <FormSelect id="experiment-type-select" placeholder="Select an Experiment Type" onChange={value => this.handleSelectExpType(value)} > {[experimentTypes.hil].map((option, idx) => ( <FormSelectOption key={idx} label={option} /> ))} </FormSelect> </FormGroup> <FormGroup style={{ width: 350 }} label="Service Namespace" helperText="Namespace where the target service resides" isRequired fieldId="exprForm-id-4" > <FormSelect id="namespace-select" placeholder="Select a Namespace" onChange={value => this.handleAddNs(value)} > {this.state.nsList.map((option, idx) => ( <FormSelectOption key={idx} label={option ? option.text : ''} /> ))} </FormSelect> </FormGroup> <FormGroup label="Edge Service" fieldId="exprForm-id-5"> <Toggle aria-label="" id="edge-service" isChecked label="False" labelOff="True" onChange={value => this.handleEdgeServiceChange(value)} /> </FormGroup> <FormGroup style={{ width: 350 }} label="Host/Gateway pairs" helperText="Enter Host and gateway names for edge service" helperTextInvalid="Invalid Host Gateway Pairs. Try again" validated={this.state.invalidHostGateways ? 'error' : 'default'} fieldId="exprForm-id-6" > <TextInput id="hostGateway" placeholder="Eg: hostname1, gatewayname1; hostname2, gatewayname2" onChange={value => this.addHostGatewayPairs(value)} type="text" isDisabled={!this.state.edgeService} ></TextInput> </FormGroup> <FormGroup style={{ width: 350 }} label="Service" helperText="Name of the target service" isRequired fieldId="exprForm-id-7" > <FormSelect id="service-select" placeholder="Select a Service" onChange={value => this.handleAddSvc(value)}> {this.state.svcList.map((option, idx) => ( <FormSelectOption key={idx} label={option ? option.text : ''} /> ))} </FormSelect> </FormGroup> <FormGroup style={{ width: 350 }} label="Baseline Deployment" helperText="The version of the service to be used as experimental baseline" isRequired fieldId="exprForm-id-8" > <FormSelect id="baseline-select" placeholder="Select a Baseline Deployment" onChange={value => this.handleAddBase(value)} > {this.state.deployList.map((option, idx) => ( <FormSelectOption key={idx} label={option ? option.text : ''} /> ))} </FormSelect> </FormGroup> <FormGroup style={{ width: 350 }} label="Select Candidate Deployment(s)" validated={this.state.invalidCandidate ? 'error' : 'default'} helperTextInvalid="Cannot select same version as experimental baseline." fieldId="exprForm-id-9" > <p> <span> Candidate Deployment(s) </span> <br /> <span className="helper"> The version(s) of the service to be used as experimental candidate(s).</span> </p> <MultiSelect id="candidates-select" options={this.state.deployList.map(_ => (_ ? _.text : ''))} onChange={selectedItems => this.handleAddCand(selectedItems)} /> </FormGroup> <FormGroup label="or Add Candidate Deployment(s) below:" helperText="Comma separated candidate names" fieldId="exprForm-id-10" > <TextInput id="candidate-name" placeholder="reviews_v3, reviews_v4" onChange={value => this.handleSplitCand(value)} type="text" ></TextInput> </FormGroup> {this.state.showCriteria ? ( <div style={{ position: 'relative' }}> {criteria.map((val, idx) => { const criterionId = `criterion-${idx}` const limitTypeId = `limitType-${idx}` const limitValueId = `limitValue-${idx}` const deletecriterion = `deletecriterion-${idx}` const checkId = `checkbox-${idx}` return ( <div style={{ padding: 20 }} key={idx}> <h5> {`Criterion #${idx + 1}`}</h5> <FormGroup fieldId={`exprForm-id-11-${idx}-1`} label="Metric name" helperText="Metric to be used for this critetion" > <FormSelect id={criterionId} onChange={value => this.handleMetricName(value, idx)}> {this.state.totalMetricsList.map((option, idx) => ( <FormSelectOption key={idx} label={option ? option.name : ''} /> ))} </FormSelect> </FormGroup> <Tag type="ok">{val.type === '' ? '...' : val.type}</Tag> <Tag type="warning"> {val.reward ? 'Reward' : val.limitType === '' ? 'Absolute Threshold' : `${val.limitType} threshold`} </Tag> <br></br> <span className="child"> {val.limitType ? null : this.handleLimitTypeChange(false, idx)} <FormGroup fieldId={`exprForm-id-11-${idx}-2`} label="Threshold Type"> <Toggle aria-label="" id={limitTypeId} isDisabled={val.reward} label="Absolute" labelOff="Relative" onChange={value => this.handleLimitTypeChange(value, idx)} /> </FormGroup> </span> <span className="child"> <FormGroup fieldId={`exprForm-id-11-${idx}-3`} label="Limit Value" helperText="Set a value for the threshold selected" helperTextInvalid="Limit values can only be set for non-reward metrics" validated={val.reward && val.limitValue !== 0 ? 'error' : 'default'} > <TextInput id={limitValueId} isDisabled={val.reward} onChange={value => this.handleLimitValChange(value, idx)} /> </FormGroup> </span> <FormGroup fieldId={`exprForm-id-11-${idx}-4`} label="Set as reward"> <Checkbox id={checkId} isDisabled={(!val.reward && this.state.disableReward) || val.type === 'Counter'} onChange={() => this.handleRewardChange(idx)} /> </FormGroup> <Button id={deletecriterion} size="small" kind="danger" onClick={() => this.deleteCriterion(idx)}> {`Delete Criterion ${idx + 1}`} </Button> </div> ) })} </div> ) : null} <ActionGroup> <FormGroup style={{ width: 350 }} fieldId="exprForm-id-12"> <Button id="addcriterion" size="default" kind="primary" onClick={this.addCriterion}> Add Criterion </Button> </FormGroup> <FormGroup style={{ width: 350 }} fieldId="exprForm-id-13"> <Button id="submitform" type="submit" size="default" onClick={this.submitForm}> Create Experiment </Button> </FormGroup> </ActionGroup> </Form> </div> ) } }
the_stack
import validator from 'validator'; import lTrim from 'lodash/trim'; import lTrimStart from 'lodash/trimStart'; import lTrimEnd from 'lodash/trimEnd'; import lCamelCase from 'lodash/camelCase'; import lSnakeCase from 'lodash/snakeCase'; import lKebabCase from 'lodash/kebabCase'; import lStartCase from 'lodash/startCase'; import { MACDelimiter } from '@terascope/types'; import { isArrayLike } from './arrays'; import { getTypeOf } from './deps'; import { bigIntToJSON } from './numbers'; /** A simplified implementation of lodash isString */ export function isString(val: unknown): val is string { return typeof val === 'string'; } /** * Safely convert any input to a string * * @example * * toString(1); // '1' * toString(0.01); // '0.01' * toString(true); // 'true' * toString(BigInt(2) ** BigInt(64)); // '18,446,744,073,709,551,616' * toString(new Date('2020-09-23T14:54:21.020Z')) // '2020-09-23T14:54:21.020Z' */ export function toString(val: unknown): string { if (val == null) return ''; if (typeof val === 'string') return val; if (typeof val === 'number' || typeof val === 'symbol' || typeof val === 'boolean') { return String(val); } if (typeof val === 'bigint') { const res = bigIntToJSON(val); if (typeof res === 'string') return res; return `${res}`; } if (typeof val === 'function') { return val.toString(); } if (isArrayLike(val)) { return val.map(toString).join(','); } if (val instanceof Date) { return val.toISOString(); } if (typeof val === 'object' && val != null) { if (val[Symbol.iterator]) { return [...val as any].map(toString).join(','); } // is error if ('message' in val && 'stack' in val) { return val.toString(); } if (val[Symbol.toPrimitive]) { return `${val}`; } if (typeof (val as any).toJSON === 'function') { return toString((val as any).toJSON()); } } // fall back to this return JSON.stringify(val); } /** * Check if a value is a JavaScript primitive value OR * it is object with Symbol.toPrimitive */ export function isPrimitiveValue(value: unknown): boolean { const type = typeof value; if (type === 'string') return true; if (type === 'boolean') return true; if (type === 'number') return true; if (type === 'bigint') return true; if (type === 'symbol') return true; if (type === 'object' && typeof (value as any)[Symbol.toPrimitive] === 'function') return true; return false; } /** * Convert a JavaScript primitive value to a string. * (Does not covert object like entities unless Symbol.toPrimitive is specified) */ export function primitiveToString(value: unknown): string { if (value == null) return ''; if (!isPrimitiveValue(value)) { throw new Error(`Expected ${value} (${getTypeOf(value)}) to be in a string like format`); } return `${value}`; } /** safely trims whitespace from an input */ export function trim(input: unknown, char?: string): string { return lTrim(primitiveToString(input), char); } export function trimFP(char?: string) { return function _trim(input: unknown): string { return trim(input, char); }; } export function trimStart(input: unknown, char?: string): string { return lTrimStart(primitiveToString(input), char); } export function trimStartFP(char?: string) { return function _trimStart(input: unknown): string { return trimStart(input, char); }; } export function trimEnd(input: unknown, char?: string): string { return lTrimEnd(primitiveToString(input), char); } export function trimEndFP(char?: string) { return function _trimEnd(input: unknown): string { return trimEnd(input, char); }; } /** safely trim and to lower a input, useful for string comparison */ export function trimAndToLower(input?: string): string { return trim(input).toLowerCase(); } /** safely trim and to lower a input, useful for string comparison */ export function trimAndToUpper(input?: string): string { return trim(input).toUpperCase(); } /** * Converts a value to upper case * * @example * * toUpperCase('lowercase'); // 'LOWERCASE' * toUpperCase('MixEd'); // 'MIXED' * toUpperCase('UPPERCASE'); // 'UPPERCASE' */ export function toUpperCase(input: unknown): string { if (typeof input !== 'string') return ''; return input.toUpperCase(); } /** * Converts a value to lower case * * @example * * toLowerCase('lowercase'); // 'lowercase' * toLowerCase('MixEd'); // 'mixed' * toLowerCase('UPPERCASE'); // 'uppercase' */ export function toLowerCase(input: unknown): string { if (typeof input !== 'string') return ''; return input.toLowerCase(); } /** Unescape characters in string and avoid double escaping */ export function unescapeString(str = ''): string { const len = str.length; let unescaped = ''; for (let i = 0; i < len; i++) { const char = str.charAt(i); const next = i < len ? str.charAt(i + 1) : ''; if (char === '\\' && next) { unescaped += next; i++; } else { unescaped += char; } } return unescaped; } /** A native implementation of lodash startsWith */ export function startsWith(str: unknown, val: unknown): boolean { if (!isString(str)) return false; if (!isString(val)) return false; return str.startsWith(val); } /** A function version of startsWith */ export function startsWithFP(val: string): (input: unknown) => boolean { if (!isString(val)) { throw new Error(`Invalid argument "val", must be of type string, got ${getTypeOf(val)}`); } return function _startsWithFP(str: unknown): boolean { return startsWith(str, val); }; } /** A native implementation of lodash endsWith */ export function endsWith(str: unknown, val: unknown): boolean { if (!isString(str)) return false; if (!isString(val)) return false; return str.endsWith(val); } /** A function version of startsWith */ export function endsWithFP(val: string): (input: unknown) => boolean { if (!isString(val)) { throw new Error(`Invalid argument "val", must be of type string, got ${getTypeOf(val)}`); } return function _startsWithFP(str: unknown): boolean { return endsWith(str, val); }; } /** * Truncate a string value, by default it will add an ellipsis (...) if truncated. */ export function truncate(value: unknown, len: number, ellipsis = true): string { if (value == null || value === '') return ''; if (!isString(value)) { throw new SyntaxError(`Expected string value to truncate, got ${getTypeOf(value)}`); } if (!ellipsis) return value.slice(0, len); const sliceLen = len - 4 > 0 ? len - 4 : len; return value.length >= len ? `${value.slice(0, sliceLen)} ...` : value; } /** * A functional version of truncate */ export function truncateFP(len: number, ellipsis = true) { return function _truncateFP(value: unknown): string { return truncate(value, len, ellipsis); }; } export const LOWER_CASE_CHARS = { a: true, b: true, c: true, d: true, e: true, f: true, g: true, h: true, i: true, j: true, k: true, l: true, m: true, n: true, o: true, p: true, q: true, r: true, s: true, t: true, u: true, v: true, w: true, x: true, y: true, z: true, } as const; export const UPPER_CASE_CHARS = { A: true, B: true, C: true, D: true, E: true, F: true, G: true, H: true, I: true, J: true, K: true, L: true, M: true, N: true, O: true, P: true, Q: true, R: true, S: true, T: true, U: true, V: true, W: true, X: true, Y: true, Z: true, } as const; export const NUM_CHARS = { 0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: true, } as const; export const WORD_SEPARATOR_CHARS = { ' ': true, _: true, '-': true, } as const; export const WORD_CHARS = { ...LOWER_CASE_CHARS, ...UPPER_CASE_CHARS, ...NUM_CHARS, } as const; /** * Split a string and get the word parts */ export function getWordParts(input: string): string[] { if (!isString(input)) { throw new Error(`Expected string, got ${getTypeOf(input)}`); } const parts: string[] = []; let word = ''; let started = false; for (let i = 0; i < input.length; i++) { const char = input.charAt(i); const nextChar = input.charAt(i + 1); if (!started && char === '_') { if (nextChar === '_' || WORD_CHARS[nextChar]) { word += char; continue; } } started = true; if (char && WORD_CHARS[char]) { word += char; } if (WORD_SEPARATOR_CHARS[nextChar]) { parts.push(word); word = ''; } if (UPPER_CASE_CHARS[nextChar]) { const nextNextChar = input.charAt(i + 2); if (LOWER_CASE_CHARS[nextNextChar]) { parts.push(word); word = ''; } } } return parts.concat(word).filter(Boolean); } export function toCamelCase(input: string): string { return lCamelCase(input); } export function toPascalCase(input: string): string { return firstToUpper(lCamelCase(input)); } export function toKebabCase(input: string): string { return lKebabCase(input); } export function toSnakeCase(input: string): string { return lSnakeCase(input); } export function toTitleCase(input: string): string { return lStartCase(input); } /** * Make a string url/elasticsearch safe. * safeString converts the string to lower case, * removes any invalid characters, * and replaces whitespace with _ (if it exists in the string) or - * Warning this may reduce the str length */ export function toSafeString(input: string): string { let s = trimAndToLower(input); const startReg = /^[_\-+]+/; while (startReg.test(s)) { s = s.replace(startReg, ''); } const whitespaceChar = s.includes('_') ? '_' : '-'; s = s.replace(/\s/g, whitespaceChar); const reg = new RegExp('[.+#*?"<>|/\\\\]', 'g'); s = s.replace(reg, ''); return s; } function _replaceFirstWordChar(str: string, fn: (char: string) => string): string { let found = false; return str.split('').map((s) => { if (!found && WORD_CHARS[s]) { found = true; return fn(s); } return s; }).join(''); } /** Change first character in string to upper case */ export function firstToUpper(str: string): string { if (!str) return ''; return _replaceFirstWordChar(str, (char) => char.toUpperCase()); } /** Change first character in string to lower case */ export function firstToLower(str: string): string { if (!str) return ''; return _replaceFirstWordChar(str, (char) => char.toLowerCase()); } export function getFirstChar(input: string): string { if (!input) return ''; return trim(input).charAt(0); } // http://www.regular-expressions.info/email.html // not an exhaustive email regex, which is impossible, but will catch obvious errors // is more lenient in most cases const EmailRegex = /^[A-Z0-9._%+-@]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,8}[A-Z]{2,63}$/i; export function isEmail(input: unknown): input is string { return isString(input) && EmailRegex.test(input); } const macAddressDelimiters = { colon: /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/, space: /^([0-9a-fA-F][0-9a-fA-F]\s){5}([0-9a-fA-F][0-9a-fA-F])$/, dash: /^([0-9a-fA-F][0-9a-fA-F]-){5}([0-9a-fA-F][0-9a-fA-F])$/, dot: /^([0-9a-fA-F]{4}\.){2}([0-9a-fA-F]{4})$/, none: /^([0-9a-fA-F]){12}$/ } as const; export function isMACAddress( input: unknown, delimiter?: MACDelimiter ): input is string { if (!isString(input)) return false; if (!delimiter || delimiter === 'any') { return Object.values(macAddressDelimiters).some((d) => d.test(input)); } return macAddressDelimiters[delimiter].test(input); } /** * A functional version of isMacAddress */ export function isMACAddressFP(args?: MACDelimiter) { return function _isMacAddressFP(input: unknown): input is string { return isMACAddress(input, args); }; } export function isURL(input: unknown): boolean { return isString(input) && validator.isURL(input); } export function isUUID(input: unknown): boolean { return isString(input) && validator.isUUID(input); } /** * Check whether a string includes another string */ export function contains(input: unknown, substring: string): input is string { return isString(input) && input.includes(substring); } /** * A function version of contains */ export function containsFP(substring: string) { return function _contains(input: unknown): input is string { return isString(input) && input.includes(substring); }; } export function isBase64(input: unknown): boolean { if (!isString(input)) return false; const validatorValid = validator.isBase64(input); if (validatorValid) { const decode = Buffer.from(input, 'base64').toString('utf8'); const encode = Buffer.from(decode, 'utf8').toString('base64'); return input === encode; } return false; } export function isFQDN(input: unknown): boolean { return isString(input) && validator.isFQDN(input); } export function isCountryCode(input: unknown): boolean { return isString(input) && validator.isISO31661Alpha2(input); } export function isPostalCode(input: unknown, locale: validator.PostalCodeLocale | 'any' = 'any'): boolean { return validator.isPostalCode(toString(input), locale); } export function isPort(input: unknown): boolean { return validator.isPort(toString(input)); } export function isAlpha(input: unknown, locale?: validator.AlphaLocale): boolean { return isString(input) && validator.isAlpha(input, locale); } export function isAlphaNumeric(input: unknown, locale?: validator.AlphanumericLocale): boolean { return isString(input) && validator.isAlphanumeric(input, locale); } export function isMIMEType(input: unknown): boolean { return validator.isMimeType(toString(input)); } /** * Maps an array of strings and and trims the result, or * parses a comma separated list and trims the result */ export function parseList(input: unknown): string[] { let strings: string[] = []; if (isString(input)) { strings = input.split(','); } else if (isArrayLike(input)) { strings = input.map((val) => { if (!val) return ''; return toString(val); }); } else { return []; } return strings.map((s) => s.trim()).filter((s) => !!s); } type JoinListType = string|number|boolean|symbol|null|undefined; /** * Create a sentence from a list (all items will be unique, empty values will be skipped) */ export function joinList( input: (JoinListType)[]|readonly (JoinListType)[], sep = ',', join = 'and' ): string { if (!Array.isArray(input)) { throw new Error('joinList requires input to be a array'); } const list = [ ...new Set(input .filter((str) => str != null && str !== '') .map((str) => toString(str).trim())) ]; if (list.length === 0) { throw new Error('joinList requires at least one string'); } if (list.length === 1) return `${list[0]}`; return list.reduce((acc, curr, index, arr) => { if (!acc) return curr; const isLast = (index + 1) === arr.length; if (isLast) { return `${acc} ${join} ${curr}`; } return `${acc}${sep} ${curr}`; }, ''); } export type StringEntropyFN = (input: unknown) => number // inspired from https://gist.github.com/jabney/5018b4adc9b2bf488696 /** Performs a Shannon entropy calculation on string inputs */ export function shannonEntropy(input: unknown): number { if (!isString(input)) { throw new Error(`Invalid input ${input}, must be of type String`); } let sum = 0; const len = input.length; const dict: Record<string, number> = Object.create(null); // get number of chars per string for (const char of input) { if (dict[char] != null) { dict[char]++; } else { dict[char] = 1; } } for (const num of Object.values(dict)) { const p = num / len; const pLogCalc = p * Math.log(p); sum -= pLogCalc / Math.log(2); } return sum; } export enum StringEntropy { shannon = 'shannon' } const StringEntropyDict: Record<StringEntropy, StringEntropyFN> = { [StringEntropy.shannon]: shannonEntropy }; /** returns a function to perform entropy calculations, currently only supports * the "shannon" algorithm * */ export function stringEntropy( algo: StringEntropy = StringEntropy.shannon ): StringEntropyFN { const fn = StringEntropyDict[algo]; if (fn == null) { const keys = Object.keys(StringEntropyDict); throw new Error(`Unsupported algorithm ${algo}, please use the available algorithms ${joinList(keys, ', ')}`); } return fn; }
the_stack
* DescribeAbnormalEvent返回参数结构体 */ export interface DescribeAbnormalEventResponse { /** * 返回的数据总条数 */ Total: number /** * 异常体验列表 */ AbnormalExperienceList: Array<AbnormalExperience> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 查询秒级监控返回的数据 */ export interface RealtimeData { /** * 返回的数据 注意:此字段可能返回 null,表示取不到有效值。 */ Content: Array<TimeValue> /** * 数据类型字段 */ DataType: string } /** * DescribeAbnormalEvent请求参数结构体 */ export interface DescribeAbnormalEventRequest { /** * 用户SDKAppID,查询SDKAppID下任意20条异常体验事件(可能不同房间) */ SdkAppId: string /** * 查询开始时间,本地unix时间戳(1592448600s) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1592449080s) */ EndTime: number /** * 房间号,查询房间内任意20条以内异常体验事件 */ RoomId?: string } /** * DescribeTrtcInteractiveTime返回参数结构体 */ export interface DescribeTrtcInteractiveTimeResponse { /** * 应用的用量信息数组。 */ Usages: Array<OneSdkAppIdUsagesInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyPicture返回参数结构体 */ export interface ModifyPictureResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * StartMCUMixTranscodeByStrRoomId请求参数结构体 */ export interface StartMCUMixTranscodeByStrRoomIdRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 字符串房间号。 */ StrRoomId: string /** * 混流输出控制参数。 */ OutputParams: OutputParams /** * 混流输出编码参数。 */ EncodeParams: EncodeParams /** * 混流输出布局参数。 */ LayoutParams: LayoutParams /** * 第三方CDN转推参数。 */ PublishCdnParams?: PublishCdnParams } /** * MCU混流布局参数 */ export interface LayoutParams { /** * 混流布局模板ID,0为悬浮模板(默认);1为九宫格模板;2为屏幕分享模板;3为画中画模板;4为自定义模板。 */ Template?: number /** * 屏幕分享模板、悬浮模板、画中画模板中有效,代表大画面对应的用户ID。 */ MainVideoUserId?: string /** * 屏幕分享模板、悬浮模板、画中画模板中有效,代表大画面对应的流类型,0为摄像头,1为屏幕分享。左侧大画面为web用户时此值填0。 */ MainVideoStreamType?: number /** * 画中画模板中有效,代表小画面的布局参数。 */ SmallVideoLayoutParams?: SmallVideoLayoutParams /** * 屏幕分享模板有效。设置为1时代表大画面居右,小画面居左布局。默认为0。 */ MainVideoRightAlign?: number /** * 悬浮模板、九宫格、屏幕分享模板有效。设置此参数后,输出流混合此参数中包含用户的音视频,以及其他用户的纯音频。最多可设置16个用户。 */ MixVideoUids?: Array<string> /** * 自定义模板中有效,指定用户视频在混合画面中的位置。 */ PresetLayoutConfig?: Array<PresetLayoutConfig> /** * 自定义模板中有效,设置为1时代表启用占位图功能,0时代表不启用占位图功能,默认为0。启用占位图功能时,在预设位置的用户没有上行视频时可显示对应的占位图。 */ PlaceHolderMode?: number /** * 悬浮模板、九宫格、屏幕分享模板生效,用于控制纯音频上行是否占用画面布局位置。设置为0是代表后台默认处理方式,悬浮小画面占布局位置,九宫格画面占布局位置、屏幕分享小画面不占布局位置;设置为1时代表纯音频上行占布局位置;设置为2时代表纯音频上行不占布局位置。默认为0。 */ PureAudioHoldPlaceMode?: number /** * 水印参数。 */ WaterMarkParams?: WaterMarkParams } /** * 返回的质量数据,时间:值 */ export interface TimeValue { /** * 时间,unix时间戳(1590065877s) */ Time: number /** * 当前时间返回参数取值,如(bigvCapFps在1590065877取值为0,则Value:0 ) */ Value: number } /** * CreatePicture请求参数结构体 */ export interface CreatePictureRequest { /** * 应用id */ SdkAppId: number /** * 图片内容经base64编码后的string格式 */ Content: string /** * 图片后缀名 */ Suffix: string /** * 图片长度 */ Height: number /** * 图片宽度 */ Width: number /** * 显示位置x轴方向 */ XPosition: number /** * 显示位置y轴方向 */ YPosition: number } /** * DescribeTrtcMcuTranscodeTime请求参数结构体 */ export interface DescribeTrtcMcuTranscodeTimeRequest { /** * 查询开始时间,格式为YYYY-MM-DD。 */ StartTime: string /** * 查询结束时间,格式为YYYY-MM-DD。 单次查询统计区间最多不能超过31天。 */ EndTime: string /** * 应用ID,可不传。传应用ID时返回的是该应用的用量,不传时返回多个应用的合计值。 */ SdkAppId?: number } /** * 查询旁路转码计费时长。 查询时间小于等于1天时,返回每5分钟粒度的数据;查询时间大于1天时,返回按天汇总的数据。 */ export interface SdkAppIdTrtcMcuTranscodeTimeUsage { /** * 本组数据对应的时间点,格式如:2020-09-07或2020-09-07 00:05:05。 */ TimeKey: string /** * 语音时长,单位:秒。 */ AudioTime: number /** * 视频时长-标清SD,单位:秒。 */ VideoTimeSd: number /** * 视频时长-高清HD,单位:秒。 */ VideoTimeHd: number /** * 视频时长-全高清FHD,单位:秒。 */ VideoTimeFhd: number } /** * RemoveUserByStrRoomId请求参数结构体 */ export interface RemoveUserByStrRoomIdRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 房间号。 */ RoomId: string /** * 要移出的用户列表,最多10个。 */ UserIds: Array<string> } /** * DescribeRealtimeScale返回参数结构体 */ export interface DescribeRealtimeScaleResponse { /** * 返回的数据数组 */ Data?: Array<RealtimeData> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DismissRoom返回参数结构体 */ export interface DismissRoomResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeRealtimeNetwork返回参数结构体 */ export interface DescribeRealtimeNetworkResponse { /** * 查询返回的数据 */ Data?: Array<RealtimeData> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeRecordStatistic请求参数结构体 */ export interface DescribeRecordStatisticRequest { /** * 查询开始日期,格式为YYYY-MM-DD。 */ StartTime: string /** * 查询结束日期,格式为YYYY-MM-DD。 单次查询统计区间最多不能超过31天。 */ EndTime: string /** * 应用ID,可不传。传应用ID时返回的是该应用的用量,不传时返回多个应用的合计值。 */ SdkAppId?: number } /** * DescribeUserInformation请求参数结构体 */ export interface DescribeUserInformationRequest { /** * 通话 ID(唯一标识一次通话): sdkappid_roomgString(房间号_createTime(房间创建时间,unix时间戳,单位为s)例:1400353843_218695_1590065777。通过 DescribeRoomInformation(查询房间列表)接口获取(链接:https://cloud.tencent.com/document/product/647/44050) */ CommId: string /** * 查询开始时间,14天内。本地unix时间戳(1590065777) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1590065877) */ EndTime: number /** * 用户SDKAppID(1400353843) */ SdkAppId: string /** * 需查询的用户数组,不填默认返回6个用户,最多可填6个用户 */ UserIds?: Array<string> /** * 设置分页index,从0开始(PageNumber和PageSize 其中一个不填均默认返回6条数据) */ PageNumber?: string /** * 设置分页大小(PageNumber和PageSize 其中一个不填均默认返回6条数据,PageSize最大不超过100) */ PageSize?: string } /** * DescribeCallDetail请求参数结构体 */ export interface DescribeCallDetailRequest { /** * 通话 ID(唯一标识一次通话): sdkappid_roomgString(房间号_createTime(房间创建时间,unix时间戳,单位为s)例:1400353843_218695_1590065777。通过 DescribeRoomInformation(查询房间列表)接口获取(链接:https://cloud.tencent.com/document/product/647/44050) */ CommId: string /** * 查询开始时间,14天内。本地unix时间戳(1590065777s),查询实时数据时,查询起止时间不超过1个小时。 */ StartTime: number /** * 查询结束时间,本地unix时间戳(1590065877s) */ EndTime: number /** * 用户SDKAppID(1400353843) */ SdkAppId: string /** * 需查询的用户数组,不填默认返回6个用户,最多可填6个用户 */ UserIds?: Array<string> /** * 需查询的指标,不填则只返回用户列表,填all则返回所有指标。 appCpu:APP CPU使用率; sysCpu:系统 CPU使用率; aBit:上/下行音频码率; aBlock:音频卡顿时长; bigvBit:上/下行视频码率; bigvCapFps:视频采集帧率; bigvEncFps:视频发送帧率; bigvDecFps:渲染帧率; bigvBlock:视频卡顿时长; aLoss:上/下行音频丢包; bigvLoss:上/下行视频丢包; bigvWidth:上/下行分辨率宽; bigvHeight:上/下行分辨率高 */ DataType?: Array<string> /** * 设置分页index,从0开始(PageNumber和PageSize 其中一个不填均默认返回6条数据) */ PageNumber?: string /** * 设置分页大小(PageNumber和PageSize 其中一个不填均默认返回6条数据,DataType,UserIds不为null,PageSize最大不超过6,DataType,UserIds为null,PageSize最大不超过100) */ PageSize?: string } /** * DescribeRealtimeNetwork请求参数结构体 */ export interface DescribeRealtimeNetworkRequest { /** * 查询开始时间,24小时内,本地unix时间戳(1588031999s) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1588031999s) */ EndTime: number /** * 用户sdkappid */ SdkAppId: string /** * 需查询的数据类型 sendLossRateRaw:上行丢包率 recvLossRateRaw:下行丢包率 */ DataType?: Array<string> } /** * DescribeUserInformation返回参数结构体 */ export interface DescribeUserInformationResponse { /** * 返回的用户总条数 */ Total: number /** * 用户信息列表 注意:此字段可能返回 null,表示取不到有效值。 */ UserList: Array<UserInformation> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * MCU混流输出流编码参数 */ export interface EncodeParams { /** * 混流-输出流音频采样率。取值为[48000, 44100, 32000, 24000, 16000, 8000],单位是Hz。 */ AudioSampleRate: number /** * 混流-输出流音频码率。取值范围[8,500],单位为kbps。 */ AudioBitrate: number /** * 混流-输出流音频声道数,取值范围[1,2],1表示混流输出音频为单声道,2表示混流输出音频为双声道。 */ AudioChannels: number /** * 混流-输出流宽,音视频输出时必填。取值范围[0,1920],单位为像素值。 */ VideoWidth?: number /** * 混流-输出流高,音视频输出时必填。取值范围[0,1080],单位为像素值。 */ VideoHeight?: number /** * 混流-输出流码率,音视频输出时必填。取值范围[1,10000],单位为kbps。 */ VideoBitrate?: number /** * 混流-输出流帧率,音视频输出时必填。取值范围[1,60],表示混流的输出帧率可选范围为1到60fps。 */ VideoFramerate?: number /** * 混流-输出流gop,音视频输出时必填。取值范围[1,5],单位为秒。 */ VideoGop?: number /** * 混流-输出流背景色,取值是十进制整数。常用的颜色有: 红色:0xff0000,对应的十进制整数是16724736。 黄色:0xffff00。对应的十进制整数是16776960。 绿色:0x33cc00。对应的十进制整数是3394560。 蓝色:0x0066ff。对应的十进制整数是26367。 黑色:0x000000。对应的十进制整数是0。 白色:0xFFFFFF。对应的十进制整数是16777215。 灰色:0x999999。对应的十进制整数是10066329。 */ BackgroundColor?: number /** * 混流-输出流背景图片,取值为实时音视频控制台上传的图片ID。 */ BackgroundImageId?: number /** * 混流-输出流音频编码类型,取值范围[0,1, 2],0为LC-AAC,1为HE-AAC,2为HE-AACv2。默认值为0。当音频编码设置为HE-AACv2时,只支持输出流音频声道数为双声道。HE-AAC和HE-AACv2支持的输出流音频采样率范围为[48000, 44100, 32000, 24000, 16000] */ AudioCodec?: number /** * 混流-输出流背景图片URL地址,支持png、jpg、jpeg、bmp格式,暂不支持透明通道。URL链接长度限制为512字节。BackgroundImageUrl和BackgroundImageId参数都填时,以BackgroundImageUrl为准。图片大小限制不超过10MB。 */ BackgroundImageUrl?: string } /** * RemoveUserByStrRoomId返回参数结构体 */ export interface RemoveUserByStrRoomIdResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * StartMCUMixTranscode请求参数结构体 */ export interface StartMCUMixTranscodeRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 房间号。 */ RoomId: number /** * 混流输出控制参数。 */ OutputParams: OutputParams /** * 混流输出编码参数。 */ EncodeParams: EncodeParams /** * 混流输出布局参数。 */ LayoutParams: LayoutParams /** * 第三方CDN转推参数。 */ PublishCdnParams?: PublishCdnParams } /** * DescribeRealtimeQuality返回参数结构体 */ export interface DescribeRealtimeQualityResponse { /** * 返回的数据类型 */ Data?: Array<RealtimeData> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * StopMCUMixTranscode请求参数结构体 */ export interface StopMCUMixTranscodeRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 房间号。 */ RoomId: number } /** * 用户信息,包括用户进房时间,退房时间等 */ export interface UserInformation { /** * 房间号 */ RoomStr: string /** * 用户Id */ UserId: string /** * 用户进房时间 */ JoinTs: number /** * 用户退房时间,用户没有退房则返回当前时间 */ LeaveTs: number /** * 终端类型 */ DeviceType: string /** * Sdk版本号 */ SdkVersion: string /** * 客户端IP地址 */ ClientIp: string /** * 判断用户是否已经离开房间 */ Finished: boolean } /** * DescribeHistoryScale请求参数结构体 */ export interface DescribeHistoryScaleRequest { /** * 用户sdkappid(1400188366) */ SdkAppId: string /** * 查询开始时间,5天内。本地unix时间戳(1587571000s) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1588034999s) */ EndTime: number } /** * DeletePicture请求参数结构体 */ export interface DeletePictureRequest { /** * 图片id */ PictureId: number /** * 应用id */ SdkAppId: number } /** * DescribeRoomInformation返回参数结构体 */ export interface DescribeRoomInformationResponse { /** * 返回当页数据总数 */ Total: number /** * 房间信息列表 */ RoomList: Array<RoomState> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 录制的使用信息。 */ export interface RecordUsage { /** * 本组数据对应的时间点,格式如:2020-09-07或2020-09-07 00:05:05。 */ TimeKey: string /** * 视频时长-标清SD,单位:秒。 */ Class1VideoTime: number /** * 视频时长-高清HD,单位:秒。 */ Class2VideoTime: number /** * 视频时长-超清HD,单位:秒。 */ Class3VideoTime: number /** * 语音时长,单位:秒。 */ AudioTime: number } /** * RemoveUser请求参数结构体 */ export interface RemoveUserRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 房间号。 */ RoomId: number /** * 要移出的用户列表,最多10个。 */ UserIds: Array<string> } /** * MCU混流的输出参数 */ export interface OutputParams { /** * 直播流 ID,由用户自定义设置,该流 ID 不能与用户旁路的流 ID 相同。 */ StreamId: string /** * 取值范围[0,1], 填0:直播流为音视频(默认); 填1:直播流为纯音频 */ PureAudioStream?: number /** * 自定义录制文件名称前缀。请先在实时音视频控制台开通录制功能,https://cloud.tencent.com/document/product/647/50768 */ RecordId?: string /** * 取值范围[0,1],填0无实际含义; 填1:指定录制文件格式为mp3。此参数不建议使用,建议在实时音视频控制台配置纯音频录制模板。 */ RecordAudioOnly?: number } /** * 事件信息,包括,事件时间戳,事件ID, */ export interface EventMessage { /** * 视频流类型: 0:与视频无关的事件; 2:视频为大画面; 3:视频为小画面; 7:视频为旁路画面; */ Type: number /** * 事件上报的时间戳,unix时间(1589891188801ms) */ Time: number /** * 事件Id:分为sdk的事件和webrtc的事件,详情见:附录/事件 ID 映射表:https://cloud.tencent.com/document/product/647/44916 */ EventId: number /** * 事件的第一个参数,如视频分辨率宽 */ ParamOne: number /** * 事件的第二个参数,如视频分辨率高 */ ParamTwo: number } /** * ModifyPicture请求参数结构体 */ export interface ModifyPictureRequest { /** * 图片id */ PictureId: number /** * 应用id */ SdkAppId: number /** * 图片长度 */ Height?: number /** * 图片宽度 */ Width?: number /** * 显示位置x轴方向 */ XPosition?: number /** * 显示位置y轴方向 */ YPosition?: number } /** * CreateTroubleInfo返回参数结构体 */ export interface CreateTroubleInfoResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * StopMCUMixTranscodeByStrRoomId请求参数结构体 */ export interface StopMCUMixTranscodeByStrRoomIdRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 字符串房间号。 */ StrRoomId: string } /** * Es返回的质量数据 */ export interface QualityData { /** * 数据内容 */ Content: Array<TimeValue> /** * 用户ID */ UserId: string /** * 对端Id,为空时表示上行数据 注意:此字段可能返回 null,表示取不到有效值。 */ PeerId: string /** * 数据类型 */ DataType: string } /** * 造成异常体验可能的异常事件类型 */ export interface AbnormalEvent { /** * 异常事件ID,具体值查看附录:异常体验ID映射表:https://cloud.tencent.com/document/product/647/44916 */ AbnormalEventId: number /** * 远端用户ID,"":表示异常事件不是由远端用户产生 注意:此字段可能返回 null,表示取不到有效值。 */ PeerId: string } /** * StopMCUMixTranscodeByStrRoomId返回参数结构体 */ export interface StopMCUMixTranscodeByStrRoomIdResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeRealtimeQuality请求参数结构体 */ export interface DescribeRealtimeQualityRequest { /** * 查询开始时间,24小时内。本地unix时间戳(1588031999s) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1588031999s) */ EndTime: number /** * 用户sdkappid */ SdkAppId: string /** * 查询的数据类型 enterTotalSuccPercent:进房成功率 fistFreamInSecRate:首帧秒开率 blockPercent:视频卡顿率 audioBlockPercent:音频卡顿率 */ DataType?: Array<string> } /** * DeletePicture返回参数结构体 */ export interface DeletePictureResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * StopMCUMixTranscode返回参数结构体 */ export interface StopMCUMixTranscodeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateTroubleInfo请求参数结构体 */ export interface CreateTroubleInfoRequest { /** * 应用的ID */ SdkAppId: string /** * 房间ID */ RoomId: string /** * 老师用户ID */ TeacherUserId: string /** * 学生用户ID */ StudentUserId: string /** * 体验异常端(老师或学生)的用户 ID。 */ TroubleUserId: string /** * 异常类型。 1. 仅视频异常 2. 仅声音异常 3. 音视频都异常 5. 进房异常 4. 切课 6. 求助 7. 问题反馈 8. 投诉 */ TroubleType: number /** * 异常发生的UNIX 时间戳,单位为秒。 */ TroubleTime: number /** * 异常详情 */ TroubleMsg: string } /** * sdk或webrtc的事件列表。 */ export interface EventList { /** * 数据内容 */ Content: Array<EventMessage> /** * 发送端的userId */ PeerId: string } /** * DismissRoom请求参数结构体 */ export interface DismissRoomRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 房间号。 */ RoomId: number } /** * DescribeDetailEvent返回参数结构体 */ export interface DescribeDetailEventResponse { /** * 返回的事件列表,若没有数据,会返回空数组。 */ Data: Array<EventList> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DismissRoomByStrRoomId请求参数结构体 */ export interface DismissRoomByStrRoomIdRequest { /** * TRTC的SDKAppId。 */ SdkAppId: number /** * 房间号。 */ RoomId: string } /** * StartMCUMixTranscode返回参数结构体 */ export interface StartMCUMixTranscodeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 旁路转码时长的查询结果 */ export interface OneSdkAppIdTranscodeTimeUsagesInfo { /** * 旁路转码时长查询结果数组 */ SdkAppIdTranscodeTimeUsages: Array<SdkAppIdTrtcMcuTranscodeTimeUsage> /** * 查询记录数量 */ TotalNum: number /** * 所查询的应用ID,可能值为:1-应用的应用ID,2-total,显示为total则表示查询的是所有应用的用量合计值。 */ SdkAppId: string } /** * DescribeTrtcMcuTranscodeTime返回参数结构体 */ export interface DescribeTrtcMcuTranscodeTimeResponse { /** * 应用的用量信息数组。 */ Usages: Array<OneSdkAppIdTranscodeTimeUsagesInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribePicture请求参数结构体 */ export interface DescribePictureRequest { /** * 应用ID */ SdkAppId: number /** * 图片ID,不填时返回该应用下所有图片 */ PictureId?: number /** * 每页数量,不填时默认为10 */ PageSize?: number /** * 页码,不填时默认为1 */ PageNo?: number } /** * SdkAppId级别录制时长数据。 */ export interface SdkAppIdRecordUsage { /** * SdkAppId的值。 */ SdkAppId: string /** * 统计的时间点数据。 */ Usages: Array<RecordUsage> } /** * 单个SdkAppId的音视频互动计费时长用量数组和数组长度。 */ export interface OneSdkAppIdUsagesInfo { /** * 该 SdkAppId 对应的用量记录数长度 */ TotalNum: number /** * 用量数组 */ SdkAppIdTrtcTimeUsages: Array<SdkAppIdTrtcUsage> /** * 应用ID */ SdkAppId: string } /** * 画中画模板中有效,代表小画面的布局参数 */ export interface SmallVideoLayoutParams { /** * 代表小画面对应的用户ID。 */ UserId: string /** * 代表小画面对应的流类型,0为摄像头,1为屏幕分享。小画面为web用户时此值填0。 */ StreamType: number /** * 小画面在输出时的宽度,单位为像素值,不填默认为0。 */ ImageWidth?: number /** * 小画面在输出时的高度,单位为像素值,不填默认为0。 */ ImageHeight?: number /** * 小画面在输出时的X偏移,单位为像素值,LocationX与ImageWidth之和不能超过混流输出的总宽度,不填默认为0。 */ LocationX?: number /** * 小画面在输出时的Y偏移,单位为像素值,LocationY与ImageHeight之和不能超过混流输出的总高度,不填默认为0。 */ LocationY?: number } /** * RemoveUser返回参数结构体 */ export interface RemoveUserResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 自定义模板中有效,指定用户视频在混合画面中的位置。 */ export interface PresetLayoutConfig { /** * 指定显示在该画面上的用户ID。如果不指定用户ID,会按照用户加入房间的顺序自动匹配PresetLayoutConfig中的画面设置。 */ UserId?: string /** * 当该画面指定用户时,代表用户的流类型。0为摄像头,1为屏幕分享。小画面为web用户时此值填0。 */ StreamType?: number /** * 该画面在输出时的宽度,单位为像素值,不填默认为0。 */ ImageWidth?: number /** * 该画面在输出时的高度,单位为像素值,不填默认为0。 */ ImageHeight?: number /** * 该画面在输出时的X偏移,单位为像素值,LocationX与ImageWidth之和不能超过混流输出的总宽度,不填默认为0。 */ LocationX?: number /** * 该画面在输出时的Y偏移,单位为像素值,LocationY与ImageHeight之和不能超过混流输出的总高度,不填默认为0。 */ LocationY?: number /** * 该画面在输出时的层级,不填默认为0。 */ ZOrder?: number /** * 该画面在输出时的显示模式:0为裁剪,1为缩放,2为缩放并显示黑底。不填默认为0。 */ RenderMode?: number /** * 该当前位置用户混入的流类型:0为混入音视频,1为只混入视频,2为只混入音频。默认为0,建议配合指定用户ID使用。 */ MixInputType?: number /** * 占位图ID。启用占位图功能时,在当前位置的用户没有上行视频时显示占位图。占位图在实时音视频控制台上传并生成,https://cloud.tencent.com/document/product/647/50769 */ PlaceImageId?: number } /** * DescribeRealtimeScale请求参数结构体 */ export interface DescribeRealtimeScaleRequest { /** * 查询开始时间,24小时内。本地unix时间戳(1588031999s) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1588031999s) */ EndTime: number /** * 用户sdkappid */ SdkAppId: string /** * 查询的数据类型 UserNum:通话人数; RoomNum:房间数 */ DataType?: Array<string> } /** * DescribeCallDetail返回参数结构体 */ export interface DescribeCallDetailResponse { /** * 返回的用户总条数 */ Total: number /** * 用户信息列表 注意:此字段可能返回 null,表示取不到有效值。 */ UserList: Array<UserInformation> /** * 质量数据 注意:此字段可能返回 null,表示取不到有效值。 */ Data: Array<QualityData> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribePicture返回参数结构体 */ export interface DescribePictureResponse { /** * 返回的图片记录数 */ Total: number /** * 图片信息列表 */ PictureInfo: Array<PictureInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 查询音视频互动时长的输出数据。 查询时间小于等于1天时,返回每5分钟粒度的数据;查询时间大于1天时,返回按天汇总的数据。 */ export interface SdkAppIdTrtcUsage { /** * 本组数据对应的时间点,格式如:2020-09-07或2020-09-07 00:05:05。 */ TimeKey: string /** * 语音时长,单位:秒。 */ AudioTime: number /** * 音视频时长,单位:秒。 2019年10月11日前注册,没有变更为 [新计费模式](https://cloud.tencent.com/document/product/647/17157) 的用户才会返回此值。 */ AudioVideoTime: number /** * 视频时长-标清SD,单位:秒。 */ VideoTimeSd: number /** * 视频时长-高清HD,单位:秒。 */ VideoTimeHd: number /** * 视频时长-超清HD,单位:秒。 */ VideoTimeHdp: number } /** * DescribeTrtcInteractiveTime请求参数结构体 */ export interface DescribeTrtcInteractiveTimeRequest { /** * 查询开始时间,格式为YYYY-MM-DD。 */ StartTime: string /** * 查询结束时间,格式为YYYY-MM-DD。 单次查询统计区间最多不能超过31天。 */ EndTime: string /** * 应用ID,可不传。传应用ID时返回的是该应用的用量,不传时返回所有应用的合计值。 */ SdkAppId?: number } /** * 第三方CDN转推参数 */ export interface PublishCdnParams { /** * 腾讯云直播BizId。 */ BizId: number /** * 第三方CDN转推的目的地址,同时只支持转推一个第三方CDN地址。 */ PublishCdnUrls: Array<string> } /** * DescribeRoomInformation请求参数结构体 */ export interface DescribeRoomInformationRequest { /** * 用户sdkappid */ SdkAppId: string /** * 查询开始时间,14天内。本地unix时间戳(1588031999) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1588034999) */ EndTime: number /** * 字符串房间号 */ RoomId?: string /** * 分页index,从0开始(PageNumber和PageSize 其中一个不填均默认返回10条数据) */ PageNumber?: string /** * 分页大小(PageNumber和PageSize 其中一个不填均默认返回10条数据,最大不超过100) */ PageSize?: string } /** * 历史规模信息 */ export interface ScaleInfomation { /** * 每天开始的时间 */ Time: number /** * 房间人数,用户重复进入同一个房间为1次 注意:此字段可能返回 null,表示取不到有效值。 */ UserNumber: number /** * 房间人次,用户每次进入房间为一次 注意:此字段可能返回 null,表示取不到有效值。 */ UserCount: number /** * sdkappid下一天内的房间数 注意:此字段可能返回 null,表示取不到有效值。 */ RoomNumbers: number } /** * DescribeDetailEvent请求参数结构体 */ export interface DescribeDetailEventRequest { /** * 通话 ID(唯一标识一次通话): sdkappid_roomgString(房间号_createTime(房间创建时间,unix时间戳,单位s)。通过 DescribeRoomInformation(查询房间列表)接口获取。(链接:https://cloud.tencent.com/document/product/647/44050) */ CommId: string /** * 查询开始时间,14天内。本地unix时间戳(1588055615s) */ StartTime: number /** * 查询结束时间,本地unix时间戳(1588058615s) */ EndTime: number /** * 用户id */ UserId: string /** * 房间号 */ RoomId: string } /** * 用户的异常体验及可能的原因 */ export interface AbnormalExperience { /** * 用户ID */ UserId: string /** * 异常体验ID */ ExperienceId: number /** * 字符串房间号 */ RoomId: string /** * 异常事件数组 */ AbnormalEventList: Array<AbnormalEvent> /** * 异常事件的上报时间 */ EventTime: number } /** * 房间信息列表 */ export interface RoomState { /** * 通话ID(唯一标识一次通话) */ CommId: string /** * 房间号 */ RoomString: string /** * 房间创建时间 */ CreateTime: number /** * 房间销毁时间 */ DestroyTime: number /** * 房间是否已经结束 */ IsFinished: boolean /** * 房间创建者Id */ UserId: string } /** * CreatePicture返回参数结构体 */ export interface CreatePictureResponse { /** * 图片id */ PictureId: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * MCU混流水印参数 */ export interface WaterMarkParams { /** * 混流-水印图片ID。取值为实时音视频控制台上传的图片ID。 */ WaterMarkId: number /** * 混流-水印宽。单位为像素值。 */ WaterMarkWidth: number /** * 混流-水印高。单位为像素值。 */ WaterMarkHeight: number /** * 水印在输出时的X偏移。单位为像素值。 */ LocationX: number /** * 水印在输出时的Y偏移。单位为像素值。 */ LocationY: number /** * 混流-水印图片URL地址,支持png、jpg、jpeg、bmp格式,暂不支持透明通道。URL链接长度限制为512字节。WaterMarkUrl和WaterMarkId参数都填时,以WaterMarkUrl为准。图片大小限制不超过10MB。 */ WaterMarkUrl?: string } /** * DescribeRecordStatistic返回参数结构体 */ export interface DescribeRecordStatisticResponse { /** * 应用的用量信息数组。 */ SdkAppIdUsages?: Array<SdkAppIdRecordUsage> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DismissRoomByStrRoomId返回参数结构体 */ export interface DismissRoomByStrRoomIdResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeHistoryScale返回参数结构体 */ export interface DescribeHistoryScaleResponse { /** * 返回的数据条数 */ Total: number /** * 返回的数据 注意:此字段可能返回 null,表示取不到有效值。 */ ScaleList: Array<ScaleInfomation> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * StartMCUMixTranscodeByStrRoomId返回参数结构体 */ export interface StartMCUMixTranscodeByStrRoomIdResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 图片列表信息 */ export interface PictureInfo { /** * 图片长度 */ Height: number /** * 图片宽度 */ Width: number /** * 显示位置x轴方向 */ XPosition: number /** * 显示位置y轴方向 */ YPosition: number /** * 应用id */ SdkAppId: number /** * 图片id */ PictureId: number }
the_stack
import { Graph, Node, Edge, Shape, EdgeView, Line, Angle, Registry, } from '@antv/x6' Graph.registerNode( 'angle-node', Shape.Rect.define({ width: 120, height: 120, zIndex: 1, attrs: { body: { fill: '#f5f5f5', stroke: '#d9d9d9', strokeWidth: 1, rx: 2, ry: 2, }, }, }), true, ) Graph.registerEdge( 'angle-edge', { markup: [ { tagName: 'path', selector: 'wrap', attrs: { fill: 'none', cursor: 'pointer', stroke: 'transparent', strokeLinecap: 'round', }, }, { tagName: 'path', selector: 'line', attrs: { fill: 'none', pointerEvents: 'none', }, }, { tagName: 'path', selector: 'sourceAngle', groupSelector: 'angles', attrs: { cursor: 'pointer', }, }, { tagName: 'path', selector: 'targetAngle', groupSelector: 'angles', attrs: { cursor: 'pointer', }, }, { tagName: 'text', selector: 'sourceAngleLabel', groupSelector: 'angleLabels', }, { tagName: 'text', selector: 'targetAngleLabel', groupSelector: 'angleLabels', }, ], attrs: { wrapper: { connection: true, strokeWidth: 10, strokeLinejoin: 'round', }, line: { connection: true, stroke: '#333333', strokeWidth: 2, strokeLinejoin: 'round', }, angles: { stroke: '#333333', fill: 'none', strokeWidth: 1, angle: { radius: 40, pie: false, }, }, sourceAngle: { angle: { type: 'source', }, }, targetAngle: { angle: { type: 'target', }, }, angleLabels: { textAnchor: 'middle', textVerticalAnchor: 'middle', fill: '#333', fontSize: 11, fontFamily: 'sans-serif', angleText: { distance: 23, precision: 0, }, }, sourceAngleLabel: { angleText: { type: 'source', }, }, targetAngleLabel: { angleText: { type: 'target', }, }, }, attrHooks: { angle: { set(val, { view }) { const defaults = { d: 'M 0 0 0 0' } if (val == null || typeof val !== 'object') { return defaults } const attr = (val as {}) as AngleEdge.AngleOptions var angleRadius = attr.radius || 40 var angleStart = attr.start || 'self' var anglePie = attr.pie || false var angleDirection = attr.direction || 'small' const meta = AngleEdge.getArcMeta(view as EdgeView, attr.type, { angle: attr.value, radius: angleRadius, start: angleStart, direction: angleDirection, }) if (meta == null) { return defaults } var connectionPoint = meta.connectionPoint, linkArcPoint = meta.arcPoint1, otherArcPoint = meta.arcPoint2, arcAngle = meta.arcAngle, largeArcFlag = meta.largeArcFlag, sweepFlag = meta.sweepFlag const segments = [ `M ${linkArcPoint.x} ${linkArcPoint.y}`, // A rx ry x-axis-rotation large-arc-flag sweep-flag x y `A ${angleRadius} ${angleRadius} ${arcAngle} ${largeArcFlag} ${sweepFlag} ${otherArcPoint.x} ${otherArcPoint.y}`, ] if (anglePie) { segments.push(`L ${connectionPoint.x} ${connectionPoint.y} Z`) } return { d: segments.join(' '), } }, }, angleText: { set(val, options) { let text = '' const view = options.view as EdgeView const attr = (val as {}) as AngleEdge.AngleTextOptions let meta = AngleEdge.getArcMeta(view, attr.type, { radius: 40 }) if (meta) { text = AngleEdge.getAngleText({ angle: meta.angleBetween, precision: attr.precision, }) } const raw = Registry.Attr.presets.text as Registry.Attr.SetDefinition raw.set.call(this, text, options) // update text position const distance = attr.distance || 60 meta = AngleEdge.getArcMeta(view, attr.type, { radius: distance }) if (!meta) { return {} } var line: Line const connectionPoint = meta.connectionPoint const arcPoint1 = meta.arcPoint1 const arcPoint2 = meta.arcPoint2 const angleBetween = meta.angleBetween const largeArcFlag = meta.largeArcFlag if (Math.abs(angleBetween - 180) < 1e-6) { const p = arcPoint1 .clone() .rotate(largeArcFlag ? 90 : -90, connectionPoint) line = new Line(connectionPoint, p).setLength(distance) } else { const c = new Line(arcPoint1, arcPoint2).getCenter() ;(line = new Line(connectionPoint, c).setLength(distance)), largeArcFlag && line.scale(-1, -1, line.start) } const pos = line.end const angle = Angle.normalize(((line.angle() + 90) % 180) - 90) return { transform: `translate(${pos.x}, ${pos.y}) rotate(${angle})`, } }, }, }, }, true, ) namespace Cache { function ensure(view: EdgeView) { const cacheKey = 'angleData' const cache = view.getDataOfElement(view.container) if (!(cacheKey in cache)) { cache[cacheKey] = {} } return (cache[cacheKey] as Object) as { [key: string]: AngleEdge.Metadata | null } } export function get( view: EdgeView, type: Edge.TerminalType, ): AngleEdge.Metadata | null { const cache = ensure(view) return cache[type] || null } export function set( view: EdgeView, type: Edge.TerminalType, meta: AngleEdge.Metadata | null, ) { const cache = ensure(view) cache[type] = meta return meta } } namespace AngleEdge { export type AngleStart = 'self' | 'source' | 'target' export type AngleDirection = 'clockwise' | 'anticlockwise' | 'small' | 'large' export type Metadata = ReturnType<typeof calc> export interface AngleOptions { type: Edge.TerminalType start?: AngleStart direction?: AngleDirection radius?: number value?: number pie?: boolean } export interface AngleTextOptions { type: Edge.TerminalType precision?: number distance?: number } export function getArcMeta( edgeView: EdgeView, terminalType: Edge.TerminalType, options: { angle?: number radius: number start?: AngleStart direction?: AngleDirection }, ): Metadata | null { let meta = Cache.get(edgeView, terminalType) if (meta) { return meta } const isValidAngle = typeof options.angle === 'number' const terminalView = edgeView.getTerminalView(terminalType) if (!terminalView && !isValidAngle) { return null } var isTarget = terminalType === 'target' var tangent = edgeView.getTangentAtRatio(isTarget ? 1 : 0) if (!tangent) { return null } if (isTarget) { tangent.scale(-1, -1, tangent.start) } // angle is specified if (typeof options.angle === 'number') { const ref = tangent.clone().rotate(-options.angle, tangent.start) meta = calc(tangent, ref, { start: 'target', radius: options.radius, direction: options.angle < 0 ? 'clockwise' : 'anticlockwise', }) } else if (terminalView) { const terminalCell = terminalView.cell if (terminalCell.isEdge()) { // terminal is another edge const terminalEdgeView = terminalView as EdgeView const p = terminalEdgeView.getClosestPointLength(tangent.start)! const ref = terminalEdgeView.getTangentAtLength(p)! meta = calc(tangent, ref, options) } else if (terminalCell.isNode()) { // terminal is node const magnet = edgeView.getTerminalMagnet(terminalType) as SVGElement if (!magnet) { return null } const angleRadius = options.radius const angleDirection = options.direction const terminalNode = terminalCell as Node const bbox = terminalNode.getBBox() const angle = terminalNode.getAngle() const center = bbox.getCenter() const magnetBBox = terminalView.getUnrotatedBBoxOfElement(magnet) const end = tangent.clone().setLength(1).end.rotate(angle, center) if (magnetBBox.containsPoint(end)) { return null } let sweepFlag = 0 let tx = 0 let ty = 0 let arcAngle = tangent.angle() - angle if (end.y > magnetBBox.y + magnetBBox.height || end.y < magnetBBox.y) { arcAngle += 90 tx = angleRadius } else { ty = angleRadius } arcAngle = Angle.normalize(arcAngle) const quadrant = Math.floor(arcAngle / 90) switch (quadrant) { case 0: sweepFlag = 1 break case 1: sweepFlag = 0 break case 2: tx *= -1 ty *= -1 sweepFlag = 1 break case 3: tx *= -1 ty *= -1 sweepFlag = 0 } let sweep = false switch (angleDirection) { case 'large': sweep = true break case 'anticlockwise': sweep = 0 === quadrant || 2 === quadrant break case 'clockwise': sweep = 1 === quadrant || 3 === quadrant break } if (sweep) { tx *= -1 ty *= -1 sweepFlag ^= 1 } const startLine = tangent.setLength(angleRadius) const connectionPoint = startLine.start const arcPoint1 = startLine.end const arcPoint2 = connectionPoint .clone() .translate(tx, ty) .rotate(-angle, connectionPoint) let angleBetween = connectionPoint.angleBetween(arcPoint1, arcPoint2) if (180 < angleBetween) { angleBetween = 360 - angleBetween } meta = { connectionPoint: connectionPoint, arcPoint1: arcPoint1, arcPoint2: arcPoint2, sweepFlag: sweepFlag, largeArcFlag: 0, arcAngle: arcAngle, angleBetween: angleBetween, } } } Cache.set(edgeView, terminalType, meta) return meta } function calc( line: Line, ref: Line, options: { radius: number start?: AngleStart direction?: AngleDirection }, ) { const angleStart = options.start const angleRadius = options.radius let angleDirection = options.direction const startLine = line.setLength(angleRadius) const endLine = ref.setLength(angleRadius) const arcAngle = line.angle() const connectionPoint = startLine.start const arcPoint1 = startLine.end let arcPoint2 = endLine.end let angleBetween = connectionPoint.angleBetween(arcPoint1, arcPoint2) let sweepFlag = 1 let largeArcFlag = 0 const quadrant = Math.floor(angleBetween / 90) let reflect = false let antifix = false let normalize = true switch (angleStart) { case 'target': { if (angleDirection === 'small') { angleDirection = angleBetween < 180 ? 'clockwise' : 'anticlockwise' } if (angleDirection === 'large') { angleDirection = 180 < angleBetween ? 'clockwise' : 'anticlockwise' } switch (angleDirection) { case 'anticlockwise': if (0 < angleBetween && angleBetween < 180) { largeArcFlag ^= 1 } antifix = true break case 'clockwise': default: if (180 <= angleBetween) { largeArcFlag ^= 1 } sweepFlag ^= 1 break } normalize = false break } case 'source': { if (angleDirection === 'small') { angleDirection = 180 < angleBetween ? 'clockwise' : 'anticlockwise' } else if (angleDirection === 'large') { angleDirection = angleBetween < 180 ? 'clockwise' : 'anticlockwise' } switch (angleDirection) { case 'anticlockwise': { if (180 < angleBetween) { largeArcFlag ^= 1 } sweepFlag = 1 antifix = true break } default: case 'clockwise': { if (angleBetween < 180) { largeArcFlag ^= 1 } sweepFlag = 0 break } } normalize = false reflect = true angleBetween = Angle.normalize(angleBetween + 180) break } case 'self': default: { switch (angleDirection) { case 'anticlockwise': { reflect = 0 === quadrant || 1 === quadrant sweepFlag = 1 antifix = true break } case 'clockwise': { reflect = 2 === quadrant || 3 === quadrant sweepFlag = 0 antifix = false break } case 'small': { reflect = 1 === quadrant || 2 === quadrant sweepFlag = 0 === quadrant || 2 === quadrant ? 0 : 1 antifix = 1 === quadrant || 3 === quadrant break } case 'large': { reflect = 0 === quadrant || 3 === quadrant sweepFlag = 1 === quadrant || 3 === quadrant ? 0 : 1 antifix = 0 === quadrant || 2 === quadrant break } } } } if (reflect) { arcPoint2 = arcPoint2.reflection(connectionPoint) } if (normalize && 180 <= angleBetween) { angleBetween = Angle.normalize(angleBetween - 180) } if (antifix) { angleBetween = Angle.normalize((normalize ? 180 : 360) - angleBetween) } return { connectionPoint: connectionPoint, arcPoint1: arcPoint1, arcPoint2: arcPoint2, largeArcFlag: largeArcFlag, sweepFlag: sweepFlag, arcAngle: arcAngle, angleBetween: angleBetween, } } export function getAngleText( options: { angle?: number; precision?: number } = {}, ) { const angle = options.angle != null ? options.angle : 0 const decimalPoints = options.precision == null ? 2 : options.precision return `${angle.toFixed(decimalPoints)}°` } }
the_stack
import { $log } from '@tsed/logger'; import { BigNumber } from 'bignumber.js'; import moment from 'moment'; import { bootstrap, TestTz } from '../bootstrap-sandbox'; import { Contract, address, bytes, nat, mutez, key } from '../../src/type-aliases'; import { InternalOperationResult } from '@taquito/rpc'; import { originateEnglishAuctionTezOffchainBid, MintNftParam, originateNftFaucet, } from '../../src/nft-contracts'; import { ContractAbstraction, ContractProvider, MichelsonMap, TezosToolkit } from '@taquito/taquito'; import { addOperator } from '../../src/fa2-interface'; import { Fa2_token, Tokens, sleep } from '../../src/auction-interface'; import { queryBalancesWithLambdaView, hasTokens, QueryBalances } from '../../test/fa2-balance-inspector'; import { errors_to_missigned_bytes, Permit, dummy_sig, } from '../../src/permit'; jest.setTimeout(360000); // 6 minutes interface OffchainBidData { asset_id : nat; bid_amount : mutez; } interface PermitBidParam { offchain_bid_data : OffchainBidData; permit : Permit; } async function createPermit( signerKey : key, assetId: nat, bidAmount : mutez, auction : ContractAbstraction<ContractProvider>, permitSigner : TezosToolkit, submitter : TezosToolkit ): Promise<PermitBidParam> { const fake_permit : Permit = { signerKey : signerKey, signature : dummy_sig, }; const offchain_bid_data : OffchainBidData = { asset_id : assetId, bid_amount : bidAmount, }; const fake_permit_bid_param : PermitBidParam = { offchain_bid_data : offchain_bid_data, permit : fake_permit, }; // Bob preapplies a transfer with the dummy_sig to extract the bytes_to_sign const transfer_params = auction.methodsObject.offchain_bid(fake_permit_bid_param) .toTransferParams({ amount : 0 }); const bytes_to_sign = await submitter.estimate.transfer(transfer_params) .catch((e) => errors_to_missigned_bytes(e.errors)); $log.info('bytes_to_sign:', bytes_to_sign); // Alice sign the parameter const param_sig = await permitSigner.signer.sign(bytes_to_sign).then(s => s.prefixSig); const one_step_permit : Permit = { signerKey : signerKey, signature : param_sig, }; const permit_bid_param : PermitBidParam = { offchain_bid_data : offchain_bid_data, permit : one_step_permit, }; // This is what a relayer needs to submit the parameter on the signer's behalf $log.info('permit package:', permit_bid_param); return permit_bid_param; }; describe('test NFT auction', () => { let tezos: TestTz; let nftAuction: Contract; let nftAuctionBob : Contract; let nftAuctionAlice : Contract; let nftAuctionEve : Contract; let nftContract : Contract; let bobAddress : address; let aliceAddress : address; let eveAddress : address; let aliceKey : key; let eveKey : key; let startTime : Date; let endTime : Date; let tokenId : BigNumber; let empty_metadata_map : MichelsonMap<string, bytes>; let mintToken : MintNftParam; let assetId : nat; let queryBalances : QueryBalances; let dummy_permit_bid_param : PermitBidParam; beforeAll(async () => { tezos = await bootstrap(); empty_metadata_map = new MichelsonMap(); tokenId = new BigNumber(0); bobAddress = await tezos.bob.signer.publicKeyHash(); aliceAddress = await tezos.alice.signer.publicKeyHash(); eveAddress = await tezos.eve.signer.publicKeyHash(); eveKey = await tezos.eve.signer.publicKey(); aliceKey = await tezos.alice.signer.publicKey(); mintToken = { token_metadata: { token_id: tokenId, token_info: empty_metadata_map, }, owner: bobAddress, }; queryBalances = queryBalancesWithLambdaView(tezos.lambdaView); assetId = new BigNumber(0); }); beforeEach(async() => { $log.info('originating nft auction...'); nftAuction = await originateEnglishAuctionTezOffchainBid(tezos.bob); nftAuctionBob = await tezos.bob.contract.at(nftAuction.address); nftAuctionAlice = await tezos.alice.contract.at(nftAuction.address); nftAuctionEve = await tezos.eve.contract.at(nftAuction.address); $log.info('originating nft faucets...'); nftContract = await originateNftFaucet(tezos.bob); $log.info('minting token'); const opMint = await nftContract.methods.mint([mintToken]).send(); await opMint.confirmation(); $log.info(`Minted tokens. Consumed gas: ${opMint.consumedGas}`); $log.info('adding auction contract as operator'); await addOperator(nftContract.address, tezos.bob, nftAuction.address, tokenId); $log.info('Auction contract added as operator'); const fa2_token : Fa2_token = { token_id : tokenId, amount : new BigNumber(1), }; const tokens : Tokens = { fa2_address : nftContract.address, fa2_batch : [fa2_token], }; startTime = moment.utc().add(7, 'seconds').toDate(); endTime = moment(startTime).add(90, 'seconds').toDate(); const opAuction = await nftAuctionBob.methods.configure( //opening price = 10 tz new BigNumber(10000000), //percent raise =10 new BigNumber(10), //min_raise = 10tz new BigNumber(10000000), //round_time = 1 hr new BigNumber(3600), //extend_time = 0 seconds new BigNumber(0), //assset [tokens], //start_time = now + 7seconds startTime, //end_time = start_time + 90 seconds, endTime, ).send({ amount : 0 }); await opAuction.confirmation(); $log.info(`Auction configured. Consumed gas: ${opAuction.consumedGas}`); await sleep(7000); //7 seconds }); test('resovled auction with winning offchain bid should only send NFT to winning bidder, not send payment', async () => { const bidMutez = new BigNumber(10000000); const permit_bid_param = await createPermit(aliceKey, assetId, bidMutez, nftAuctionBob, tezos.alice, tezos.bob); const opBid = await nftAuctionBob.methodsObject .offchain_bid(permit_bid_param).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); await sleep(90000); //90 seconds $log.info("Resolving auction"); const opResolve = await nftAuctionBob.methods.resolve(0).send({ amount : 0 }); await opResolve.confirmation(); $log.info("Auction Resolve"); const [aliceHasNft] = await hasTokens([ { owner: aliceAddress, token_id: tokenId }, ], queryBalances, nftContract); expect(aliceHasNft).toBe(true); $log.info(`NFT sent to winning bidder as expected`); const internalOps = opResolve.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]; expect(internalOps.length).toEqual(1); expect(internalOps[0].destination).toEqual(nftContract.address); }); test('offchain bid outbid by normal bid should not return offchain bid', async () => { const bidMutez = new BigNumber(10000000); const permit_bid_param = await createPermit(aliceKey, assetId, bidMutez, nftAuctionBob, tezos.alice, tezos.bob); const opBid = await nftAuctionBob.methodsObject .offchain_bid(permit_bid_param).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); const outBidMutez = new BigNumber(200000000); const opOutbid = await nftAuctionEve.methods.bid(0).send({ amount : outBidMutez.toNumber(), mutez : true }); await opOutbid.confirmation(); $log.info(`Bid placed`); const internalOps = opOutbid.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]; expect(internalOps).toBeUndefined(); }); test('offchain bid outbid by another offchain bid should not return first offchain bid', async () => { const bidMutez = new BigNumber(10000000); const permit_bid_param = await createPermit(aliceKey, assetId, bidMutez, nftAuctionBob, tezos.alice, tezos.bob); const opBid = await nftAuctionBob.methodsObject .offchain_bid(permit_bid_param).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); const outBidMutez = new BigNumber(20000000); const permit_outbid_param = await createPermit(eveKey, assetId, outBidMutez, nftAuctionBob, tezos.eve, tezos.bob); const opOutbid = await nftAuctionBob.methodsObject .offchain_bid(permit_outbid_param).send({ amount : 0 }); await opOutbid.confirmation(); $log.info(`Bid placed`); const internalOps = opOutbid.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]; expect(internalOps).toBeUndefined(); }); test('Offchain bid outbidding normal bid should return that bid', async () => { const bidMutez = new BigNumber(10000000); const opBid = await nftAuctionEve.methods.bid(0).send({ amount : bidMutez.toNumber(), mutez : true }); await opBid.confirmation(); $log.info(`Bid placed. Amount sent: ${opBid.amount} mutez`); const outBidMutez = new BigNumber(20000000); const permit_outbid_param = await createPermit(aliceKey, assetId, outBidMutez, nftAuctionBob, tezos.alice, tezos.bob); const opOutbid = await nftAuctionBob.methodsObject .offchain_bid(permit_outbid_param).send({ amount : 0 }); await opOutbid.confirmation(); $log.info(`Bid placed`); const internalOps = opOutbid.operationResults[0].metadata.internal_operation_results as InternalOperationResult[]; expect(internalOps.length).toEqual(1); const feeOp = internalOps[0]; const amountReturned = feeOp.amount; const feeDestination = feeOp.destination; expect(amountReturned).toEqual(bidMutez.toString()); expect(feeDestination).toEqual(eveAddress); }); test('Offchain bid by non admin should fail', async () => { dummy_permit_bid_param = { offchain_bid_data : { asset_id : new BigNumber(0), bid_amount : new BigNumber(0), }, permit : { signerKey : aliceKey, signature : dummy_sig, }, }; const opBid = nftAuctionAlice.methodsObject .offchain_bid(dummy_permit_bid_param).send({ amount : 0 }); expect(opBid).rejects.toHaveProperty('message', 'NOT_AN_ADMIN'); }); });
the_stack
import server from "../config/oauth2orize-server"; import passport from "passport"; import login from "connect-ensure-login"; import Client from "../models/OAuth/Client"; import ClientCollection from "../models/OAuth/ClientCollection"; import AccessToken from "../models/OAuth/AccessToken"; import AccessTokenCollection from "../models/OAuth/AccessTokenCollection"; import UserDocument from "../models/User/UserDocument"; import UserCollection, { postFind } from "../models/User/UserCollection"; import { RequestHandler } from "express"; import { Request, Response, NextFunction } from "express"; import { IVerifyOptions } from "passport-local"; import { MiddlewareRequest } from "oauth2orize"; import storage, { CONTAINER_AVATAR } from "../repository/storage"; import { validationResult } from "express-validator"; import { validationErrorResponse } from "./utils"; import _ from "lodash"; import { getBlobNameFromUrl } from "../repository/utils"; import AuthenticationResponse from "../../client/core/src/models/response/AuthenticationResponse"; import * as NotificationStorage from "../models/Notification/NotificationStorage"; import Notification from "../../client/core/src/models/Notification.d"; import User from "../../client/core/src/models/User"; import { FLAG_ENABLE_OTP_FOR_VERIFICATION, FLAG_ENABLE_INVITATION_CODE } from "../../client/core/src/shared/constants"; import { refreshOtpThenSendToUser, OTP_LENGTH } from "../models/User/UserStorage"; import { invitationCode } from "../../client/core/src/shared/data/invitationCode"; // User authorization endpoint. // // `authorization` middleware accepts a `validate` callback which is // responsible for validating the client making the authorization request. In // doing so, is recommended that the `redirectUri` be checked against a // registered value, although security requirements may vary across // implementations. Once validated, the `done` callback must be invoked with // a `client` instance, as well as the `redirectUri` to which the user will be // redirected after an authorization decision is obtained. // // This middleware simply initializes a new authorization transaction. It is // the application's responsibility to authenticate the user and render a dialog // to obtain their approval (displaying details about the client requesting // authorization). We accomplish that here by routing through `ensureLoggedIn()` // first, and rendering the `dialog` view. export const authorization: RequestHandler[] = [ login.ensureLoggedIn(), server.authorization( (clientId: string, redirectUri: string, done: (err: Error | null, client?: any, redirectURI?: string) => void) => { // Validate the client const client: Client | undefined = ClientCollection.find( (value: Client) => clientId === value.id ); if (!client) { return done(new Error("toast.client.invalid")); } if (client.redirectUri !== redirectUri) { return done(new Error("toast.client.incorrect_url")); } // tslint:disable-next-line:no-null-keyword return done(null, client, redirectUri); }, (client: Client, user: UserDocument, scope: string[], type: string, areq: any, done: (err: Error | null, allow: boolean, info: any, locals: any) => void): void => { AccessTokenCollection .findOne({clientId: client.id, userId: user.id}) .exec() .then((accessToken: AccessToken | null): void => { if (accessToken) { // Auto-approve // tslint:disable-next-line: no-null-keyword done(null, true, user, undefined); } else { // tslint:disable-next-line:no-null-keyword done(null, false, user, undefined); } } ).catch((error: Error) => { done(error, false, user, undefined); }); } ), function (req: MiddlewareRequest & Request, res: Response) { if (!req.oauth2) { return res.status(500).end(); } res.redirect(302, `/consent?email=${(req.user as User).email}&client_name=${(req.oauth2.client as Client).name}&transactionID=${req.oauth2.transactionID}`); } ]; // user decision endpoint // // `decision` middleware processes a user's decision to allow or deny access // requested by a client application. Based on the grant type requested by the // client, the above grant middleware configured above will be invoked to send // a response. export const decision: RequestHandler[] = [ login.ensureLoggedIn(), (req: Request, res: Response, next: NextFunction) => { if (FLAG_ENABLE_OTP_FOR_VERIFICATION) { UserCollection .findById((req.user as User)._id) .exec() .then((user: UserDocument | null) => { verifyOtpInternal(res, next, user, req.body["OTP"], true); }); } else { next(); } }, server.decision() ]; // Token endpoint. // // `token` middleware handles client requests to exchange authorization grants // for access tokens. Based on the grant type being exchanged, the above // exchange middleware will be invoked to handle the request. Clients must // authenticate when making requests to this endpoint. export const token: RequestHandler[] = [ passport.authenticate(["basic", "oauth2-client-password"], { session: false }), server.token(), server.errorHandler(), ]; /** * Create a new oauth2 user account. */ export const signUp: RequestHandler[] = [ (req: Request, res: Response, next: NextFunction) => { if (FLAG_ENABLE_INVITATION_CODE) { const code: string = req.body.invitationCode; if (invitationCode.indexOf(code) > 0) { UserCollection .findOne({invitationCode: code}) .exec() .then((user: UserDocument | null) => { if (user) { Promise.reject(res.status(409).json({ message: "toast.user.invitation_code.used" })); } else { return next(); } }) .catch((error: Response) => { return next(error); }); } else { return res.status(400).json({ message: "toast.user.invitation_code.invalid" }); } } else { return next(); } }, (req: Request, res: Response, next: NextFunction) => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } const user: UserDocument = new UserCollection({ email: req.body.email, password: req.body.password, gender: req.body.gender, name: req.body.name, address: req.body.address, avatarUrl: req.body.avatarUrl, preferences: req.body.preferences, invitationCode: req.body.invitationCode }); UserCollection .findOne({ email: _.toLower(req.body.email) }) .exec() .then((existingUser: UserDocument | null) => { if (existingUser) { return Promise.reject(res.status(409).json({ message: "toast.user.upload_exist_account" })); } return user.save(); }) .then((user: UserDocument) => { req.logIn(user, (err) => { if (err) { return next(err); } return res.redirect(302, "/auth/oauth2"); // Get access token }); }) .catch((error: Response) => { return next(error); }); } ]; /** * Sign in using email and password. */ export const logIn: RequestHandler = (req: Request, res: Response, next: NextFunction) => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } passport.authenticate("local", (err: Error, user: UserDocument, info: IVerifyOptions) => { if (err) { return res.status(401).json({ message: err.message }); } if (!user) { return res.status(401).json({ message: "toast.user.sign_in_failed" }); } req.logIn(user, (err) => { if (err) { return res.status(401).json({ message: "toast.user.sign_in_failed" }); } res.redirect(302, "/auth/oauth2"); // Get access token }); })(req, res, next); }; export const profile: RequestHandler = async (req: Request, res: Response, next: NextFunction) => { const notifications: Notification[] = await NotificationStorage.findByOwner((req.user as User)._id.toString(), true); const others: UserDocument[] = await UserCollection.find({}); (req.user as User).password = "######"; others.forEach((other: UserDocument) => { other.password = "######"; postFind(other); }); return res.json({ user: req.user as User, notifications: notifications, others: others } as AuthenticationResponse); }; export const updateProfile: RequestHandler = (req: Request, res: Response, next: NextFunction) => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } UserCollection .findById(req.body._id) .exec() .then((user: UserDocument | null) => { if (!user) { return Promise.reject(res.status(404).json({ message: "toast.user.account_not_found" })); } Object.assign(user, req.body); return user.save(); }) .then((user: UserDocument) => { const avatarFilename: string = getBlobNameFromUrl(user.avatarUrl); user.avatarUrl = `${user.avatarUrl}?${storage.generateSigningUrlParams(CONTAINER_AVATAR, avatarFilename)}`; return res.json(user); }) .catch((error: Response) => { return next(error); }); }; export const updatePreferences: RequestHandler = (req: Request, res: Response, next: NextFunction) => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } UserCollection .findById(req.body.id) .exec() .then((user: UserDocument | null) => { if (!user) { return Promise.reject(res.status(404).json({ message: "toast.user.account_not_found" })); } user.preferences = req.body.preferences; return user.save(); }) .then((user: UserDocument) => { return res.json(user.preferences); }) .catch((error: Response) => { return next(error); }); }; export const updatePassword: RequestHandler = (req: Request, res: Response, next: NextFunction): any => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } (req.user as UserDocument).comparePassword( req.body.oldPassword, (err: Error, isMatch: boolean) => { if (err || !isMatch) { return res.status(401).json({ message: "toast.user.old_password_error" }); } }); UserCollection .findById((req.user as User)._id) .exec() .then((user: UserDocument | null) => { if (!user) { return Promise.reject(res.status(500).end()); } user.password = req.body.password; return user.save(); }) .then(() => { return res.sendStatus(200); }) .catch((error: Response) => { return next(error); }); }; export const resetPassword: RequestHandler = (req: Request, res: Response, next: NextFunction): any => { if (!FLAG_ENABLE_OTP_FOR_VERIFICATION) { return res.sendStatus(404); } const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } UserCollection .findOne({email: req.body.email, OTP: req.body.OTP}) .exec() .then((user: UserDocument | null) => { if (!user) { return Promise.reject(res.sendStatus(404)); } user.password = req.body.password; return user.save(); }) .then(() => { return res.sendStatus(200); }) .catch((error: Response) => { return next(error); }); }; export const sendOtp: RequestHandler = (req: Request, res: Response, next: NextFunction): any => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } UserCollection .findOne({email: req.query.email as string}) .exec() .then((user: UserDocument | null) => { if (!user) { return Promise.reject(res.status(404).json({ message: "toast.user.account_not_found"})); } const locale: string = req.acceptsLanguages() ? req.acceptsLanguages()[0] : "en-us"; return refreshOtpThenSendToUser(user.email, locale); }) .then((value: any) => { return res.sendStatus(200); }).catch((reason: any) => { return res.status(500).json({ message: "toast.user.otp_send_failed" }); }); }; export const verifyAccount: RequestHandler = (req: Request, res: Response, next: NextFunction): any => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } UserCollection .findOne({email: req.query.email as string}) .exec() .then((user: UserDocument | null) => { if (!user) { return res.status(404).json({ message: "toast.user.email"}); } return res.sendStatus(200); }); }; export const verifyOtp: RequestHandler[] = [ (req: Request, res: Response, next: NextFunction): any => { const invalid: Response | false = validationErrorResponse(res, validationResult(req)); if (invalid) { return invalid; } UserCollection .findOne({email: req.query.email as string}) .exec() .then((user: UserDocument | null) => { if (!user) { return res.status(404).json({ message: "toast.user.email"}); } return verifyOtpInternal(res, next, user, req.query.OTP, false); }); }, (req: Request, res: Response, next: NextFunction): any => { res.sendStatus(200); } ]; const verifyOtpInternal: any = (res: Response, next: NextFunction, user: UserDocument, OTP: string, reset: boolean): any => { if (user && user.OTP && user.OTP.length == OTP_LENGTH && user.OTP.toLowerCase() === OTP.toLowerCase()) { if (!user.otpExpireTime || user.otpExpireTime.getTime() <= Date.now()) { return res.status(401).json({ message: "toast.user.expired_OTP" }); } else { if (reset) { user.OTP = ""; user.save(); } return next(); } } else { return res.status(401).json({ message: "toast.user.error_OTP" }); } };
the_stack
declare module AutoMapperJs { /** * AutoMapper implementation, for both creating maps and performing maps. Comparable usage and functionality to the original * .NET AutoMapper library is the pursuit of this implementation. */ class AutoMapper { /** * Initializes the mapper with the supplied configuration. * @param {(config: IConfiguration) => void} Configuration function to call. */ initialize(configFunction: (config: IConfiguration) => void): void; /** * Create a createMap curry function which expects only a destination key. * @param {string} sourceKey The map source key. * @returns {(destinationKey: string) => ICreateMapFluentFunctions} */ createMap(sourceKey: string | (new() => any)): (destinationKey: string | (new() => any)) => ICreateMapFluentFunctions; /** * Create a mapping profile. * @param {string} sourceKey The map source key. * @param {string} destinationKey The map destination key. * @returns {Core.ICreateMapFluentFunctions} */ createMap(sourceKey: string | (new() => any), destinationKey: string | (new() => any)): ICreateMapFluentFunctions; /** * Create a map curry function which expects a destination key and a source object. * @param sourceKey Source key, for instance the source type name. * @returns {(destinationKey: string, sourceObject: any) => any} */ map(sourceKey: string | (new() => any)): (destinationKey: string | (new() => any), sourceObject: any) => any; /** * Create a map curry function which expects only a source object. * @param sourceKey Source key, for instance the source type name. * @param destinationKey Destination key, for instance the destination type name. * @returns {(sourceObject: any) => any} */ map(sourceKey: string | (new() => any), destinationKey: string | (new() => any)): (sourceObject: any) => any; /** * Execute a mapping from the source object to a new destination object with explicit mapping configuration and supplied mapping options (using createMap). * @param sourceKey Source key, for instance the source type name. * @param destinationKey Destination key, for instance the destination type name. * @param sourceObject The source object to map. * @returns {any} Destination object. */ map(sourceKey: string | (new() => any), destinationKey: string | (new() => any), sourceObject: any): any; /** * Create a mapAsync curry function which expects a destination key, a source object and a callback function. * @param sourceKey Source key, for instance the source type name. * @returns {(destinationKey: string, sourceObject: any, callback: IMapCallback) => void} */ mapAsync(sourceKey: string | (new() => any)): (destinationKey: string | (new() => any), sourceObject: any, callback: IMapCallback) => void; /** * Create a map curry function which expects only a source object and a callback function. * @param sourceKey Source key, for instance the source type name. * @param destinationKey Destination key, for instance the destination type name. * @param sourceObject The source object to map. * @returns {(callback: IMapCallback) => void} */ mapAsync(sourceKey: string | (new() => any), destinationKey: string | (new() => any), sourceObject: any): (callback: IMapCallback) => void; /** * Create a map curry function which expects only a source object and a callback function. * @param sourceKey Source key, for instance the source type name. * @param destinationKey Destination key, for instance the destination type name. * @returns {(sourceObject: any, callback: IMapCallback) => void} */ mapAsync(sourceKey: string | (new() => any), destinationKey: string | (new() => any)): (sourceObject: any, callback: IMapCallback) => void; /** * Execute an asynchronous mapping from the source object to a new destination object with explicit mapping configuration and supplied mapping options (using createMap). * @param sourceKey Source key, for instance the source type name. * @param destinationKey Destination key, for instance the destination type name. * @param sourceObject The source object to map. * @param {IMapCallback} callback The callback to call when asynchronous mapping is complete. */ mapAsync(sourceKey: string | (new() => any), destinationKey: string | (new() => any), sourceObject: any, callback: IMapCallback): void; /** * Validates mapping configuration by dry-running. Since JS does not * fully support typing, it only checks if properties match on both * sides. The function needs IMapping.sourceTypeClass and * IMapping.destinationTypeClass to function. * @param {boolean} strictMode Whether or not to fail when properties * sourceTypeClass or destinationTypeClass * are unavailable. */ assertConfigurationIsValid(strictMode?: boolean): void; } class AsyncAutoMapper { /* For Test Purposes Only */ } /** * Converts source type to destination type instead of normal member mapping */ class TypeConverter implements ITypeConverter { /** * Performs conversion from source to destination type. * @param {IResolutionContext} resolutionContext Resolution context. * @returns {any} Destination object. */ convert(resolutionContext: IResolutionContext): any; } export class Profile implements IProfile { /** Profile name */ public profileName: string; /** Naming convention for source members */ public sourceMemberNamingConvention: INamingConvention; /** Naming convention for destination members */ public destinationMemberNamingConvention: INamingConvention; /** * Create a createMap curry function which expects only a destination key. * @param {string} sourceKey The map source key. * @returns {(destinationKey: string) => ICreateMapFluentFunctions} */ protected createMap(sourceKey: string): (destinationKey: string) => ICreateMapFluentFunctions; /** * Create a mapping profile. * @param {string} sourceKey The map source key. * @param {string} destinationKey The map destination key. * @returns {Core.ICreateMapFluentFunctions} */ protected createMap(sourceKey: string, destinationKey: string): ICreateMapFluentFunctions; /** * Implement this method in a derived class and call the CreateMap method to associate that map with this profile. * Avoid calling the AutoMapper class / automapper instance from this method. */ public configure(): void; } /** * Defines the PascalCase naming convention strategy. */ class PascalCaseNamingConvention implements INamingConvention { /** Regular expression on how to tokenize a member. */ splittingExpression: RegExp; /** Character to separate on. */ separatorCharacter: string; /** * Transformation function called when this convention is the destination naming convention. * @param {string[]} sourcePropertyNameParts Array containing tokenized source property name parts. * @returns {string} Destination property name */ transformPropertyName(sourcePropertyNameParts: string[]): string; } /** * Defines the camelCase naming convention strategy. */ class CamelCaseNamingConvention implements INamingConvention { /** Regular expression on how to tokenize a member. */ splittingExpression: RegExp; /** Character to separate on. */ separatorCharacter: string; /** * Transformation function called when this convention is the destination naming convention. * @param {string[]} sourcePropertyNameParts Array containing tokenized source property name parts. * @returns {string} Destination property name */ transformPropertyName(sourcePropertyNameParts: string[]): string; } // [v1.8] interface IProperty { // TODO Rename! name: string; sourcePropertyName: string; destinationPropertyName: string; level: number; } interface ISourceProperty extends IProperty { children: ISourceProperty[]; destination: IDestinationProperty; } interface IDestinationTransformation { transformationType: number; // Ideal: AutoMapperJs.DestinationTransformationType (but not as easy as it appears to be); constant?: any; memberConfigurationOptionsFunc?: (opts: IMemberConfigurationOptions) => void; asyncMemberConfigurationOptionsFunc?: (opts: IMemberConfigurationOptions, cb: IMemberCallback) => void; sourceMemberConfigurationOptionsFunc?: (opts: ISourceMemberConfigurationOptions) => void; asyncSourceMemberConfigurationOptionsFunc?: (opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => void; } interface IDestinationProperty extends IProperty { child: IDestinationProperty; transformations: IDestinationTransformation[]; conditionFunction: (sourceObject: any) => boolean; ignore: boolean; sourceMapping: boolean; // TODO is this still necessary? } interface ICreateMapForMemberParameters { mapping: IMapping; propertyName: string; transformation: any; sourceMapping: boolean; fluentFunctions: ICreateMapFluentFunctions; } // [/v1.8] interface IPropertyOld { name: string; metadata: IPropertyMetadata; level: number; sourceMapping: boolean; ignore: boolean; async: boolean; children?: IPropertyOld[]; destinations?: IPropertyOld[]; conversionValuesAndFunctions: any[]; conditionFunction?: (sourceObject: any) => boolean; } interface IPropertyMetadata { mapping: IMapping; root: IPropertyOld; parent: IPropertyOld; destinations: {[name: string]: IPropertyDestinationMetadata}; destinationCount: number; } interface IPropertyDestinationMetadata { source: IPropertyOld; destination: IPropertyOld; } interface IMemberMappingMetaData { destination: string; source: string; transformation: IDestinationTransformation; sourceMapping: boolean; ignore: boolean; async: boolean; condition: (sourceObject: any) => boolean; } /** * Member mapping properties. */ interface IForMemberMapping { /** The source member property name. */ sourceProperty: string; /** The destination member property name parts for nested property support (e.g. 'type.name'). */ destinationProperty: string; /** Source or destination mapping. */ sourceMapping: boolean; /** All mapping values and/or functions resulting from stacked for(Source)Member calls. */ mappingValuesAndFunctions: Array<any>; /** Whether or not this destination property must be ignored. */ ignore: boolean; /** Whether or not this member mapping has an asynchronous mapping function. */ async: boolean; /** * The object will only be mapped when the condition is met. * @param {any} sourceObject The source object to check. * @returns {boolean} */ conditionFunction: (sourceObject: any) => boolean; } /** * Interface for returning an object with available 'sub' functions to enable method chaining (e.g. automapper.createMap().forMember().forMember() ...) */ interface ICreateMapFluentFunctions { /** * Customize configuration for an individual destination member. * @param sourceProperty The destination member property name. * @param valueOrFunction The value or function to use for this individual member. * @returns {IAutoMapperCreateMapChainingFunctions} */ forMember: (sourceProperty: string, valueOrFunction: any | ((opts: IMemberConfigurationOptions) => any) | ((opts: IMemberConfigurationOptions, cb: IMemberCallback) => void)) => ICreateMapFluentFunctions; /** * Customize configuration for an individual source member. * @param sourceProperty The source member property name. * @param sourceMemberConfigFunction The function to use for this individual member. * @returns {IAutoMapperCreateMapChainingFunctions} */ forSourceMember: (sourceProperty: string, sourceMemberConfigFunction: ((opts: ISourceMemberConfigurationOptions) => any) | ((opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => void) ) => ICreateMapFluentFunctions; /** * Customize configuration for all destination members. * @param func The function to use for this individual member. * @returns {IAutoMapperCreateMapChainingFunctions} */ forAllMembers: (func: (destinationObject: any, destinationPropertyName: string, value: any) => void) => ICreateMapFluentFunctions; /** * Ignore all members not specified explicitly. */ ignoreAllNonExisting: () => ICreateMapFluentFunctions; /** * Skip normal member mapping and convert using a custom type converter (instantiated during mapping). * @param typeConverterClassOrFunction The converter class or function to use when converting. */ convertUsing: (typeConverterClassOrFunction: ((resolutionContext: IResolutionContext) => any) | ((resolutionContext: IResolutionContext, callback: IMapCallback) => void) | ITypeConverter | (new() => ITypeConverter) ) => void; /** * Specify to which class type AutoMapper should convert. When specified, AutoMapper will create an instance of the given type, instead of returning a new object literal. * @param typeClass The destination type class. * @returns {IAutoMapperCreateMapChainingFunctions} */ convertToType: (typeClass: new () => any) => ICreateMapFluentFunctions; /** * Specify which profile should be used when mapping. * @param {string} profileName The profile name. * @returns {IAutoMapperCreateMapChainingFunctions} */ withProfile: (profileName: string) => void; } /** * The mapping configuration for the current mapping keys/types. */ interface IMapping { /** The mapping source key. */ sourceKey: string; /** The mapping destination key. */ destinationKey: string; /** The mappings for forAllMembers functions. */ forAllMemberMappings: Array<(destinationObject: any, destinationPropertyName: string, value: any) => void>; // propertiesOld: IPropertyOld[]; properties: ISourceProperty[]; /** * Skip normal member mapping and convert using a type converter. * @param resolutionContext Context information regarding resolution of a destination value * @returns {any} Destination object. */ typeConverterFunction: ((resolutionContext: IResolutionContext) => any) | ((resolutionContext: IResolutionContext, callback: IMapCallback) => void); /** The source type class to convert from. */ sourceTypeClass: any; /** The destination type class to convert to. */ destinationTypeClass: any; /** The profile used when mapping. */ profile?: IProfile; /** Whether or not to ignore all properties not specified using createMap. */ ignoreAllNonExisting?: boolean; /** Whether or not an mapping has to be asynchronous. */ async: boolean; /* * PERFORMANCE ENHANCEMENTS */ /** * Item mapping function to use. */ mapItemFunction: IMapItemFunction | IAsyncMapItemFunction; } // export interface IMappingMapOptimized extends IMapping { // final: boolean; // forMemberMappingsArray: Array<IForMemberMapping>; // } /** * Context information regarding resolution of a destination value */ export interface IResolutionContext { /** Source value */ sourceValue: any; /** Destination value */ destinationValue: any; /** Source property name */ sourcePropertyName?: string; /** Destination property name */ destinationPropertyName?: string; /** Index of current collection mapping */ arrayIndex?: number; } interface IMappingConfigurationOptions { /** The source object to map. */ sourceObject: any; /** The source property to map. */ sourcePropertyName: string; /** * The intermediate destination property value, used for stacking multiple for(Source)Member calls * while elaborating the intermediate result. */ intermediatePropertyValue: any; } /** * Configuration options for forMember mapping function. */ interface IMemberConfigurationOptions extends ISourceMemberConfigurationOptions { /** * Map from a custom source property name. * @param sourcePropertyName The source property to map. */ mapFrom: (sourcePropertyName: string) => void; /** * If specified, the property will only be mapped when the condition is fulfilled. */ condition: (predicate: ((sourceObject: any) => boolean)) => void; } /** * Configuration options for forSourceMember mapping function. */ interface ISourceMemberConfigurationOptions extends IMappingConfigurationOptions { /** * When this configuration function is used, the property is ignored * when mapping. */ ignore: () => void; } /** * Member callback interface */ interface IMemberCallback { /** * Callback function to call when the async operation is executed. * @param {any} callbackValue Callback value to be used as output for the for(Source)Member call. */ (callbackValue: any): void; } /** * Member callback interface */ interface IAsyncTransformCallback { /** * Callback function to call when the async operation is executed. * @param {any} callbackValue Callback value to be used as output for the for(Source)Member call. * @param {boolean} success Whether or not this call was successful. */ (callbackValue: any, success: boolean): void; } /** * Member callback interface */ interface IMapCallback { /** * Callback function to call when the async operation is executed. * @param {any} result Callback value to be used as output for the mapAsync call. */ (result: any): void; } /** * Converts source type to destination type instead of normal member mapping */ export interface ITypeConverter { /** * Performs conversion from source to destination type. * @param {IResolutionContext} resolutionContext Resolution context. * @returns {any} Destination object. */ convert: (resolutionContext: IResolutionContext) => any; } /** * Defines a naming convention strategy. */ export interface INamingConvention { /** Regular expression on how to tokenize a member. */ splittingExpression: RegExp; /** Character to separate on. */ separatorCharacter: string; /** * Transformation function called when this convention is the destination naming convention. * @param {string[]} sourcePropertyNameParts Array containing tokenized source property name parts. * @returns {string} Destination property name */ transformPropertyName: (sourcePropertyNameParts: string[]) => string; } /** * Configuration for profile-specific maps. */ export interface IConfiguration { /** * Add an existing profile * @param profile {IProfile} Profile to add. */ addProfile(profile: IProfile): void; /** * Create a createMap curry function which expects only a destination key. * @param {string} sourceKey The map source key. * @returns {(destinationKey: string) => IAutoMapperCreateMapChainingFunctions} */ createMap?(sourceKey: string): (destinationKey: string) => ICreateMapFluentFunctions; /** * Create a mapping profile. * @param {string} sourceKey The map source key. * @param {string} destinationKey The map destination key. * @returns {Core.IAutoMapperCreateMapChainingFunctions} */ createMap?(sourceKey: string, destinationKey: string): ICreateMapFluentFunctions; } /** * Provides a named configuration for maps. Naming conventions become scoped per profile. */ export interface IProfile { /** Profile name */ profileName: string; /** Naming convention for source members */ sourceMemberNamingConvention: INamingConvention; /** Naming convention for destination members */ destinationMemberNamingConvention: INamingConvention; /** * Implement this method in a derived class and call the CreateMap method to associate that map with this profile. * Avoid calling the AutoMapper class / automapper instance from this method. */ configure: () => void; } export interface IMapItemFunction { (mapping: IMapping, sourceObject: any, destinationObject: any): any; } export interface IAsyncMapItemFunction { (mapping: IMapping, sourceObject: any, destinationObject: any, callback: IMapCallback): void; } interface ICreateMapParameters { mapping: IMapping; destinationProperty: string; conversionValueOrFunction: any; sourceMapping: boolean; fluentFunctions: ICreateMapFluentFunctions; } interface IGetOrCreatePropertyParameters { propertyNameParts: string[]; mapping: IMapping; parent?: IPropertyOld; propertyArray: IPropertyOld[]; destination?: string; sourceMapping: boolean; } interface ICreatePropertyParameters { name: string; mapping: IMapping; parent: IPropertyOld; propertyArray: IPropertyOld[]; sourceMapping: boolean; } } declare var automapper: AutoMapperJs.AutoMapper;
the_stack
import { QueryMetrics, Resource, StoredProcedureDefinition, TriggerDefinition, UserDefinedFunctionDefinition, } from "@azure/cosmos"; import Explorer from "../Explorer/Explorer"; import { ConsoleData } from "../Explorer/Menus/NotificationConsole/ConsoleData"; import { CassandraTableKey, CassandraTableKeys } from "../Explorer/Tables/TableDataClient"; import ConflictId from "../Explorer/Tree/ConflictId"; import DocumentId from "../Explorer/Tree/DocumentId"; import StoredProcedure from "../Explorer/Tree/StoredProcedure"; import Trigger from "../Explorer/Tree/Trigger"; import UserDefinedFunction from "../Explorer/Tree/UserDefinedFunction"; import { SelfServeType } from "../SelfServe/SelfServeUtils"; import { CollectionCreationDefaults } from "../UserContext"; import { SqlTriggerResource } from "../Utils/arm/generatedClients/cosmos/types"; import * as DataModels from "./DataModels"; import { SubscriptionType } from "./SubscriptionType"; export interface TokenProvider { getAuthHeader(): Promise<Headers>; } export interface UploadDetailsRecord { fileName: string; numSucceeded: number; numFailed: number; numThrottled: number; errors: string[]; } export interface QueryResultsMetadata { hasMoreResults: boolean; firstItemIndex: number; lastItemIndex: number; itemCount: number; } export interface QueryResults extends QueryResultsMetadata { documents: any[]; activityId: string; requestCharge: number; roundTrips?: number; headers?: any; queryMetrics?: QueryMetrics; } export interface Button { visible: ko.Computed<boolean>; enabled: ko.Computed<boolean>; isSelected?: ko.Computed<boolean>; } export interface NotificationConsole { filteredConsoleData: ko.ObservableArray<ConsoleData>; isConsoleExpanded: ko.Observable<boolean>; expandConsole(source: any, evt: MouseEvent): void; collapseConsole(source: any, evt: MouseEvent): void; } export interface WaitsForTemplate { isTemplateReady: ko.Observable<boolean>; } export interface TreeNode { nodeKind: string; rid: string; id: ko.Observable<string>; database?: Database; collection?: Collection; onNewQueryClick?(source: any, event: MouseEvent): void; onNewStoredProcedureClick?(source: Collection, event: MouseEvent): void; onNewUserDefinedFunctionClick?(source: Collection, event: MouseEvent): void; onNewTriggerClick?(source: Collection, event: MouseEvent): void; } export interface Database extends TreeNode { container: Explorer; self: string; id: ko.Observable<string>; collections: ko.ObservableArray<Collection>; offer: ko.Observable<DataModels.Offer>; isDatabaseExpanded: ko.Observable<boolean>; isDatabaseShared: ko.Computed<boolean>; selectedSubnodeKind: ko.Observable<CollectionTabKind>; expandDatabase(): Promise<void>; collapseDatabase(): void; loadCollections(): Promise<void>; findCollectionWithId(collectionId: string): Collection; openAddCollection(database: Database, event: MouseEvent): void; onSettingsClick: () => void; loadOffer(): Promise<void>; getPendingThroughputSplitNotification(): Promise<DataModels.Notification>; } export interface CollectionBase extends TreeNode { container: Explorer; databaseId: string; self: string; rawDataModel: DataModels.Collection; partitionKey: DataModels.PartitionKey; partitionKeyProperty: string; partitionKeyPropertyHeader: string; id: ko.Observable<string>; selectedSubnodeKind: ko.Observable<CollectionTabKind>; children: ko.ObservableArray<TreeNode>; isCollectionExpanded: ko.Observable<boolean>; onDocumentDBDocumentsClick(): void; onNewQueryClick(source: any, event?: MouseEvent, queryText?: string): void; expandCollection(): void; collapseCollection(): void; getDatabase(): Database; } export interface Collection extends CollectionBase { defaultTtl: ko.Observable<number>; analyticalStorageTtl: ko.Observable<number>; schema?: DataModels.ISchema; requestSchema?: () => void; indexingPolicy: ko.Observable<DataModels.IndexingPolicy>; uniqueKeyPolicy: DataModels.UniqueKeyPolicy; usageSizeInKB: ko.Observable<number>; offer: ko.Observable<DataModels.Offer>; conflictResolutionPolicy: ko.Observable<DataModels.ConflictResolutionPolicy>; changeFeedPolicy: ko.Observable<DataModels.ChangeFeedPolicy>; geospatialConfig: ko.Observable<DataModels.GeospatialConfig>; documentIds: ko.ObservableArray<DocumentId>; cassandraKeys: CassandraTableKeys; cassandraSchema: CassandraTableKey[]; onConflictsClick(): void; onTableEntitiesClick(): void; onGraphDocumentsClick(): void; onMongoDBDocumentsClick(): void; onSchemaAnalyzerClick(): void; openTab(): void; onSettingsClick: () => Promise<void>; onNewGraphClick(): void; onNewMongoQueryClick(source: any, event?: MouseEvent, queryText?: string): void; onNewMongoShellClick(): void; onNewStoredProcedureClick(source: Collection, event?: MouseEvent): void; onNewUserDefinedFunctionClick(source: Collection, event?: MouseEvent): void; onNewTriggerClick(source: Collection, event?: MouseEvent): void; storedProcedures: ko.Computed<StoredProcedure[]>; userDefinedFunctions: ko.Computed<UserDefinedFunction[]>; triggers: ko.Computed<Trigger[]>; isStoredProceduresExpanded: ko.Observable<boolean>; isTriggersExpanded: ko.Observable<boolean>; isUserDefinedFunctionsExpanded: ko.Observable<boolean>; expandStoredProcedures(): void; expandUserDefinedFunctions(): void; expandTriggers(): void; collapseStoredProcedures(): void; collapseUserDefinedFunctions(): void; collapseTriggers(): void; loadUserDefinedFunctions(): Promise<any>; loadStoredProcedures(): Promise<any>; loadTriggers(): Promise<any>; loadOffer(): Promise<void>; createStoredProcedureNode(data: StoredProcedureDefinition & Resource): StoredProcedure; createUserDefinedFunctionNode(data: UserDefinedFunctionDefinition & Resource): UserDefinedFunction; createTriggerNode(data: TriggerDefinition | SqlTriggerResource): Trigger; findStoredProcedureWithId(sprocRid: string): StoredProcedure; findTriggerWithId(triggerRid: string): Trigger; findUserDefinedFunctionWithId(udfRid: string): UserDefinedFunction; onDragOver(source: Collection, event: { originalEvent: DragEvent }): void; onDrop(source: Collection, event: { originalEvent: DragEvent }): void; uploadFiles(fileList: FileList): Promise<{ data: UploadDetailsRecord[] }>; getLabel(): string; getPendingThroughputSplitNotification(): Promise<DataModels.Notification>; } /** * Options used to initialize pane */ export interface PaneOptions { id: string; visible: ko.Observable<boolean>; container?: Explorer; } /** * Graph configuration */ export enum NeighborType { SOURCES_ONLY, TARGETS_ONLY, BOTH, } export interface IGraphConfigUiData { showNeighborType: NeighborType; nodeProperties: string[]; nodePropertiesWithNone: string[]; nodeCaptionChoice: string; nodeColorKeyChoice: string; nodeIconChoice: string; nodeIconSet: string; } /** * User input for creating new vertex */ export interface NewVertexData { label: string; properties: InputProperty[]; } export type GremlinPropertyValueType = string | boolean | number | null | undefined; export type InputPropertyValueTypeString = "string" | "number" | "boolean" | "null"; export interface InputPropertyValue { value: GremlinPropertyValueType; type: InputPropertyValueTypeString; } /** * Property input by user */ export interface InputProperty { key: string; values: InputPropertyValue[]; } export interface Editable<T> extends ko.Observable<T> { setBaseline(baseline: T): void; editableIsDirty: ko.Computed<boolean>; editableIsValid: ko.Observable<boolean>; getEditableCurrentValue?: ko.Computed<T>; getEditableOriginalValue?: ko.Computed<T>; edits?: ko.ObservableArray<T>; validations?: ko.ObservableArray<(value: T) => boolean>; } export interface QueryError { message: string; start: string; end: string; code: string; severity: string; } export interface DocumentRequestContainer { self: string; rid?: string; resourceName?: string; } export interface DocumentClientOption { endpoint?: string; masterKey?: string; requestTimeoutMs?: number; } // Tab options export interface TabOptions { tabKind: CollectionTabKind; title: string; tabPath: string; isTabsContentExpanded?: ko.Observable<boolean>; onLoadStartKey?: number; // TODO Remove the flag and use a context to handle this // TODO: 145357 Remove dependency on collection/database and add abstraction collection?: CollectionBase; database?: Database; rid?: string; node?: TreeNode; theme?: string; index?: number; } export interface DocumentsTabOptions extends TabOptions { partitionKey: DataModels.PartitionKey; documentIds: ko.ObservableArray<DocumentId>; container?: Explorer; isPreferredApiMongoDB?: boolean; resourceTokenPartitionKey?: string; } export interface ConflictsTabOptions extends TabOptions { partitionKey: DataModels.PartitionKey; conflictIds: ko.ObservableArray<ConflictId>; container?: Explorer; } export interface QueryTabOptions extends TabOptions { partitionKey?: DataModels.PartitionKey; queryText?: string; resourceTokenPartitionKey?: string; } export interface ScriptTabOption extends TabOptions { resource: any; isNew: boolean; partitionKey?: DataModels.PartitionKey; } export interface EditorPosition { line: number; column: number; } export enum DocumentExplorerState { noDocumentSelected, newDocumentValid, newDocumentInvalid, exisitingDocumentNoEdits, exisitingDocumentDirtyValid, exisitingDocumentDirtyInvalid, } export enum IndexingPolicyEditorState { noCollectionSelected, noEdits, dirtyValid, dirtyInvalid, } export enum ScriptEditorState { newInvalid, newValid, exisitingNoEdits, exisitingDirtyValid, exisitingDirtyInvalid, } export enum CollectionTabKind { Documents = 0, Settings = 1, StoredProcedures = 2, UserDefinedFunctions = 3, Triggers = 4, Query = 5, Graph = 6, QueryTables = 9, MongoShell = 10, DatabaseSettings = 11, Conflicts = 12, Notebook = 13 /* Deprecated */, Terminal = 14, NotebookV2 = 15, SparkMasterTab = 16 /* Deprecated */, Gallery = 17, NotebookViewer = 18, Schema = 19, CollectionSettingsV2 = 20, DatabaseSettingsV2 = 21, SchemaAnalyzer = 22, } export enum TerminalKind { Default = 0, Mongo = 1, Cassandra = 2, } export interface DataExplorerInputsFrame { databaseAccount: any; subscriptionId?: string; resourceGroup?: string; masterKey?: string; hasWriteAccess?: boolean; authorizationToken?: string; csmEndpoint?: string; dnsSuffix?: string; serverId?: string; extensionEndpoint?: string; subscriptionType?: SubscriptionType; quotaId?: string; addCollectionDefaultFlight?: string; isTryCosmosDBSubscription?: boolean; loadDatabaseAccountTimestamp?: number; sharedThroughputMinimum?: number; sharedThroughputMaximum?: number; sharedThroughputDefault?: number; dataExplorerVersion?: string; defaultCollectionThroughput?: CollectionCreationDefaults; flights?: readonly string[]; features?: { [key: string]: string; }; } export interface SelfServeFrameInputs { selfServeType: SelfServeType; databaseAccount: any; subscriptionId: string; resourceGroup: string; authorizationToken: string; csmEndpoint: string; flights?: readonly string[]; } export class MonacoEditorSettings { public readonly language: string; public readonly readOnly: boolean; constructor(supportedLanguage: string, isReadOnly: boolean) { this.language = supportedLanguage; this.readOnly = isReadOnly; } } export interface AuthorizationTokenHeaderMetadata { header: string; token: string; } export interface DropdownOption<T> { text: string; value: T; disable?: boolean; }
the_stack
* @fileoverview Implements a class that computes complexities for enriched math * * @author dpvc@mathjax.org (Davide Cervone) */ import {MmlNode, AbstractMmlTokenNode} from '../../core/MmlTree/MmlNode.js'; import {MmlMroot} from '../../core/MmlTree/MmlNodes/mroot.js'; import {MmlMaction} from '../../core/MmlTree/MmlNodes/maction.js'; import {MmlMsubsup, MmlMsub, MmlMsup} from '../../core/MmlTree/MmlNodes/msubsup.js'; import {MmlMunderover, MmlMunder, MmlMover} from '../../core/MmlTree/MmlNodes/munderover.js'; import {MmlVisitor} from '../../core/MmlTree/MmlVisitor.js'; import {MmlFactory} from '../../core/MmlTree/MmlFactory.js'; import {Collapse} from './collapse.js'; import {OptionList, userOptions, defaultOptions} from '../../util/Options.js'; /*==========================================================================*/ /** * A visitor pattern that computes complexities within the MathML tree */ export class ComplexityVisitor extends MmlVisitor { /** * The options for handling collapsing */ public static OPTIONS: OptionList = { identifyCollapsible: true, // mark elements that should be collapsed makeCollapsible: true, // insert maction to allow collapsing Collapse: Collapse // the Collapse class to use }; /** * Values used to compute complexities */ public complexity: {[name: string]: number} = { text: .5, // each character of a token element adds this to complexity token: .5, // each token element gets this additional complexity child: 1, // child nodes add this to their parent node's complexity script: .8, // script elements reduce their complexity by this factor sqrt: 2, // sqrt adds this extra complexity subsup: 2, // sub-sup adds this extra complexity underover: 2, // under-over adds this extra complexity fraction: 2, // fractions add this extra complexity enclose: 2, // menclose adds this extra complexity action: 2, // maction adds this extra complexity phantom: 0, // mphantom makes complexity 0? xml: 2, // Can't really measure complexity of annotation-xml, so punt glyph: 2 // Can't really measure complexity of mglyph, to punt }; /** * The object used to handle collapsable content */ public collapse: Collapse; /** * The MmlFactory for this visitor */ public factory: MmlFactory; /** * The options for this visitor */ public options: OptionList; /** * @override */ constructor(factory: MmlFactory, options: OptionList) { super(factory); let CLASS = this.constructor as typeof ComplexityVisitor; this.options = userOptions(defaultOptions({}, CLASS.OPTIONS), options); this.collapse = new this.options.Collapse(this); this.factory = factory; } /*==========================================================================*/ /** * @override */ public visitTree(node: MmlNode) { super.visitTree(node, true); if (this.options.makeCollapsible) { this.collapse.makeCollapse(node); } } /** * @override */ public visitNode(node: MmlNode, save: boolean) { if (node.attributes.get('data-semantic-complexity')) return; return super.visitNode(node, save); } /** * For token nodes, use the content length, otherwise, add up the child complexities * * @override */ public visitDefault(node: MmlNode, save: boolean) { let complexity; if (node.isToken) { const text = (node as AbstractMmlTokenNode).getText(); complexity = this.complexity.text * text.length + this.complexity.token; } else { complexity = this.childrenComplexity(node); } return this.setComplexity(node, complexity, save); } /** * For a fraction, add the complexities of the children and scale by script factor, then * add the fraction amount * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMfracNode(node: MmlNode, save: boolean) { const complexity = this.childrenComplexity(node) * this.complexity.script + this.complexity.fraction; return this.setComplexity(node, complexity, save); } /** * For square roots, use the child complexity plus the sqrt complexity * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMsqrtNode(node: MmlNode, save: boolean) { const complexity = this.childrenComplexity(node) + this.complexity.sqrt; return this.setComplexity(node, complexity, save); } /** * For roots, do the sqrt root computation and remove a bit for the root * (since it is counted in the children sum but is smaller) * * @param {MmlMroot} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMrootNode(node: MmlMroot, save: boolean) { const complexity = this.childrenComplexity(node) + this.complexity.sqrt - (1 - this.complexity.script) * this.getComplexity(node.childNodes[1]); return this.setComplexity(node, complexity, save); } /** * Phantom complexity is 0 * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMphantomNode(node: MmlNode, save: boolean) { return this.setComplexity(node, this.complexity.phantom, save); } /** * For ms, add the complexity of the quotes to that of the content, and use the * length of that times the text factor as the complexity * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMsNode(node: MmlNode, save: boolean) { const text = node.attributes.get('lquote') + (node as AbstractMmlTokenNode).getText() + node.attributes.get('rquote'); const complexity = text.length * this.complexity.text; return this.setComplexity(node, complexity, save); } /** * For supscripts and superscripts use the maximum of the script complexities, * multiply by the script factor, and add the base complexity. Add the child * complexity for each child, and the subsup complexity. * * @param {MmlMsubsup} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMsubsupNode(node: MmlMsubsup, save: boolean) { super.visitDefault(node, true); const sub = node.childNodes[node.sub]; const sup = node.childNodes[node.sup]; const base = node.childNodes[node.base]; let complexity = Math.max( sub ? this.getComplexity(sub) : 0, sup ? this.getComplexity(sup) : 0 ) * this.complexity.script; complexity += this.complexity.child * ((sub ? 1 : 0) + (sup ? 1 : 0)); complexity += (base ? this.getComplexity(base) + this.complexity.child : 0); complexity += this.complexity.subsup; return this.setComplexity(node, complexity, save); } /** * @param {MmlMsub} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMsubNode(node: MmlMsub, save: boolean) { return this.visitMsubsupNode(node, save); } /** * @param {MmlMsup} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMsupNode(node: MmlMsup, save: boolean) { return this.visitMsubsupNode(node, save); } /** * For under/over, get the maximum of the complexities of the under and over * elements times the script factor, and that the maximum of that with the * base complexity. Add child complexity for all children, and add the * underover amount. * * @param {MmlMunderover} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMunderoverNode(node: MmlMunderover, save: boolean) { super.visitDefault(node, true); const under = node.childNodes[node.under]; const over = node.childNodes[node.over]; const base = node.childNodes[node.base]; let complexity = Math.max( under ? this.getComplexity(under) : 0, over ? this.getComplexity(over) : 0, ) * this.complexity.script; if (base) { complexity = Math.max(this.getComplexity(base), complexity); } complexity += this.complexity.child * ((under ? 1 : 0) + (over ? 1 : 0) + (base ? 1 : 0)); complexity += this.complexity.underover; return this.setComplexity(node, complexity, save); } /** * @param {MmlMunder} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMunderNode(node: MmlMunder, save: boolean) { return this.visitMunderoverNode(node, save); } /** * @param {MmlMover} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMoverNode(node: MmlMover, save: boolean) { return this.visitMunderoverNode(node, save); } /** * For enclose, use sum of child complexities plus some for the enclose * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMencloseNode(node: MmlNode, save: boolean) { const complexity = this.childrenComplexity(node) + this.complexity.enclose; return this.setComplexity(node, complexity, save); } /** * For actions, use the complexity of the selected child * * @param {MmlMaction} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMactionNode(node: MmlMaction, save: boolean) { this.childrenComplexity(node); const complexity = this.getComplexity(node.selected); return this.setComplexity(node, complexity, save); } /** * For semantics, get the complexity from the first child * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMsemanticsNode(node: MmlNode, save: boolean) { const child = node.childNodes[0] as MmlNode; let complexity = 0; if (child) { this.visitNode(child, true); complexity = this.getComplexity(child); } return this.setComplexity(node, complexity, save); } /** * Can't really measure annotations, so just use a specific value * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitAnnotationNode(node: MmlNode, save: boolean) { return this.setComplexity(node, this.complexity.xml, save); } /** * Can't really measure annotations, so just use a specific value * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitAnnotation_xmlNode(node: MmlNode, save: boolean) { return this.setComplexity(node, this.complexity.xml, save); } /** * Can't really measure mglyph complexity, so just use a specific value * * @param {MmlNode} node The node whose complixity is being computed * @param {boolean} save True if the complexity is to be saved or just returned */ protected visitMglyphNode(node: MmlNode, save: boolean) { return this.setComplexity(node, this.complexity.glyph, save); } /*==========================================================================*/ /** * @param {MmlNode} node The node whose complixity is needed * @return {number} The complexity fof the node (if collapsable, then the collapsed complexity) */ public getComplexity(node: MmlNode): number { const collapsed = node.getProperty('collapsedComplexity'); return (collapsed != null ? collapsed : node.attributes.get('data-semantic-complexity')) as number; } /** * @param {MmlNode} node The node whose complixity is being set * @param {complexity} number The complexity for the node * @param {boolean} save True if complexity is to be set or just reported */ protected setComplexity(node: MmlNode, complexity: number, save: boolean) { if (save) { if (this.options.identifyCollapsible) { complexity = this.collapse.check(node, complexity); } node.attributes.set('data-semantic-complexity', complexity); } return complexity; } /** * @param {MmlNode} node The node whose children complexities are to be added * @return {number} The sum of the complexities, plus child complexity for each one */ protected childrenComplexity(node: MmlNode): number { super.visitDefault(node, true); let complexity = 0; for (const child of node.childNodes) { complexity += this.getComplexity(child as MmlNode); } if (node.childNodes.length > 1) { complexity += node.childNodes.length * this.complexity.child; } return complexity; } }
the_stack
import { MetricsPanelCtrl } from 'grafana/app/plugins/sdk'; import _ from 'lodash'; import $ from 'jquery'; import kbn from 'grafana/app/core/utils/kbn'; import TimeSeries from 'grafana/app/core/time_series2'; import { D3Wrapper } from './d3wrapper'; import { Transformers } from './transformers'; import { PolystatModel } from './polystatmodel'; import { MetricOverridesManager } from './metric_overrides_manager'; import { CompositesManager } from './composites_manager'; import { Tooltip } from './tooltip'; import { GetDecimalsForValue, SortVariableValuesByField } from './utils'; import { ClickThroughTransformer } from './clickThroughTransformer'; import { PolystatConfigs } from 'types'; import { convertOldAngularValueMapping } from '@grafana/ui'; import { LegacyResponseData, DataFrame, getMappedValue, PanelEvents, stringToJsRegex } from '@grafana/data'; import { DataProcessor } from './core/data_processor'; import { getProcessedDataFrames } from './core/dataframe'; import { InsertTime } from './data/deframer'; class D3PolystatPanelCtrl extends MetricsPanelCtrl { processor: DataProcessor; static templateUrl = 'partials/template.html'; animationModes = [ { value: 'all', text: 'Show All' }, { value: 'triggered', text: 'Show Triggered' }, ]; displayModes = [ { value: 'all', text: 'Show All' }, { value: 'triggered', text: 'Show Triggered' }, ]; shapes = [ { value: 'hexagon_pointed_top', text: 'Hexagon Pointed Top' }, //{ value: 'hexagon_flat_top', text: 'Hexagon Flat Top' }, { value: 'circle', text: 'Circle' }, //{ value: "cross", text: "Cross" }, //{ value: 'diamond', text: 'Diamond' }, { value: 'square', text: 'Square' }, //{ value: "star", text: "Star" }, //{ value: "triangle", text: "Triangle" }, //{ value: "wye", text: "Wye" } ]; fontSizes = [ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, ]; unitFormats = kbn.getUnitFormats(); operatorOptions = [ { value: 'avg', text: 'Average' }, { value: 'count', text: 'Count' }, { value: 'current', text: 'Current' }, { value: 'delta', text: 'Delta' }, { value: 'diff', text: 'Difference' }, { value: 'first', text: 'First' }, { value: 'logmin', text: 'Log Min' }, { value: 'max', text: 'Max' }, { value: 'min', text: 'Min' }, { value: 'name', text: 'Name' }, { value: 'last_time', text: 'Time of Last Point' }, { value: 'time_step', text: 'Time Step' }, { value: 'total', text: 'Total' }, ]; sortDirections = [ { value: 'asc', text: 'Ascending' }, { value: 'desc', text: 'Descending' }, ]; sortFields = [ { value: 'name', text: 'Name' }, { value: 'thresholdLevel', text: 'Threshold Level' }, { value: 'value', text: 'Value' }, ]; // new method for sorting same as template vars sortOptions = [ { value: 0, text: 'Disabled' }, { value: 1, text: 'Alphabetical (asc)' }, { value: 2, text: 'Alphabetical (desc)' }, { value: 3, text: 'Numerical (asc)' }, { value: 4, text: 'Numerical (desc)' }, { value: 5, text: 'Alphabetical (case-insensitive, asc)' }, { value: 6, text: 'Alphabetical (case-insensitive, desc)' }, ]; polystatData: PolystatModel[]; initialized: boolean; panelContainer: any; d3Object: D3Wrapper; series: any[]; templateSrv: any; overridesCtrl: MetricOverridesManager; compositesManager: CompositesManager; tooltipContent: string[]; d3DivId: string; containerDivId: string; svgContainer: any; panelWidth: any; panelHeight: any; panelDefaults = { nullPointMode: 'connected', savedComposites: [], savedOverrides: [], // Array<MetricOverride>(), colors: ['#299c46', '#ED8128', '#d44a3a', '#4040a0'], valueMaps: [{ value: 'null', op: '=', text: 'N/A' }], mappingTypes: [ { name: 'value to text', value: 1 }, { name: 'range to text', value: 2 }, ], rangeMaps: [{ from: 'null', to: 'null', text: 'N/A' }], mappingType: 1, polystat: { animationSpeed: 2500, columns: '', columnAutoSize: true, displayLimit: 100, defaultClickThrough: '', defaultClickThroughNewTab: false, defaultClickThroughSanitize: false, ellipseEnabled: false, ellipseCharacters: 18, fontAutoScale: true, fontSize: 12, fontType: 'Roboto', fontAutoColor: true, globalUnitFormat: 'short', globalDecimals: 2, globalDisplayMode: 'all', globalOperatorName: 'avg', globalDisplayTextTriggeredEmpty: 'OK', gradientEnabled: true, hexagonSortByDirection: 'asc', hexagonSortByField: 'name', maxMetrics: 0, polygonBorderSize: 2, polygonBorderColor: '#000000', polygonGlobalFillColor: '#0a55a1', // 'rgb(10, 80, 161)' '#0a55a1' radius: '', radiusAutoSize: true, rows: '', rowAutoSize: true, shape: 'hexagon_pointed_top', tooltipDisplayMode: 'all', tooltipDisplayTextTriggeredEmpty: 'OK', tooltipFontSize: 12, tooltipFontType: 'Roboto', tooltipPrimarySortDirection: 'desc', tooltipPrimarySortField: 'thresholdLevel', tooltipSecondarySortDirection: 'desc', tooltipSecondarySortField: 'value', tooltipTimestampEnabled: true, tooltipEnabled: true, valueEnabled: true, regexPattern: '', }, }; /** @ngInject */ constructor($scope, $injector, templateSrv, private $sanitize) { super($scope, $injector); // merge existing settings with our defaults _.defaultsDeep(this.panel, this.panelDefaults); // @ts-ignore this.useDataFrames = true; this.processor = new DataProcessor({ xaxis: { mode: 'custom' }, aliasColors: {}, }); this.d3DivId = 'd3_svg_' + this.panel.id; this.containerDivId = 'container_' + this.d3DivId; this.initialized = false; this.panelContainer = null; this.templateSrv = templateSrv; this.svgContainer = null; this.panelWidth = null; this.panelHeight = null; this.polystatData = [] as PolystatModel[]; this.d3Object = null; this.series = []; this.tooltipContent = []; // convert old sort method to new this.migrateSortDirections(); this.overridesCtrl = new MetricOverridesManager($scope, templateSrv, $sanitize, this.panel.savedOverrides); this.compositesManager = new CompositesManager($scope, templateSrv, $sanitize, this.panel.savedComposites); // events this.events.on(PanelEvents.dataFramesReceived, this.onDataFramesReceived.bind(this)); this.events.on(PanelEvents.dataError, this.onDataError.bind(this)); this.events.on(PanelEvents.dataSnapshotLoad, this.onSnapshotLoad.bind(this)); this.events.on(PanelEvents.editModeInitialized, this.onInitEditMode.bind(this)); } migrateSortDirections() { if (this.panel.polystat.hexagonSortByDirection === 'asc') { this.panel.polystat.hexagonSortByDirection = 1; } if (this.panel.polystat.hexagonSortByDirection === 'desc') { this.panel.polystat.hexagonSortByDirection = 2; } if (this.panel.polystat.tooltipPrimarySortDirection === 'asc') { this.panel.polystat.tooltipPrimarySortDirection = 1; } if (this.panel.polystat.tooltipPrimarySortDirection === 'desc') { this.panel.polystat.tooltipPrimarySortDirection = 2; } if (this.panel.polystat.tooltipSecondarySortDirection === 'asc') { this.panel.polystat.tooltipSecondarySortDirection = 1; } if (this.panel.polystat.tooltipSecondarySortDirection === 'desc') { this.panel.polystat.tooltipSecondarySortDirection = 2; } } onInitEditMode() { // determine the path to this plugin base on the name found in panel.type const thisPanelPath = 'public/plugins/' + this.panel.type + '/'; // add the relative path to the partial const optionsPath = thisPanelPath + 'partials/editor.options.html'; this.addEditorTab('Options', optionsPath, 2); const overridesPath = thisPanelPath + 'partials/editor.overrides.html'; this.addEditorTab('Overrides', overridesPath, 3); const compositesPath = thisPanelPath + 'partials/editor.composites.html'; this.addEditorTab('Composites', compositesPath, 4); // disabled for now const mappingsPath = thisPanelPath + 'partials/editor.mappings.html'; this.addEditorTab('Value Mappings', mappingsPath, 5); } /** * [setContainer description] * @param {[type]} container [description] */ setContainer(container) { this.panelContainer = container; this.svgContainer = container; } // determine the width of a panel by the span and viewport // the link element object can be used to get the width more reliably getPanelWidthFailsafe() { let trueWidth = 0; if (typeof this.panel.gridPos !== 'undefined') { // 24 slots is fullscreen, get the viewport and divide to approximate the width const viewPortWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); const pixelsPerSlot = viewPortWidth / 24; trueWidth = Math.round(this.panel.gridPos.w * pixelsPerSlot); return trueWidth; } // grafana5 - use this.panel.gridPos.w, this.panel.gridPos.h if (typeof this.panel.span === 'undefined') { // check if inside edit mode if (this.editModeInitiated) { // width is clientWidth of document trueWidth = Math.max(document.documentElement.clientWidth, window.innerWidth); } else { // get the width based on the scaled container (v5 needs this) trueWidth = this.panelContainer.offsetParent.clientWidth; } } else { // v4 and previous used fixed spans const viewPortWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); // get the pixels of a span const pixelsPerSpan = viewPortWidth / 12; // multiply num spans by pixelsPerSpan trueWidth = Math.round(this.panel.span * pixelsPerSpan); } return trueWidth; } getPanelHeight() { // panel can have a fixed height set via "General" tab in panel editor let tmpPanelHeight = this.panel.height; if (typeof tmpPanelHeight === 'undefined' || tmpPanelHeight === '') { // grafana also supplies the height, try to use that if the panel does not have a height tmpPanelHeight = String(this.height); // v4 and earlier define this height, detect span for pre-v5 if (typeof this.panel.span !== 'undefined') { // if there is no header, adjust height to use all space available let panelTitleOffset = 20; if (this.panel.title !== '') { panelTitleOffset = 42; } tmpPanelHeight = String(this.containerHeight - panelTitleOffset); // offset for header } if (typeof tmpPanelHeight === 'undefined') { // height still cannot be determined, get it from the row instead tmpPanelHeight = this.row.height; if (typeof tmpPanelHeight === 'undefined') { // last resort - default to 250px (this should never happen) tmpPanelHeight = '250'; } } } // replace px tmpPanelHeight = tmpPanelHeight.replace('px', ''); // convert to numeric value const actualHeight = parseInt(tmpPanelHeight, 10); return actualHeight; } clearSVG() { if ($('#' + this.d3DivId).length) { $('#' + this.d3DivId).remove(); } if ($('#' + this.d3DivId + '-panel').length) { $('#' + this.d3DivId + '-panel').remove(); } if ($('#' + this.d3DivId + '-tooltip').length) { $('#' + this.d3DivId + '-tooltip').remove(); } } applyRegexPattern() { let seriesList = this.series; for (let i = 0; i < seriesList.length; i++) { if (this.panel.polystat.regexPattern !== '' && this.panel.polystat.regexPattern !== undefined) { const regexVal = stringToJsRegex(this.panel.polystat.regexPattern); if (seriesList[i].id && regexVal.test(seriesList[i].id.toString())) { const temp = regexVal.exec(seriesList[i].id.toString()); if (!temp) { continue; } let extractedtxt = ''; if (temp.length > 1) { temp.slice(1).forEach((value, i) => { if (value) { extractedtxt += extractedtxt.length > 0 ? ' ' + value.toString() : value.toString(); } }); seriesList[i].alias = extractedtxt; seriesList[i].label = extractedtxt; } } } else { seriesList[i].alias = seriesList[i].id; seriesList[i].label = seriesList[i].id; } } this.series = seriesList; } renderD3() { //this.setValues(this.data); this.clearSVG(); if (this.panelWidth === 0) { this.panelWidth = this.getPanelWidthFailsafe(); } this.panelHeight = this.getPanelHeight(); const margin = { top: 0, right: 0, bottom: 0, left: 0 }; const width = this.panelWidth; const height = this.panelHeight; margin.top = 0; // pre-v5, with title, set top margin to at least 7px if (typeof this.panel.span !== 'undefined' && this.panel.title !== '') { margin.top = 7; } margin.bottom = 0; const config: PolystatConfigs = this.panel.polystat; // new attributes may not be defined in older panel definitions if (typeof config.polygonBorderSize === 'undefined') { config.polygonBorderSize = 0; } if (typeof config.polygonBorderColor === 'undefined') { config.polygonBorderColor = '#000000'; } if (this.polystatData.length === 0) { this.d3Object = null; // no data this.svgContainer.innerHTML = `<div style="text-align: center; vertical-align: middle; font-size: x-large; line-height: ${height}px;" id="${this.d3DivId}"> NO DATA </div>`; return; } // try deep copy of data so we don't get a reference and leak const copiedData = _.cloneDeep(this.polystatData); const opt = { width: width, height: height, radius: config.radius, radiusAutoSize: config.radiusAutoSize, tooltipFontSize: config.tooltipFontSize, tooltipFontType: config.tooltipFontType, data: copiedData, displayLimit: config.displayLimit, globalDisplayMode: config.globalDisplayMode, columns: config.columns, columnAutoSize: config.columnAutoSize, rows: config.rows, rowAutoSize: config.rowAutoSize, tooltipContent: this.tooltipContent, animationSpeed: config.animationSpeed, defaultClickThrough: this.getDefaultClickThrough(NaN), polystat: config, }; this.d3Object = null; this.d3Object = new D3Wrapper(this.templateSrv, this.svgContainer, this.d3DivId, opt); this.d3Object.draw(); } removeValueMap(map) { const index = _.indexOf(this.panel.valueMaps, map); this.panel.valueMaps.splice(index, 1); this.render(); } applyRegex() { this.applyRegexPattern(); this.render(); } addValueMap() { this.panel.valueMaps.push({ value: '', op: '=', text: '' }); } removeRangeMap(rangeMap) { const index = _.indexOf(this.panel.rangeMaps, rangeMap); this.panel.rangeMaps.splice(index, 1); this.render(); } addRangeMap() { this.panel.rangeMaps.push({ from: '', to: '', text: '' }); } // Called for global or override onThresholdsChanged(override?: any) { // Query and reprocess this.panel.refresh(); } link(scope, elem, attrs, ctrl) { if (!scope) { return; } if (!attrs) { return; } const panelByClass = elem.find('.grafana-d3-polystat'); panelByClass.append('<div style="width: 100%; height: 100%;" id="' + ctrl.containerDivId + '"></div>'); const container = panelByClass[0].childNodes[0]; ctrl.setContainer(container); elem = elem.find('.grafana-d3-polystat'); const render = () => { // try to get the width ctrl.panelWidth = elem.width(); ctrl.renderD3(); }; this.events.on(PanelEvents.render, () => { // try to get the width ctrl.panelWidth = elem.width(); render(); ctrl.renderingCompleted(); }); } setValues() { const config: PolystatConfigs = this.panel.polystat; // ignore the above and use a timeseries this.polystatData.length = 0; this.applyRegexPattern(); if (this.series && this.series.length > 0) { for (let index = 0; index < this.series.length; index++) { const aSeries = this.series[index]; // omit series with no datapoints if (aSeries.datapoints.length > 0) { const converted = Transformers.TimeSeriesToPolystat(config.globalOperatorName, aSeries); this.polystatData.push(converted); } } } // apply global unit formatting and decimals this.applyGlobalFormatting(this.polystatData); // now sort this.polystatData = _.orderBy( this.polystatData, [config.hexagonSortByField], [this.panel.polystat.hexagonSortByDirection] ); // this needs to be performed after sorting rules are applied // apply overrides if ( this.overridesCtrl.metricOverrides.length === 0 || this.overridesCtrl.metricOverrides.length !== this.panel.savedOverrides ) { this.overridesCtrl.metricOverrides = this.panel.savedOverrides; } this.overridesCtrl.applyOverrides(this.polystatData); // apply composites, this will filter as needed and set clickthrough if ( this.compositesManager.metricComposites.length === 0 || this.compositesManager.metricComposites.length !== this.panel.savedComposites ) { this.compositesManager.metricComposites = this.panel.savedComposites; } this.polystatData = this.compositesManager.applyComposites(this.polystatData); // apply global clickthrough to all items not set for (let index = 0; index < this.polystatData.length; index++) { if (this.polystatData[index].clickThrough.length === 0) { // add the series alias as a var to the clickthroughurl this.polystatData[index].clickThrough = this.getDefaultClickThrough(index); this.polystatData[index].newTabEnabled = config.defaultClickThroughNewTab; this.polystatData[index].sanitizeURLEnabled = config.defaultClickThroughSanitize; this.polystatData[index].sanitizedURL = this.$sanitize(this.polystatData[index].clickThrough); } } // filter out by globalDisplayMode this.polystatData = this.filterByGlobalDisplayMode(this.polystatData); // now sort by field specified this.polystatData = SortVariableValuesByField( this.polystatData, this.panel.polystat.hexagonSortByField, this.panel.polystat.hexagonSortByDirection ); // generate tooltips this.tooltipContent = Tooltip.generate(this.$scope, this.polystatData, config); } applyGlobalFormatting(data: any) { const mappings = convertOldAngularValueMapping(this.panel); for (let index = 0; index < data.length; index++) { // Check for mapped value, if nothing set, format value if (data[index].value !== null) { const mappedValue = getMappedValue(mappings, data[index].value.toString()); if (mappedValue && mappedValue.text !== '') { data[index].valueFormatted = mappedValue.text; } else { const formatFunc = kbn.valueFormats[this.panel.polystat.globalUnitFormat]; if (formatFunc) { const result = GetDecimalsForValue(data[index].value, this.panel.polystat.globalDecimals); data[index].valueFormatted = formatFunc(data[index].value, result.decimals, result.scaledDecimals); data[index].valueRounded = kbn.roundValue(data[index].value, result.decimals); } } // default the color to the global setting data[index].color = this.panel.polystat.polygonGlobalFillColor; } } } filterByGlobalDisplayMode(data: any) { const filteredMetrics: number[] = []; const compositeMetrics: PolystatModel[] = []; if (this.panel.polystat.globalDisplayMode !== 'all') { const dataLen = data.length; for (let i = 0; i < dataLen; i++) { const item = data[i]; // keep if composite if (item.isComposite) { compositeMetrics.push(item); } if (item.thresholdLevel < 1) { // push the index number filteredMetrics.push(i); } } // remove filtered metrics, use splice in reverse order for (let i = data.length; i >= 0; i--) { if (_.includes(filteredMetrics, i)) { data.splice(i, 1); } } if (data.length === 0) { if (compositeMetrics.length > 0) { // set data to be all of the composites data = compositeMetrics; } } } return data; } onDataError(err: DataFrame[]) { console.log(err); this.onDataFramesReceived([]); this.render(); } onSnapshotLoad(dataList: LegacyResponseData[]) { this.onDataFramesReceived(getProcessedDataFrames(dataList)); } seriesToPolystat(globalOperatorName: string, data: any) { const converted = Transformers.TimeSeriesToPolystat(globalOperatorName, data); return converted; } tableToPolystat(globalOperatorName: string, data: any) { return null; } onDataFramesReceived(data: DataFrame[]) { //console.log(JSON.stringify(data)); // check if data contains a field called Time of type time data = InsertTime(data); // if it does not, insert one with time "now" this.series = this.processor.getSeriesList({ dataList: data, range: this.range }).map((ts) => { ts.color = undefined; // remove whatever the processor set // TODO: this needs to be added to the editor options ts.flotpairs = ts.getFlotPairs(this.panel.nullPointMode); return ts; }); // @ts-ignore this.dataWarning = null; const datapointsCount = _.reduce( this.series, (sum, series) => { return sum + series.datapoints.length; }, 0 ); if (datapointsCount === 0) { // @ts-ignore this.dataWarning = { title: 'No data points', tip: 'No datapoints returned from data query', }; } else { for (const series of this.series) { if (series.isOutsideRange) { // @ts-ignore this.dataWarning = { title: 'Data points outside time range', tip: 'Can be caused by timezone mismatch or missing time filter in query', }; break; } } } this.setValues(); this.render(); } seriesHandler(seriesData) { const series = new TimeSeries({ datapoints: seriesData.datapoints, alias: seriesData.target, }); series.flotpairs = series.getFlotPairs(this.panel.nullPointMode); return series; } invertColorOrder() { const tmp = this.panel.colors[0]; this.panel.colors[0] = this.panel.colors[2]; this.panel.colors[2] = tmp; this.render(); } /** * Speed must not be less than 500ms */ validateAnimationSpeed() { const speed = this.panel.polystat.animationSpeed; let newSpeed = 5000; if (speed) { if (!isNaN(parseInt(speed, 10))) { const checkSpeed = parseInt(speed, 10); if (checkSpeed >= 500) { newSpeed = checkSpeed; } else { // Min speed is 500 newSpeed = 500; } } } this.panel.polystat.animationSpeed = newSpeed; this.render(); } validateDisplayLimit() { const limit = this.panel.polystat.displayLimit; let newLimit = 100; if (limit === null) { newLimit = 0; } else { if (!isNaN(parseInt(limit, 10))) { const checkLimit = parseInt(limit, 10); if (checkLimit >= 0) { newLimit = checkLimit; } } } // 0 means unlimited if (newLimit === 0) { this.panel.polystat.displayLimit = ''; } else { this.panel.polystat.displayLimit = newLimit; } this.render(); } validateColumnValue() { if (this.panel.polystat.columnAutoSize) { this.panel.polystat.columns = ''; } else { const columns = this.panel.polystat.columns; let newColumns = 1; if (columns) { if (!isNaN(parseInt(columns, 10))) { const checkColumns = parseInt(columns, 10); if (checkColumns > 0) { newColumns = checkColumns; } } } this.panel.polystat.columns = newColumns; } this.render(); } validateRowValue() { if (this.panel.polystat.rowAutoSize) { this.panel.polystat.rows = ''; } else { const rows = this.panel.polystat.rows; let newRows = 1; if (rows) { if (!isNaN(parseInt(rows, 10))) { const checkRows = parseInt(rows, 10); if (checkRows > 0) { newRows = checkRows; } } } this.panel.polystat.rows = newRows; } this.render(); } validateRadiusValue() { if (this.panel.polystat.radiusAutoSize) { this.panel.polystat.radius = ''; } else { const radius = this.panel.polystat.radius; let newRadius = 25; if (radius !== null) { if (!isNaN(parseInt(radius, 10))) { const checkRadius = parseInt(radius, 10); if (checkRadius > 0) { newRadius = checkRadius; } } } this.panel.polystat.radius = newRadius; } this.render(); } validateFontColorValue() { if (this.panel.polystat.fontAutoColor) { this.panel.polystat.fontColor = ''; } else if (!this.panel.polystat.fontColor) { this.panel.polystat.fontColor = 'black'; } this.render(); } validateBorderSizeValue() { const borderSize = this.panel.polystat.polygonBorderSize; let newBorderSize = 2; if (borderSize !== null) { if (!isNaN(parseInt(borderSize, 10))) { const checkBorderSize = parseInt(borderSize, 10); if (checkBorderSize >= 0) { newBorderSize = checkBorderSize; } } } this.panel.polystat.polygonBorderSize = newBorderSize; this.render(); } getDefaultClickThrough(index: number) { let url = this.panel.polystat.defaultClickThrough; // apply both types of transforms, one targeted at the data item index, and secondly the nth variant url = ClickThroughTransformer.tranformSingleMetric(index, url, this.polystatData); url = ClickThroughTransformer.tranformNthMetric(url, this.polystatData); // process template variables inside clickthrough url = this.templateSrv.replace(url, 'text'); return url; } setGlobalUnitFormat(subItem) { this.panel.polystat.globalUnitFormat = subItem.value; this.panel.refresh(); } } export { D3PolystatPanelCtrl, D3PolystatPanelCtrl as MetricsPanelCtrl };
the_stack
module android.widget { import Rect = android.graphics.Rect; import Trace = android.os.Trace; import Gravity = android.view.Gravity; import KeyEvent = android.view.KeyEvent; import SoundEffectConstants = android.view.SoundEffectConstants; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import Integer = java.lang.Integer; import AbsListView = android.widget.AbsListView; import LayoutParams = android.widget.AbsListView.LayoutParams; import Adapter = android.widget.Adapter; import Checkable = android.widget.Checkable; import ListAdapter = android.widget.ListAdapter; import ListView = android.widget.ListView; import AttrBinder = androidui.attr.AttrBinder; /** * A view that shows items in two-dimensional scrolling grid. The items in the * grid come from the {@link ListAdapter} associated with this view. * * <p>See the <a href="{@docRoot}guide/topics/ui/layout/gridview.html">Grid * View</a> guide.</p> * * @attr ref android.R.styleable#GridView_horizontalSpacing * @attr ref android.R.styleable#GridView_verticalSpacing * @attr ref android.R.styleable#GridView_stretchMode * @attr ref android.R.styleable#GridView_columnWidth * @attr ref android.R.styleable#GridView_numColumns * @attr ref android.R.styleable#GridView_gravity */ export class GridView extends AbsListView { /** * Disables stretching. * * @see #setStretchMode(int) */ static NO_STRETCH:number = 0; /** * Stretches the spacing between columns. * * @see #setStretchMode(int) */ static STRETCH_SPACING:number = 1; /** * Stretches columns. * * @see #setStretchMode(int) */ static STRETCH_COLUMN_WIDTH:number = 2; /** * Stretches the spacing between columns. The spacing is uniform. * * @see #setStretchMode(int) */ static STRETCH_SPACING_UNIFORM:number = 3; /** * Creates as many columns as can fit on screen. * * @see #setNumColumns(int) */ static AUTO_FIT:number = -1; private mNumColumns:number = GridView.AUTO_FIT; private mHorizontalSpacing:number = 0; private mRequestedHorizontalSpacing:number = 0; private mVerticalSpacing:number = 0; private mStretchMode:number = GridView.STRETCH_COLUMN_WIDTH; private mColumnWidth:number = 0; private mRequestedColumnWidth:number = 0; private mRequestedNumColumns:number = 0; private mReferenceView:View = null; private mReferenceViewInSelectedRow:View = null; private mGravity:number = Gravity.LEFT; private mTempRect:Rect = new Rect(); constructor(context:android.content.Context, attrs:HTMLElement, defStyle=android.R.attr.gridViewStyle) { super(context, attrs, defStyle); let a = context.obtainStyledAttributes(attrs, defStyle); let hSpacing:number = a.getDimensionPixelOffset('horizontalSpacing', 0); this.setHorizontalSpacing(hSpacing); let vSpacing:number = a.getDimensionPixelOffset('verticalSpacing', 0); this.setVerticalSpacing(vSpacing); let stretchModeS = a.getAttrValue('stretchMode'); if (stretchModeS) { switch (stretchModeS) { case "none": this.setStretchMode(GridView.NO_STRETCH); break; case "spacingWidth": this.setStretchMode(GridView.STRETCH_SPACING); break; case "columnWidth": this.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); break; case "spacingWidthUniform": this.setStretchMode(GridView.STRETCH_SPACING_UNIFORM); break; } } let columnWidth:number = a.getDimensionPixelOffset('columnWidth', -1); if (columnWidth > 0) { this.setColumnWidth(columnWidth); } let numColumns:number = a.getInt('numColumns', 1); this.setNumColumns(numColumns); let gravityS = a.getAttrValue('gravity'); if (gravityS) { this.setGravity(Gravity.parseGravity(gravityS, this.mGravity)); } a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('horizontalSpacing', { setter(v:GridView, value:any, attrBinder:AttrBinder) { v.setHorizontalSpacing(attrBinder.parseNumberPixelOffset(value, 0)); }, getter(v:GridView) { return v.getHorizontalSpacing(); } }).set('verticalSpacing', { setter(v:GridView, value:any, attrBinder:AttrBinder) { v.setVerticalSpacing(attrBinder.parseNumberPixelOffset(value, 0)); }, getter(v:GridView) { return v.getVerticalSpacing(); } }).set('stretchMode', { setter(v:GridView, value:any, attrBinder:AttrBinder) { v.setStretchMode(attrBinder.parseEnum(value, new Map<string, number>() .set("none", GridView.NO_STRETCH) .set("spacingWidth", GridView.STRETCH_SPACING) .set("columnWidth", GridView.STRETCH_COLUMN_WIDTH) .set("spacingWidthUniform", GridView.STRETCH_SPACING_UNIFORM), GridView.STRETCH_COLUMN_WIDTH)); }, getter(v:GridView) { return v.getStretchMode(); } }).set('columnWidth', { setter(v:GridView, value:any, attrBinder:AttrBinder) { let columnWidth = attrBinder.parseNumberPixelOffset(value, -1); if(columnWidth > 0 ){ this.setColumnWidth(columnWidth); } }, getter(v:GridView) { return v.getColumnWidth(); } }).set('numColumns', { setter(v:GridView, value:any, attrBinder:AttrBinder) { v.setNumColumns(attrBinder.parseInt(value, 1)); }, getter(v:GridView) { return v.getNumColumns(); } }).set('gravity', { setter(v:GridView, value:any, attrBinder:AttrBinder) { v.setGravity(attrBinder.parseGravity(value, v.getGravity())); }, getter(v:GridView) { return v.getGravity(); } }); } getAdapter():ListAdapter { return this.mAdapter; } /** * Sets the data behind this GridView. * * @param adapter the adapter providing the grid's data */ setAdapter(adapter:ListAdapter):void { if (this.mAdapter != null && this.mDataSetObserver != null) { this.mAdapter.unregisterDataSetObserver(this.mDataSetObserver); } this.resetList(); this.mRecycler.clear(); this.mAdapter = adapter; this.mOldSelectedPosition = GridView.INVALID_POSITION; this.mOldSelectedRowId = GridView.INVALID_ROW_ID; // AbsListView#setAdapter will update choice mode states. super.setAdapter(adapter); if (this.mAdapter != null) { this.mOldItemCount = this.mItemCount; this.mItemCount = this.mAdapter.getCount(); this.mDataChanged = true; this.checkFocus(); this.mDataSetObserver = new AbsListView.AdapterDataSetObserver(this); this.mAdapter.registerDataSetObserver(this.mDataSetObserver); this.mRecycler.setViewTypeCount(this.mAdapter.getViewTypeCount()); let position:number; if (this.mStackFromBottom) { position = this.lookForSelectablePosition(this.mItemCount - 1, false); } else { position = this.lookForSelectablePosition(0, true); } this.setSelectedPositionInt(position); this.setNextSelectedPositionInt(position); this.checkSelectionChanged(); } else { this.checkFocus(); // Nothing selected this.checkSelectionChanged(); } this.requestLayout(); } lookForSelectablePosition(position:number, lookDown:boolean):number { const adapter:ListAdapter = this.mAdapter; if (adapter == null || this.isInTouchMode()) { return GridView.INVALID_POSITION; } if (position < 0 || position >= this.mItemCount) { return GridView.INVALID_POSITION; } return position; } /** * {@inheritDoc} */ fillGap(down:boolean):void { const numColumns:number = this.mNumColumns; const verticalSpacing:number = this.mVerticalSpacing; const count:number = this.getChildCount(); if (down) { let paddingTop:number = 0; if ((this.mGroupFlags & GridView.CLIP_TO_PADDING_MASK) == GridView.CLIP_TO_PADDING_MASK) { paddingTop = this.getListPaddingTop(); } const startOffset:number = count > 0 ? this.getChildAt(count - 1).getBottom() + verticalSpacing : paddingTop; let position:number = this.mFirstPosition + count; if (this.mStackFromBottom) { position += numColumns - 1; } this.fillDown(position, startOffset); this.correctTooHigh(numColumns, verticalSpacing, this.getChildCount()); } else { let paddingBottom:number = 0; if ((this.mGroupFlags & GridView.CLIP_TO_PADDING_MASK) == GridView.CLIP_TO_PADDING_MASK) { paddingBottom = this.getListPaddingBottom(); } const startOffset:number = count > 0 ? this.getChildAt(0).getTop() - verticalSpacing : this.getHeight() - paddingBottom; let position:number = this.mFirstPosition; if (!this.mStackFromBottom) { position -= numColumns; } else { position--; } this.fillUp(position, startOffset); this.correctTooLow(numColumns, verticalSpacing, this.getChildCount()); } } /** * Fills the list from pos down to the end of the list view. * * @param pos The first position to put in the list * * @param nextTop The location where the top of the item associated with pos * should be drawn * * @return The view that is currently selected, if it happens to be in the * range that we draw. */ private fillDown(pos:number, nextTop:number):View { let selectedView:View = null; let end:number = (this.mBottom - this.mTop); if ((this.mGroupFlags & GridView.CLIP_TO_PADDING_MASK) == GridView.CLIP_TO_PADDING_MASK) { end -= this.mListPadding.bottom; } while (nextTop < end && pos < this.mItemCount) { let temp:View = this.makeRow(pos, nextTop, true); if (temp != null) { selectedView = temp; } // mReferenceView will change with each call to makeRow() // do not cache in a local variable outside of this loop nextTop = this.mReferenceView.getBottom() + this.mVerticalSpacing; pos += this.mNumColumns; } this.setVisibleRangeHint(this.mFirstPosition, this.mFirstPosition + this.getChildCount() - 1); return selectedView; } private makeRow(startPos:number, y:number, flow:boolean):View { const columnWidth:number = this.mColumnWidth; const horizontalSpacing:number = this.mHorizontalSpacing; const isLayoutRtl:boolean = this.isLayoutRtl(); let last:number; let nextLeft:number; if (isLayoutRtl) { nextLeft = this.getWidth() - this.mListPadding.right - columnWidth - ((this.mStretchMode == GridView.STRETCH_SPACING_UNIFORM) ? horizontalSpacing : 0); } else { nextLeft = this.mListPadding.left + ((this.mStretchMode == GridView.STRETCH_SPACING_UNIFORM) ? horizontalSpacing : 0); } if (!this.mStackFromBottom) { last = Math.min(startPos + this.mNumColumns, this.mItemCount); } else { last = startPos + 1; startPos = Math.max(0, startPos - this.mNumColumns + 1); if (last - startPos < this.mNumColumns) { const deltaLeft:number = (this.mNumColumns - (last - startPos)) * (columnWidth + horizontalSpacing); nextLeft += (isLayoutRtl ? -1 : +1) * deltaLeft; } } let selectedView:View = null; const hasFocus:boolean = this.shouldShowSelector(); const inClick:boolean = this.touchModeDrawsInPressedState(); const selectedPosition:number = this.mSelectedPosition; let child:View = null; for (let pos:number = startPos; pos < last; pos++) { // is this the selected item? let selected:boolean = pos == selectedPosition; // does the list view have focus or contain focus const where:number = flow ? -1 : pos - startPos; child = this.makeAndAddView(pos, y, flow, nextLeft, selected, where); nextLeft += (isLayoutRtl ? -1 : +1) * columnWidth; if (pos < last - 1) { nextLeft += horizontalSpacing; } if (selected && (hasFocus || inClick)) { selectedView = child; } } this.mReferenceView = child; if (selectedView != null) { this.mReferenceViewInSelectedRow = this.mReferenceView; } return selectedView; } /** * Fills the list from pos up to the top of the list view. * * @param pos The first position to put in the list * * @param nextBottom The location where the bottom of the item associated * with pos should be drawn * * @return The view that is currently selected */ private fillUp(pos:number, nextBottom:number):View { let selectedView:View = null; let end:number = 0; if ((this.mGroupFlags & GridView.CLIP_TO_PADDING_MASK) == GridView.CLIP_TO_PADDING_MASK) { end = this.mListPadding.top; } while (nextBottom > end && pos >= 0) { let temp:View = this.makeRow(pos, nextBottom, false); if (temp != null) { selectedView = temp; } nextBottom = this.mReferenceView.getTop() - this.mVerticalSpacing; this.mFirstPosition = pos; pos -= this.mNumColumns; } if (this.mStackFromBottom) { this.mFirstPosition = Math.max(0, pos + 1); } this.setVisibleRangeHint(this.mFirstPosition, this.mFirstPosition + this.getChildCount() - 1); return selectedView; } /** * Fills the list from top to bottom, starting with mFirstPosition * * @param nextTop The location where the top of the first item should be * drawn * * @return The view that is currently selected */ private fillFromTop(nextTop:number):View { this.mFirstPosition = Math.min(this.mFirstPosition, this.mSelectedPosition); this.mFirstPosition = Math.min(this.mFirstPosition, this.mItemCount - 1); if (this.mFirstPosition < 0) { this.mFirstPosition = 0; } this.mFirstPosition -= this.mFirstPosition % this.mNumColumns; return this.fillDown(this.mFirstPosition, nextTop); } private fillFromBottom(lastPosition:number, nextBottom:number):View { lastPosition = Math.max(lastPosition, this.mSelectedPosition); lastPosition = Math.min(lastPosition, this.mItemCount - 1); const invertedPosition:number = this.mItemCount - 1 - lastPosition; lastPosition = this.mItemCount - 1 - (invertedPosition - (invertedPosition % this.mNumColumns)); return this.fillUp(lastPosition, nextBottom); } private fillSelection(childrenTop:number, childrenBottom:number):View { const selectedPosition:number = this.reconcileSelectedPosition(); const numColumns:number = this.mNumColumns; const verticalSpacing:number = this.mVerticalSpacing; let rowStart:number; let rowEnd:number = -1; if (!this.mStackFromBottom) { rowStart = selectedPosition - (selectedPosition % numColumns); } else { const invertedSelection:number = this.mItemCount - 1 - selectedPosition; rowEnd = this.mItemCount - 1 - (invertedSelection - (invertedSelection % numColumns)); rowStart = Math.max(0, rowEnd - numColumns + 1); } const fadingEdgeLength:number = this.getVerticalFadingEdgeLength(); const topSelectionPixel:number = this.getTopSelectionPixel(childrenTop, fadingEdgeLength, rowStart); const sel:View = this.makeRow(this.mStackFromBottom ? rowEnd : rowStart, topSelectionPixel, true); this.mFirstPosition = rowStart; const referenceView:View = this.mReferenceView; if (!this.mStackFromBottom) { this.fillDown(rowStart + numColumns, referenceView.getBottom() + verticalSpacing); this.pinToBottom(childrenBottom); this.fillUp(rowStart - numColumns, referenceView.getTop() - verticalSpacing); this.adjustViewsUpOrDown(); } else { const bottomSelectionPixel:number = this.getBottomSelectionPixel(childrenBottom, fadingEdgeLength, numColumns, rowStart); const offset:number = bottomSelectionPixel - referenceView.getBottom(); this.offsetChildrenTopAndBottom(offset); this.fillUp(rowStart - 1, referenceView.getTop() - verticalSpacing); this.pinToTop(childrenTop); this.fillDown(rowEnd + numColumns, referenceView.getBottom() + verticalSpacing); this.adjustViewsUpOrDown(); } return sel; } private pinToTop(childrenTop:number):void { if (this.mFirstPosition == 0) { const top:number = this.getChildAt(0).getTop(); const offset:number = childrenTop - top; if (offset < 0) { this.offsetChildrenTopAndBottom(offset); } } } private pinToBottom(childrenBottom:number):void { const count:number = this.getChildCount(); if (this.mFirstPosition + count == this.mItemCount) { const bottom:number = this.getChildAt(count - 1).getBottom(); const offset:number = childrenBottom - bottom; if (offset > 0) { this.offsetChildrenTopAndBottom(offset); } } } findMotionRow(y:number):number { const childCount:number = this.getChildCount(); if (childCount > 0) { const numColumns:number = this.mNumColumns; if (!this.mStackFromBottom) { for (let i:number = 0; i < childCount; i += numColumns) { if (y <= this.getChildAt(i).getBottom()) { return this.mFirstPosition + i; } } } else { for (let i:number = childCount - 1; i >= 0; i -= numColumns) { if (y >= this.getChildAt(i).getTop()) { return this.mFirstPosition + i; } } } } return GridView.INVALID_POSITION; } /** * Layout during a scroll that results from tracking motion events. Places * the mMotionPosition view at the offset specified by mMotionViewTop, and * then build surrounding views from there. * * @param position the position at which to start filling * @param top the top of the view at that position * @return The selected view, or null if the selected view is outside the * visible area. */ private fillSpecific(position:number, top:number):View { const numColumns:number = this.mNumColumns; let motionRowStart:number; let motionRowEnd:number = -1; if (!this.mStackFromBottom) { motionRowStart = position - (position % numColumns); } else { const invertedSelection:number = this.mItemCount - 1 - position; motionRowEnd = this.mItemCount - 1 - (invertedSelection - (invertedSelection % numColumns)); motionRowStart = Math.max(0, motionRowEnd - numColumns + 1); } const temp:View = this.makeRow(this.mStackFromBottom ? motionRowEnd : motionRowStart, top, true); // Possibly changed again in fillUp if we add rows above this one. this.mFirstPosition = motionRowStart; const referenceView:View = this.mReferenceView; // We didn't have anything to layout, bail out if (referenceView == null) { return null; } const verticalSpacing:number = this.mVerticalSpacing; let above:View; let below:View; if (!this.mStackFromBottom) { above = this.fillUp(motionRowStart - numColumns, referenceView.getTop() - verticalSpacing); this.adjustViewsUpOrDown(); below = this.fillDown(motionRowStart + numColumns, referenceView.getBottom() + verticalSpacing); // Check if we have dragged the bottom of the grid too high const childCount:number = this.getChildCount(); if (childCount > 0) { this.correctTooHigh(numColumns, verticalSpacing, childCount); } } else { below = this.fillDown(motionRowEnd + numColumns, referenceView.getBottom() + verticalSpacing); this.adjustViewsUpOrDown(); above = this.fillUp(motionRowStart - 1, referenceView.getTop() - verticalSpacing); // Check if we have dragged the bottom of the grid too high const childCount:number = this.getChildCount(); if (childCount > 0) { this.correctTooLow(numColumns, verticalSpacing, childCount); } } if (temp != null) { return temp; } else if (above != null) { return above; } else { return below; } } private correctTooHigh(numColumns:number, verticalSpacing:number, childCount:number):void { // First see if the last item is visible const lastPosition:number = this.mFirstPosition + childCount - 1; if (lastPosition == this.mItemCount - 1 && childCount > 0) { // Get the last child ... const lastChild:View = this.getChildAt(childCount - 1); // ... and its bottom edge const lastBottom:number = lastChild.getBottom(); // This is bottom of our drawable area const end:number = (this.mBottom - this.mTop) - this.mListPadding.bottom; // This is how far the bottom edge of the last view is from the bottom of the // drawable area let bottomOffset:number = end - lastBottom; const firstChild:View = this.getChildAt(0); const firstTop:number = firstChild.getTop(); // first row or the first row is scrolled off the top of the drawable area if (bottomOffset > 0 && (this.mFirstPosition > 0 || firstTop < this.mListPadding.top)) { if (this.mFirstPosition == 0) { // Don't pull the top too far down bottomOffset = Math.min(bottomOffset, this.mListPadding.top - firstTop); } // Move everything down this.offsetChildrenTopAndBottom(bottomOffset); if (this.mFirstPosition > 0) { // Fill the gap that was opened above mFirstPosition with more rows, if // possible this.fillUp(this.mFirstPosition - (this.mStackFromBottom ? 1 : numColumns), firstChild.getTop() - verticalSpacing); // Close up the remaining gap this.adjustViewsUpOrDown(); } } } } private correctTooLow(numColumns:number, verticalSpacing:number, childCount:number):void { if (this.mFirstPosition == 0 && childCount > 0) { // Get the first child ... const firstChild:View = this.getChildAt(0); // ... and its top edge const firstTop:number = firstChild.getTop(); // This is top of our drawable area const start:number = this.mListPadding.top; // This is bottom of our drawable area const end:number = (this.mBottom - this.mTop) - this.mListPadding.bottom; // This is how far the top edge of the first view is from the top of the // drawable area let topOffset:number = firstTop - start; const lastChild:View = this.getChildAt(childCount - 1); const lastBottom:number = lastChild.getBottom(); const lastPosition:number = this.mFirstPosition + childCount - 1; // last row or the last row is scrolled off the bottom of the drawable area if (topOffset > 0 && (lastPosition < this.mItemCount - 1 || lastBottom > end)) { if (lastPosition == this.mItemCount - 1) { // Don't pull the bottom too far up topOffset = Math.min(topOffset, lastBottom - end); } // Move everything up this.offsetChildrenTopAndBottom(-topOffset); if (lastPosition < this.mItemCount - 1) { // Fill the gap that was opened below the last position with more rows, if // possible this.fillDown(lastPosition + (!this.mStackFromBottom ? 1 : numColumns), lastChild.getBottom() + verticalSpacing); // Close up the remaining gap this.adjustViewsUpOrDown(); } } } } /** * Fills the grid based on positioning the new selection at a specific * location. The selection may be moved so that it does not intersect the * faded edges. The grid is then filled upwards and downwards from there. * * @param selectedTop Where the selected item should be * @param childrenTop Where to start drawing children * @param childrenBottom Last pixel where children can be drawn * @return The view that currently has selection */ private fillFromSelection(selectedTop:number, childrenTop:number, childrenBottom:number):View { const fadingEdgeLength:number = this.getVerticalFadingEdgeLength(); const selectedPosition:number = this.mSelectedPosition; const numColumns:number = this.mNumColumns; const verticalSpacing:number = this.mVerticalSpacing; let rowStart:number; let rowEnd:number = -1; if (!this.mStackFromBottom) { rowStart = selectedPosition - (selectedPosition % numColumns); } else { let invertedSelection:number = this.mItemCount - 1 - selectedPosition; rowEnd = this.mItemCount - 1 - (invertedSelection - (invertedSelection % numColumns)); rowStart = Math.max(0, rowEnd - numColumns + 1); } let sel:View; let referenceView:View; let topSelectionPixel:number = this.getTopSelectionPixel(childrenTop, fadingEdgeLength, rowStart); let bottomSelectionPixel:number = this.getBottomSelectionPixel(childrenBottom, fadingEdgeLength, numColumns, rowStart); sel = this.makeRow(this.mStackFromBottom ? rowEnd : rowStart, selectedTop, true); // Possibly changed again in fillUp if we add rows above this one. this.mFirstPosition = rowStart; referenceView = this.mReferenceView; this.adjustForTopFadingEdge(referenceView, topSelectionPixel, bottomSelectionPixel); this.adjustForBottomFadingEdge(referenceView, topSelectionPixel, bottomSelectionPixel); if (!this.mStackFromBottom) { this.fillUp(rowStart - numColumns, referenceView.getTop() - verticalSpacing); this.adjustViewsUpOrDown(); this.fillDown(rowStart + numColumns, referenceView.getBottom() + verticalSpacing); } else { this.fillDown(rowEnd + numColumns, referenceView.getBottom() + verticalSpacing); this.adjustViewsUpOrDown(); this.fillUp(rowStart - 1, referenceView.getTop() - verticalSpacing); } return sel; } /** * Calculate the bottom-most pixel we can draw the selection into * * @param childrenBottom Bottom pixel were children can be drawn * @param fadingEdgeLength Length of the fading edge in pixels, if present * @param numColumns Number of columns in the grid * @param rowStart The start of the row that will contain the selection * @return The bottom-most pixel we can draw the selection into */ private getBottomSelectionPixel(childrenBottom:number, fadingEdgeLength:number, numColumns:number, rowStart:number):number { // Last pixel we can draw the selection into let bottomSelectionPixel:number = childrenBottom; if (rowStart + numColumns - 1 < this.mItemCount - 1) { bottomSelectionPixel -= fadingEdgeLength; } return bottomSelectionPixel; } /** * Calculate the top-most pixel we can draw the selection into * * @param childrenTop Top pixel were children can be drawn * @param fadingEdgeLength Length of the fading edge in pixels, if present * @param rowStart The start of the row that will contain the selection * @return The top-most pixel we can draw the selection into */ private getTopSelectionPixel(childrenTop:number, fadingEdgeLength:number, rowStart:number):number { // first pixel we can draw the selection into let topSelectionPixel:number = childrenTop; if (rowStart > 0) { topSelectionPixel += fadingEdgeLength; } return topSelectionPixel; } /** * Move all views upwards so the selected row does not interesect the bottom * fading edge (if necessary). * * @param childInSelectedRow A child in the row that contains the selection * @param topSelectionPixel The topmost pixel we can draw the selection into * @param bottomSelectionPixel The bottommost pixel we can draw the * selection into */ private adjustForBottomFadingEdge(childInSelectedRow:View, topSelectionPixel:number, bottomSelectionPixel:number):void { // list if (childInSelectedRow.getBottom() > bottomSelectionPixel) { // Find space available above the selection into which we can // scroll upwards let spaceAbove:number = childInSelectedRow.getTop() - topSelectionPixel; // Find space required to bring the bottom of the selected item // fully into view let spaceBelow:number = childInSelectedRow.getBottom() - bottomSelectionPixel; let offset:number = Math.min(spaceAbove, spaceBelow); // Now offset the selected item to get it into view this.offsetChildrenTopAndBottom(-offset); } } /** * Move all views upwards so the selected row does not interesect the top * fading edge (if necessary). * * @param childInSelectedRow A child in the row that contains the selection * @param topSelectionPixel The topmost pixel we can draw the selection into * @param bottomSelectionPixel The bottommost pixel we can draw the * selection into */ private adjustForTopFadingEdge(childInSelectedRow:View, topSelectionPixel:number, bottomSelectionPixel:number):void { // Some of the newly selected item extends above the top of the list if (childInSelectedRow.getTop() < topSelectionPixel) { // Find space required to bring the top of the selected item // fully into view let spaceAbove:number = topSelectionPixel - childInSelectedRow.getTop(); // Find space available below the selection into which we can // scroll downwards let spaceBelow:number = bottomSelectionPixel - childInSelectedRow.getBottom(); let offset:number = Math.min(spaceAbove, spaceBelow); // Now offset the selected item to get it into view this.offsetChildrenTopAndBottom(offset); } } /** * Smoothly scroll to the specified adapter position. The view will * scroll such that the indicated position is displayed. * @param position Scroll to this adapter position. */ smoothScrollToPosition(position:number):void { super.smoothScrollToPosition(position); } /** * Smoothly scroll to the specified adapter position offset. The view will * scroll such that the indicated position is displayed. * @param offset The amount to offset from the adapter position to scroll to. */ smoothScrollByOffset(offset:number):void { super.smoothScrollByOffset(offset); } /** * Fills the grid based on positioning the new selection relative to the old * selection. The new selection will be placed at, above, or below the * location of the new selection depending on how the selection is moving. * The selection will then be pinned to the visible part of the screen, * excluding the edges that are faded. The grid is then filled upwards and * downwards from there. * * @param delta Which way we are moving * @param childrenTop Where to start drawing children * @param childrenBottom Last pixel where children can be drawn * @return The view that currently has selection */ private moveSelection(delta:number, childrenTop:number, childrenBottom:number):View { const fadingEdgeLength:number = this.getVerticalFadingEdgeLength(); const selectedPosition:number = this.mSelectedPosition; const numColumns:number = this.mNumColumns; const verticalSpacing:number = this.mVerticalSpacing; let oldRowStart:number; let rowStart:number; let rowEnd:number = -1; if (!this.mStackFromBottom) { oldRowStart = (selectedPosition - delta) - ((selectedPosition - delta) % numColumns); rowStart = selectedPosition - (selectedPosition % numColumns); } else { let invertedSelection:number = this.mItemCount - 1 - selectedPosition; rowEnd = this.mItemCount - 1 - (invertedSelection - (invertedSelection % numColumns)); rowStart = Math.max(0, rowEnd - numColumns + 1); invertedSelection = this.mItemCount - 1 - (selectedPosition - delta); oldRowStart = this.mItemCount - 1 - (invertedSelection - (invertedSelection % numColumns)); oldRowStart = Math.max(0, oldRowStart - numColumns + 1); } const rowDelta:number = rowStart - oldRowStart; const topSelectionPixel:number = this.getTopSelectionPixel(childrenTop, fadingEdgeLength, rowStart); const bottomSelectionPixel:number = this.getBottomSelectionPixel(childrenBottom, fadingEdgeLength, numColumns, rowStart); // Possibly changed again in fillUp if we add rows above this one. this.mFirstPosition = rowStart; let sel:View; let referenceView:View; if (rowDelta > 0) { /* * Case 1: Scrolling down. */ const oldBottom:number = this.mReferenceViewInSelectedRow == null ? 0 : this.mReferenceViewInSelectedRow.getBottom(); sel = this.makeRow(this.mStackFromBottom ? rowEnd : rowStart, oldBottom + verticalSpacing, true); referenceView = this.mReferenceView; this.adjustForBottomFadingEdge(referenceView, topSelectionPixel, bottomSelectionPixel); } else if (rowDelta < 0) { /* * Case 2: Scrolling up. */ const oldTop:number = this.mReferenceViewInSelectedRow == null ? 0 : this.mReferenceViewInSelectedRow.getTop(); sel = this.makeRow(this.mStackFromBottom ? rowEnd : rowStart, oldTop - verticalSpacing, false); referenceView = this.mReferenceView; this.adjustForTopFadingEdge(referenceView, topSelectionPixel, bottomSelectionPixel); } else { /* * Keep selection where it was */ const oldTop:number = this.mReferenceViewInSelectedRow == null ? 0 : this.mReferenceViewInSelectedRow.getTop(); sel = this.makeRow(this.mStackFromBottom ? rowEnd : rowStart, oldTop, true); referenceView = this.mReferenceView; } if (!this.mStackFromBottom) { this.fillUp(rowStart - numColumns, referenceView.getTop() - verticalSpacing); this.adjustViewsUpOrDown(); this.fillDown(rowStart + numColumns, referenceView.getBottom() + verticalSpacing); } else { this.fillDown(rowEnd + numColumns, referenceView.getBottom() + verticalSpacing); this.adjustViewsUpOrDown(); this.fillUp(rowStart - 1, referenceView.getTop() - verticalSpacing); } return sel; } private determineColumns(availableSpace:number):boolean { const requestedHorizontalSpacing:number = this.mRequestedHorizontalSpacing; const stretchMode:number = this.mStretchMode; const requestedColumnWidth:number = this.mRequestedColumnWidth; let didNotInitiallyFit:boolean = false; if (this.mRequestedNumColumns == GridView.AUTO_FIT) { if (requestedColumnWidth > 0) { // Client told us to pick the number of columns this.mNumColumns = (availableSpace + requestedHorizontalSpacing) / (requestedColumnWidth + requestedHorizontalSpacing); } else { // Just make up a number if we don't have enough info this.mNumColumns = 2; } } else { // We picked the columns this.mNumColumns = this.mRequestedNumColumns; } if (this.mNumColumns <= 0) { this.mNumColumns = 1; } switch(stretchMode) { case GridView.NO_STRETCH: // Nobody stretches this.mColumnWidth = requestedColumnWidth; this.mHorizontalSpacing = requestedHorizontalSpacing; break; default: let spaceLeftOver:number = availableSpace - (this.mNumColumns * requestedColumnWidth) - ((this.mNumColumns - 1) * requestedHorizontalSpacing); if (spaceLeftOver < 0) { didNotInitiallyFit = true; } switch(stretchMode) { case GridView.STRETCH_COLUMN_WIDTH: // Stretch the columns this.mColumnWidth = requestedColumnWidth + spaceLeftOver / this.mNumColumns; this.mHorizontalSpacing = requestedHorizontalSpacing; break; case GridView.STRETCH_SPACING: // Stretch the spacing between columns this.mColumnWidth = requestedColumnWidth; if (this.mNumColumns > 1) { this.mHorizontalSpacing = requestedHorizontalSpacing + spaceLeftOver / (this.mNumColumns - 1); } else { this.mHorizontalSpacing = requestedHorizontalSpacing + spaceLeftOver; } break; case GridView.STRETCH_SPACING_UNIFORM: // Stretch the spacing between columns this.mColumnWidth = requestedColumnWidth; if (this.mNumColumns > 1) { this.mHorizontalSpacing = requestedHorizontalSpacing + spaceLeftOver / (this.mNumColumns + 1); } else { this.mHorizontalSpacing = requestedHorizontalSpacing + spaceLeftOver; } break; } break; } return didNotInitiallyFit; } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { // Sets up mListPadding super.onMeasure(widthMeasureSpec, heightMeasureSpec); let widthMode:number = View.MeasureSpec.getMode(widthMeasureSpec); let heightMode:number = View.MeasureSpec.getMode(heightMeasureSpec); let widthSize:number = View.MeasureSpec.getSize(widthMeasureSpec); let heightSize:number = View.MeasureSpec.getSize(heightMeasureSpec); if (widthMode == View.MeasureSpec.UNSPECIFIED) { if (this.mColumnWidth > 0) { widthSize = this.mColumnWidth + this.mListPadding.left + this.mListPadding.right; } else { widthSize = this.mListPadding.left + this.mListPadding.right; } widthSize += this.getVerticalScrollbarWidth(); } let childWidth:number = widthSize - this.mListPadding.left - this.mListPadding.right; let didNotInitiallyFit:boolean = this.determineColumns(childWidth); let childHeight:number = 0; let childState:number = 0; this.mItemCount = this.mAdapter == null ? 0 : this.mAdapter.getCount(); const count:number = this.mItemCount; if (count > 0) { const child:View = this.obtainView(0, this.mIsScrap); let p:AbsListView.LayoutParams = <AbsListView.LayoutParams> child.getLayoutParams(); if (p == null) { p = <AbsListView.LayoutParams> this.generateDefaultLayoutParams(); child.setLayoutParams(p); } p.viewType = this.mAdapter.getItemViewType(0); p.forceAdd = true; let childHeightSpec:number = GridView.getChildMeasureSpec(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 0, p.height); let childWidthSpec:number = GridView.getChildMeasureSpec(View.MeasureSpec.makeMeasureSpec(this.mColumnWidth, View.MeasureSpec.EXACTLY), 0, p.width); child.measure(childWidthSpec, childHeightSpec); childHeight = child.getMeasuredHeight(); childState = GridView.combineMeasuredStates(childState, child.getMeasuredState()); if (this.mRecycler.shouldRecycleViewType(p.viewType)) { this.mRecycler.addScrapView(child, -1); } } if (heightMode == View.MeasureSpec.UNSPECIFIED) { heightSize = this.mListPadding.top + this.mListPadding.bottom + childHeight + this.getVerticalFadingEdgeLength() * 2; } if (heightMode == View.MeasureSpec.AT_MOST) { let ourSize:number = this.mListPadding.top + this.mListPadding.bottom; const numColumns:number = this.mNumColumns; for (let i:number = 0; i < count; i += numColumns) { ourSize += childHeight; if (i + numColumns < count) { ourSize += this.mVerticalSpacing; } if (ourSize >= heightSize) { ourSize = heightSize; break; } } heightSize = ourSize; } if (widthMode == View.MeasureSpec.AT_MOST && this.mRequestedNumColumns != GridView.AUTO_FIT) { let ourSize:number = (this.mRequestedNumColumns * this.mColumnWidth) + ((this.mRequestedNumColumns - 1) * this.mHorizontalSpacing) + this.mListPadding.left + this.mListPadding.right; if (ourSize > widthSize || didNotInitiallyFit) { widthSize |= GridView.MEASURED_STATE_TOO_SMALL; } } this.setMeasuredDimension(widthSize, heightSize); this.mWidthMeasureSpec = widthMeasureSpec; } protected layoutChildren():void { const blockLayoutRequests:boolean = this.mBlockLayoutRequests; if (!blockLayoutRequests) { this.mBlockLayoutRequests = true; } try { super.layoutChildren(); this.invalidate(); if (this.mAdapter == null) { this.resetList(); this.invokeOnItemScrollListener(); return; } const childrenTop:number = this.mListPadding.top; const childrenBottom:number = this.mBottom - this.mTop - this.mListPadding.bottom; let childCount:number = this.getChildCount(); let index:number; let delta:number = 0; let sel:View; let oldSel:View = null; let oldFirst:View = null; let newSel:View = null; // Remember stuff we will need down below switch(this.mLayoutMode) { case GridView.LAYOUT_SET_SELECTION: index = this.mNextSelectedPosition - this.mFirstPosition; if (index >= 0 && index < childCount) { newSel = this.getChildAt(index); } break; case GridView.LAYOUT_FORCE_TOP: case GridView.LAYOUT_FORCE_BOTTOM: case GridView.LAYOUT_SPECIFIC: case GridView.LAYOUT_SYNC: break; case GridView.LAYOUT_MOVE_SELECTION: if (this.mNextSelectedPosition >= 0) { delta = this.mNextSelectedPosition - this.mSelectedPosition; } break; default: // Remember the previously selected view index = this.mSelectedPosition - this.mFirstPosition; if (index >= 0 && index < childCount) { oldSel = this.getChildAt(index); } // Remember the previous first child oldFirst = this.getChildAt(0); } let dataChanged:boolean = this.mDataChanged; if (dataChanged) { this.handleDataChanged(); } // and calling it a day if (this.mItemCount == 0) { this.resetList(); this.invokeOnItemScrollListener(); return; } this.setSelectedPositionInt(this.mNextSelectedPosition); // Pull all children into the RecycleBin. // These views will be reused if possible const firstPosition:number = this.mFirstPosition; const recycleBin:AbsListView.RecycleBin = this.mRecycler; if (dataChanged) { for (let i:number = 0; i < childCount; i++) { recycleBin.addScrapView(this.getChildAt(i), firstPosition + i); } } else { recycleBin.fillActiveViews(childCount, firstPosition); } // Clear out old views //removeAllViewsInLayout(); this.detachAllViewsFromParent(); recycleBin.removeSkippedScrap(); switch(this.mLayoutMode) { case GridView.LAYOUT_SET_SELECTION: if (newSel != null) { sel = this.fillFromSelection(newSel.getTop(), childrenTop, childrenBottom); } else { sel = this.fillSelection(childrenTop, childrenBottom); } break; case GridView.LAYOUT_FORCE_TOP: this.mFirstPosition = 0; sel = this.fillFromTop(childrenTop); this.adjustViewsUpOrDown(); break; case GridView.LAYOUT_FORCE_BOTTOM: sel = this.fillUp(this.mItemCount - 1, childrenBottom); this.adjustViewsUpOrDown(); break; case GridView.LAYOUT_SPECIFIC: sel = this.fillSpecific(this.mSelectedPosition, this.mSpecificTop); break; case GridView.LAYOUT_SYNC: sel = this.fillSpecific(this.mSyncPosition, this.mSpecificTop); break; case GridView.LAYOUT_MOVE_SELECTION: // Move the selection relative to its old position sel = this.moveSelection(delta, childrenTop, childrenBottom); break; default: if (childCount == 0) { if (!this.mStackFromBottom) { this.setSelectedPositionInt(this.mAdapter == null || this.isInTouchMode() ? GridView.INVALID_POSITION : 0); sel = this.fillFromTop(childrenTop); } else { const last:number = this.mItemCount - 1; this.setSelectedPositionInt(this.mAdapter == null || this.isInTouchMode() ? GridView.INVALID_POSITION : last); sel = this.fillFromBottom(last, childrenBottom); } } else { if (this.mSelectedPosition >= 0 && this.mSelectedPosition < this.mItemCount) { sel = this.fillSpecific(this.mSelectedPosition, oldSel == null ? childrenTop : oldSel.getTop()); } else if (this.mFirstPosition < this.mItemCount) { sel = this.fillSpecific(this.mFirstPosition, oldFirst == null ? childrenTop : oldFirst.getTop()); } else { sel = this.fillSpecific(0, childrenTop); } } break; } // Flush any cached views that did not get reused above recycleBin.scrapActiveViews(); if (sel != null) { this.positionSelector(GridView.INVALID_POSITION, sel); this.mSelectedTop = sel.getTop(); } else if (this.mTouchMode > GridView.TOUCH_MODE_DOWN && this.mTouchMode < GridView.TOUCH_MODE_SCROLL) { let child:View = this.getChildAt(this.mMotionPosition - this.mFirstPosition); if (child != null) this.positionSelector(this.mMotionPosition, child); } else { this.mSelectedTop = 0; this.mSelectorRect.setEmpty(); } this.mLayoutMode = GridView.LAYOUT_NORMAL; this.mDataChanged = false; if (this.mPositionScrollAfterLayout != null) { this.post(this.mPositionScrollAfterLayout); this.mPositionScrollAfterLayout = null; } this.mNeedSync = false; this.setNextSelectedPositionInt(this.mSelectedPosition); this.updateScrollIndicators(); if (this.mItemCount > 0) { this.checkSelectionChanged(); } this.invokeOnItemScrollListener(); } finally { if (!blockLayoutRequests) { this.mBlockLayoutRequests = false; } } } /** * Obtain the view and add it to our list of children. The view can be made * fresh, converted from an unused view, or used as is if it was in the * recycle bin. * * @param position Logical position in the list * @param y Top or bottom edge of the view to add * @param flow if true, align top edge to y. If false, align bottom edge to * y. * @param childrenLeft Left edge where children should be positioned * @param selected Is this position selected? * @param where to add new item in the list * @return View that was added */ private makeAndAddView(position:number, y:number, flow:boolean, childrenLeft:number, selected:boolean, where:number):View { let child:View; if (!this.mDataChanged) { // Try to use an existing view for this position child = this.mRecycler.getActiveView(position); if (child != null) { // Found it -- we're using an existing child // This just needs to be positioned this.setupChild(child, position, y, flow, childrenLeft, selected, true, where); return child; } } // Make a new view for this position, or convert an unused view if // possible child = this.obtainView(position, this.mIsScrap); // This needs to be positioned and measured this.setupChild(child, position, y, flow, childrenLeft, selected, this.mIsScrap[0], where); return child; } /** * Add a view as a child and make sure it is measured (if necessary) and * positioned properly. * * @param child The view to add * @param position The position of the view * @param y The y position relative to which this view will be positioned * @param flow if true, align top edge to y. If false, align bottom edge * to y. * @param childrenLeft Left edge where children should be positioned * @param selected Is this position selected? * @param recycled Has this view been pulled from the recycle bin? If so it * does not need to be remeasured. * @param where Where to add the item in the list * */ private setupChild(child:View, position:number, y:number, flow:boolean, childrenLeft:number, selected:boolean, recycled:boolean, where:number):void { Trace.traceBegin(Trace.TRACE_TAG_VIEW, "setupGridItem"); let isSelected:boolean = selected && this.shouldShowSelector(); const updateChildSelected:boolean = isSelected != child.isSelected(); const mode:number = this.mTouchMode; const isPressed:boolean = mode > GridView.TOUCH_MODE_DOWN && mode < GridView.TOUCH_MODE_SCROLL && this.mMotionPosition == position; const updateChildPressed:boolean = isPressed != child.isPressed(); let needToMeasure:boolean = !recycled || updateChildSelected || child.isLayoutRequested(); // Respect layout params that are already in the view. Otherwise make // some up... let p:AbsListView.LayoutParams = <AbsListView.LayoutParams> child.getLayoutParams(); if (p == null) { p = <AbsListView.LayoutParams> this.generateDefaultLayoutParams(); } p.viewType = this.mAdapter.getItemViewType(position); if (recycled && !p.forceAdd) { this.attachViewToParent(child, where, p); } else { p.forceAdd = false; this.addViewInLayout(child, where, p, true); } if (updateChildSelected) { child.setSelected(isSelected); if (isSelected) { this.requestFocus(); } } if (updateChildPressed) { child.setPressed(isPressed); } if (this.mChoiceMode != GridView.CHOICE_MODE_NONE && this.mCheckStates != null) { if (child['setChecked']) { (<Checkable><any>child).setChecked(this.mCheckStates.get(position)); } else { child.setActivated(this.mCheckStates.get(position)); } } if (needToMeasure) { let childHeightSpec:number = ViewGroup.getChildMeasureSpec(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 0, p.height); let childWidthSpec:number = ViewGroup.getChildMeasureSpec(View.MeasureSpec.makeMeasureSpec(this.mColumnWidth, View.MeasureSpec.EXACTLY), 0, p.width); child.measure(childWidthSpec, childHeightSpec); } else { this.cleanupLayoutState(child); } const w:number = child.getMeasuredWidth(); const h:number = child.getMeasuredHeight(); let childLeft:number; const childTop:number = flow ? y : y - h; //const layoutDirection:number = this.getLayoutDirection(); const absoluteGravity:number = this.mGravity;//Gravity.getAbsoluteGravity(this.mGravity, layoutDirection); switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.LEFT: childLeft = childrenLeft; break; case Gravity.CENTER_HORIZONTAL: childLeft = childrenLeft + ((this.mColumnWidth - w) / 2); break; case Gravity.RIGHT: childLeft = childrenLeft + this.mColumnWidth - w; break; default: childLeft = childrenLeft; break; } if (needToMeasure) { const childRight:number = childLeft + w; const childBottom:number = childTop + h; child.layout(childLeft, childTop, childRight, childBottom); } else { child.offsetLeftAndRight(childLeft - child.getLeft()); child.offsetTopAndBottom(childTop - child.getTop()); } if (this.mCachingStarted) { child.setDrawingCacheEnabled(true); } if (recycled && ((<AbsListView.LayoutParams> child.getLayoutParams()).scrappedFromPosition) != position) { child.jumpDrawablesToCurrentState(); } Trace.traceEnd(Trace.TRACE_TAG_VIEW); } /** * Sets the currently selected item * * @param position Index (starting at 0) of the data item to be selected. * * If in touch mode, the item will not be selected but it will still be positioned * appropriately. */ setSelection(position:number):void { if (!this.isInTouchMode()) { this.setNextSelectedPositionInt(position); } else { this.mResurrectToPosition = position; } this.mLayoutMode = GridView.LAYOUT_SET_SELECTION; if (this.mPositionScroller != null) { this.mPositionScroller.stop(); } this.requestLayout(); } /** * Makes the item at the supplied position selected. * * @param position the position of the new selection */ setSelectionInt(position:number):void { let previousSelectedPosition:number = this.mNextSelectedPosition; if (this.mPositionScroller != null) { this.mPositionScroller.stop(); } this.setNextSelectedPositionInt(position); this.layoutChildren(); const next:number = this.mStackFromBottom ? this.mItemCount - 1 - this.mNextSelectedPosition : this.mNextSelectedPosition; const previous:number = this.mStackFromBottom ? this.mItemCount - 1 - previousSelectedPosition : previousSelectedPosition; const nextRow:number = next / this.mNumColumns; const previousRow:number = previous / this.mNumColumns; if (nextRow != previousRow) { this.awakenScrollBars(); } } onKeyDown(keyCode:number, event:KeyEvent):boolean { return this.commonKey(keyCode, 1, event); } onKeyMultiple(keyCode:number, repeatCount:number, event:KeyEvent):boolean { return this.commonKey(keyCode, repeatCount, event); } onKeyUp(keyCode:number, event:KeyEvent):boolean { return this.commonKey(keyCode, 1, event); } private commonKey(keyCode:number, count:number, event:KeyEvent):boolean { if (this.mAdapter == null) { return false; } if (this.mDataChanged) { this.layoutChildren(); } let handled:boolean = false; let action:number = event.getAction(); if (action != KeyEvent.ACTION_UP) { switch(keyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.arrowScroll(GridView.FOCUS_LEFT); } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.arrowScroll(GridView.FOCUS_RIGHT); } break; case KeyEvent.KEYCODE_DPAD_UP: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.arrowScroll(GridView.FOCUS_UP); } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { handled = this.resurrectSelectionIfNeeded() || this.fullScroll(GridView.FOCUS_UP); } break; case KeyEvent.KEYCODE_DPAD_DOWN: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.arrowScroll(GridView.FOCUS_DOWN); } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { handled = this.resurrectSelectionIfNeeded() || this.fullScroll(GridView.FOCUS_DOWN); } break; case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded(); if (!handled && event.getRepeatCount() == 0 && this.getChildCount() > 0) { this.keyPressed(); handled = true; } } break; case KeyEvent.KEYCODE_SPACE: //if (this.mPopup == null || !this.mPopup.isShowing()) { if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.pageScroll(GridView.FOCUS_DOWN); } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { handled = this.resurrectSelectionIfNeeded() || this.pageScroll(GridView.FOCUS_UP); } //} break; case KeyEvent.KEYCODE_PAGE_UP: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.pageScroll(GridView.FOCUS_UP); } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { handled = this.resurrectSelectionIfNeeded() || this.fullScroll(GridView.FOCUS_UP); } break; case KeyEvent.KEYCODE_PAGE_DOWN: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.pageScroll(GridView.FOCUS_DOWN); } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { handled = this.resurrectSelectionIfNeeded() || this.fullScroll(GridView.FOCUS_DOWN); } break; case KeyEvent.KEYCODE_MOVE_HOME: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.fullScroll(GridView.FOCUS_UP); } break; case KeyEvent.KEYCODE_MOVE_END: if (event.hasNoModifiers()) { handled = this.resurrectSelectionIfNeeded() || this.fullScroll(GridView.FOCUS_DOWN); } break; case KeyEvent.KEYCODE_TAB: // XXX Sometimes it is useful to be able to TAB through the items in // a GridView sequentially. Unfortunately this can create an // asymmetry in TAB navigation order unless the list selection // always reverts to the top or bottom when receiving TAB focus from // another widget. Leaving this behavior disabled for now but // perhaps it should be configurable (and more comprehensive). // if (false) { // if (event.hasNoModifiers()) { // handled = this.resurrectSelectionIfNeeded() || this.sequenceScroll(GridView.FOCUS_FORWARD); // } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) { // handled = this.resurrectSelectionIfNeeded() || this.sequenceScroll(GridView.FOCUS_BACKWARD); // } // } break; } } if (handled) { return true; } //if (this.sendToTextFilter(keyCode, count, event)) { // return true; //} switch(action) { case KeyEvent.ACTION_DOWN: return super.onKeyDown(keyCode, event); case KeyEvent.ACTION_UP: return super.onKeyUp(keyCode, event); //case KeyEvent.ACTION_MULTIPLE: // return super.onKeyMultiple(keyCode, count, event); default: return false; } } /** * Scrolls up or down by the number of items currently present on screen. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} * @return whether selection was moved */ pageScroll(direction:number):boolean { let nextPage:number = -1; if (direction == GridView.FOCUS_UP) { nextPage = Math.max(0, this.mSelectedPosition - this.getChildCount()); } else if (direction == GridView.FOCUS_DOWN) { nextPage = Math.min(this.mItemCount - 1, this.mSelectedPosition + this.getChildCount()); } if (nextPage >= 0) { this.setSelectionInt(nextPage); this.invokeOnItemScrollListener(); this.awakenScrollBars(); return true; } return false; } /** * Go to the last or first item if possible. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}. * * @return Whether selection was moved. */ fullScroll(direction:number):boolean { let moved:boolean = false; if (direction == GridView.FOCUS_UP) { this.mLayoutMode = GridView.LAYOUT_SET_SELECTION; this.setSelectionInt(0); this.invokeOnItemScrollListener(); moved = true; } else if (direction == GridView.FOCUS_DOWN) { this.mLayoutMode = GridView.LAYOUT_SET_SELECTION; this.setSelectionInt(this.mItemCount - 1); this.invokeOnItemScrollListener(); moved = true; } if (moved) { this.awakenScrollBars(); } return moved; } /** * Scrolls to the next or previous item, horizontally or vertically. * * @param direction either {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, * {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} * * @return whether selection was moved */ arrowScroll(direction:number):boolean { const selectedPosition:number = this.mSelectedPosition; const numColumns:number = this.mNumColumns; let startOfRowPos:number; let endOfRowPos:number; let moved:boolean = false; if (!this.mStackFromBottom) { startOfRowPos = Math.floor(selectedPosition / numColumns) * numColumns; endOfRowPos = Math.min(startOfRowPos + numColumns - 1, this.mItemCount - 1); } else { const invertedSelection:number = this.mItemCount - 1 - selectedPosition; endOfRowPos = this.mItemCount - 1 - (invertedSelection / numColumns) * numColumns; startOfRowPos = Math.max(0, endOfRowPos - numColumns + 1); } switch(direction) { case GridView.FOCUS_UP: if (startOfRowPos > 0) { this.mLayoutMode = GridView.LAYOUT_MOVE_SELECTION; this.setSelectionInt(Math.max(0, selectedPosition - numColumns)); moved = true; } break; case GridView.FOCUS_DOWN: if (endOfRowPos < this.mItemCount - 1) { this.mLayoutMode = GridView.LAYOUT_MOVE_SELECTION; this.setSelectionInt(Math.min(selectedPosition + numColumns, this.mItemCount - 1)); moved = true; } break; case GridView.FOCUS_LEFT: if (selectedPosition > startOfRowPos) { this.mLayoutMode = GridView.LAYOUT_MOVE_SELECTION; this.setSelectionInt(Math.max(0, selectedPosition - 1)); moved = true; } break; case GridView.FOCUS_RIGHT: if (selectedPosition < endOfRowPos) { this.mLayoutMode = GridView.LAYOUT_MOVE_SELECTION; this.setSelectionInt(Math.min(selectedPosition + 1, this.mItemCount - 1)); moved = true; } break; } if (moved) { this.playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); this.invokeOnItemScrollListener(); } if (moved) { this.awakenScrollBars(); } return moved; } /** * Goes to the next or previous item according to the order set by the * adapter. */ sequenceScroll(direction:number):boolean { let selectedPosition:number = this.mSelectedPosition; let numColumns:number = this.mNumColumns; let count:number = this.mItemCount; let startOfRow:number; let endOfRow:number; if (!this.mStackFromBottom) { startOfRow = (selectedPosition / numColumns) * numColumns; endOfRow = Math.min(startOfRow + numColumns - 1, count - 1); } else { let invertedSelection:number = count - 1 - selectedPosition; endOfRow = count - 1 - (invertedSelection / numColumns) * numColumns; startOfRow = Math.max(0, endOfRow - numColumns + 1); } let moved:boolean = false; let showScroll:boolean = false; switch(direction) { case GridView.FOCUS_FORWARD: if (selectedPosition < count - 1) { // Move to the next item. this.mLayoutMode = GridView.LAYOUT_MOVE_SELECTION; this.setSelectionInt(selectedPosition + 1); moved = true; // Show the scrollbar only if changing rows. showScroll = selectedPosition == endOfRow; } break; case GridView.FOCUS_BACKWARD: if (selectedPosition > 0) { // Move to the previous item. this.mLayoutMode = GridView.LAYOUT_MOVE_SELECTION; this.setSelectionInt(selectedPosition - 1); moved = true; // Show the scrollbar only if changing rows. showScroll = selectedPosition == startOfRow; } break; } if (moved) { this.playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); this.invokeOnItemScrollListener(); } if (showScroll) { this.awakenScrollBars(); } return moved; } protected onFocusChanged(gainFocus:boolean, direction:number, previouslyFocusedRect:Rect):void { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); let closestChildIndex:number = -1; if (gainFocus && previouslyFocusedRect != null) { previouslyFocusedRect.offset(this.mScrollX, this.mScrollY); // figure out which item should be selected based on previously // focused rect let otherRect:Rect = this.mTempRect; let minDistance:number = Integer.MAX_VALUE; const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { // only consider view's on appropriate edge of grid if (!this.isCandidateSelection(i, direction)) { continue; } const other:View = this.getChildAt(i); other.getDrawingRect(otherRect); this.offsetDescendantRectToMyCoords(other, otherRect); let distance:number = GridView.getDistance(previouslyFocusedRect, otherRect, direction); if (distance < minDistance) { minDistance = distance; closestChildIndex = i; } } } if (closestChildIndex >= 0) { this.setSelection(closestChildIndex + this.mFirstPosition); } else { this.requestLayout(); } } /** * Is childIndex a candidate for next focus given the direction the focus * change is coming from? * @param childIndex The index to check. * @param direction The direction, one of * {FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, FOCUS_BACKWARD} * @return Whether childIndex is a candidate. */ private isCandidateSelection(childIndex:number, direction:number):boolean { const count:number = this.getChildCount(); const invertedIndex:number = count - 1 - childIndex; let rowStart:number; let rowEnd:number; if (!this.mStackFromBottom) { rowStart = childIndex - (childIndex % this.mNumColumns); rowEnd = Math.max(rowStart + this.mNumColumns - 1, count); } else { rowEnd = count - 1 - (invertedIndex - (invertedIndex % this.mNumColumns)); rowStart = Math.max(0, rowEnd - this.mNumColumns + 1); } switch(direction) { case View.FOCUS_RIGHT: // edge return childIndex == rowStart; case View.FOCUS_DOWN: // coming from top; only valid if in top row return rowStart == 0; case View.FOCUS_LEFT: // coming from right, must be on right edge return childIndex == rowEnd; case View.FOCUS_UP: // coming from bottom, need to be in last row return rowEnd == count - 1; case View.FOCUS_FORWARD: // coming from top-left, need to be first in top row return childIndex == rowStart && rowStart == 0; case View.FOCUS_BACKWARD: // coming from bottom-right, need to be last in bottom row return childIndex == rowEnd && rowEnd == count - 1; default: throw Error(`new IllegalArgumentException("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, " + "FOCUS_FORWARD, FOCUS_BACKWARD}.")`); } } /** * Set the gravity for this grid. Gravity describes how the child views * are horizontally aligned. Defaults to Gravity.LEFT * * @param gravity the gravity to apply to this grid's children * * @attr ref android.R.styleable#GridView_gravity */ setGravity(gravity:number):void { if (this.mGravity != gravity) { this.mGravity = gravity; this.requestLayoutIfNecessary(); } } /** * Describes how the child views are horizontally aligned. Defaults to Gravity.LEFT * * @return the gravity that will be applied to this grid's children * * @attr ref android.R.styleable#GridView_gravity */ getGravity():number { return this.mGravity; } /** * Set the amount of horizontal (x) spacing to place between each item * in the grid. * * @param horizontalSpacing The amount of horizontal space between items, * in pixels. * * @attr ref android.R.styleable#GridView_horizontalSpacing */ setHorizontalSpacing(horizontalSpacing:number):void { if (horizontalSpacing != this.mRequestedHorizontalSpacing) { this.mRequestedHorizontalSpacing = horizontalSpacing; this.requestLayoutIfNecessary(); } } /** * Returns the amount of horizontal spacing currently used between each item in the grid. * * <p>This is only accurate for the current layout. If {@link #setHorizontalSpacing(int)} * has been called but layout is not yet complete, this method may return a stale value. * To get the horizontal spacing that was explicitly requested use * {@link #getRequestedHorizontalSpacing()}.</p> * * @return Current horizontal spacing between each item in pixels * * @see #setHorizontalSpacing(int) * @see #getRequestedHorizontalSpacing() * * @attr ref android.R.styleable#GridView_horizontalSpacing */ getHorizontalSpacing():number { return this.mHorizontalSpacing; } /** * Returns the requested amount of horizontal spacing between each item in the grid. * * <p>The value returned may have been supplied during inflation as part of a style, * the default GridView style, or by a call to {@link #setHorizontalSpacing(int)}. * If layout is not yet complete or if GridView calculated a different horizontal spacing * from what was requested, this may return a different value from * {@link #getHorizontalSpacing()}.</p> * * @return The currently requested horizontal spacing between items, in pixels * * @see #setHorizontalSpacing(int) * @see #getHorizontalSpacing() * * @attr ref android.R.styleable#GridView_horizontalSpacing */ getRequestedHorizontalSpacing():number { return this.mRequestedHorizontalSpacing; } /** * Set the amount of vertical (y) spacing to place between each item * in the grid. * * @param verticalSpacing The amount of vertical space between items, * in pixels. * * @see #getVerticalSpacing() * * @attr ref android.R.styleable#GridView_verticalSpacing */ setVerticalSpacing(verticalSpacing:number):void { if (verticalSpacing != this.mVerticalSpacing) { this.mVerticalSpacing = verticalSpacing; this.requestLayoutIfNecessary(); } } /** * Returns the amount of vertical spacing between each item in the grid. * * @return The vertical spacing between items in pixels * * @see #setVerticalSpacing(int) * * @attr ref android.R.styleable#GridView_verticalSpacing */ getVerticalSpacing():number { return this.mVerticalSpacing; } /** * Control how items are stretched to fill their space. * * @param stretchMode Either {@link #NO_STRETCH}, * {@link #STRETCH_SPACING}, {@link #STRETCH_SPACING_UNIFORM}, or {@link #STRETCH_COLUMN_WIDTH}. * * @attr ref android.R.styleable#GridView_stretchMode */ setStretchMode(stretchMode:number):void { if (stretchMode != this.mStretchMode) { this.mStretchMode = stretchMode; this.requestLayoutIfNecessary(); } } getStretchMode():number { return this.mStretchMode; } /** * Set the width of columns in the grid. * * @param columnWidth The column width, in pixels. * * @attr ref android.R.styleable#GridView_columnWidth */ setColumnWidth(columnWidth:number):void { if (columnWidth != this.mRequestedColumnWidth) { this.mRequestedColumnWidth = columnWidth; this.requestLayoutIfNecessary(); } } /** * Return the width of a column in the grid. * * <p>This may not be valid yet if a layout is pending.</p> * * @return The column width in pixels * * @see #setColumnWidth(int) * @see #getRequestedColumnWidth() * * @attr ref android.R.styleable#GridView_columnWidth */ getColumnWidth():number { return this.mColumnWidth; } /** * Return the requested width of a column in the grid. * * <p>This may not be the actual column width used. Use {@link #getColumnWidth()} * to retrieve the current real width of a column.</p> * * @return The requested column width in pixels * * @see #setColumnWidth(int) * @see #getColumnWidth() * * @attr ref android.R.styleable#GridView_columnWidth */ getRequestedColumnWidth():number { return this.mRequestedColumnWidth; } /** * Set the number of columns in the grid * * @param numColumns The desired number of columns. * * @attr ref android.R.styleable#GridView_numColumns */ setNumColumns(numColumns:number):void { if (numColumns != this.mRequestedNumColumns) { this.mRequestedNumColumns = numColumns; this.requestLayoutIfNecessary(); } } /** * Get the number of columns in the grid. * Returns {@link #AUTO_FIT} if the Grid has never been laid out. * * @attr ref android.R.styleable#GridView_numColumns * * @see #setNumColumns(int) */ getNumColumns():number { return this.mNumColumns; } /** * Make sure views are touching the top or bottom edge, as appropriate for * our gravity */ private adjustViewsUpOrDown():void { const childCount:number = this.getChildCount(); if (childCount > 0) { let delta:number; let child:View; if (!this.mStackFromBottom) { // Uh-oh -- we came up short. Slide all views up to make them // align with the top child = this.getChildAt(0); delta = child.getTop() - this.mListPadding.top; if (this.mFirstPosition != 0) { // It's OK to have some space above the first item if it is // part of the vertical spacing delta -= this.mVerticalSpacing; } if (delta < 0) { // We only are looking to see if we are too low, not too high delta = 0; } } else { // we are too high, slide all views down to align with bottom child = this.getChildAt(childCount - 1); delta = child.getBottom() - (this.getHeight() - this.mListPadding.bottom); if (this.mFirstPosition + childCount < this.mItemCount) { // It's OK to have some space below the last item if it is // part of the vertical spacing delta += this.mVerticalSpacing; } if (delta > 0) { // We only are looking to see if we are too high, not too low delta = 0; } } if (delta != 0) { this.offsetChildrenTopAndBottom(-delta); } } } protected computeVerticalScrollExtent():number { const count:number = this.getChildCount(); if (count > 0) { const numColumns:number = this.mNumColumns; const rowCount:number = (count + numColumns - 1) / numColumns; let extent:number = rowCount * 100; let view:View = this.getChildAt(0); const top:number = view.getTop(); let height:number = view.getHeight(); if (height > 0) { extent += (top * 100) / height; } view = this.getChildAt(count - 1); const bottom:number = view.getBottom(); height = view.getHeight(); if (height > 0) { extent -= ((bottom - this.getHeight()) * 100) / height; } return extent; } return 0; } protected computeVerticalScrollOffset():number { if (this.mFirstPosition >= 0 && this.getChildCount() > 0) { const view:View = this.getChildAt(0); const top:number = view.getTop(); let height:number = view.getHeight(); if (height > 0) { const numColumns:number = this.mNumColumns; const rowCount:number = (this.mItemCount + numColumns - 1) / numColumns; // In case of stackFromBottom the calculation of whichRow needs // to take into account that counting from the top the first row // might not be entirely filled. const oddItemsOnFirstRow:number = this.isStackFromBottom() ? ((rowCount * numColumns) - this.mItemCount) : 0; const whichRow:number = (this.mFirstPosition + oddItemsOnFirstRow) / numColumns; return Math.max(whichRow * 100 - (top * 100) / height + Math.floor((<number> this.mScrollY / this.getHeight() * rowCount * 100)), 0); } } return 0; } protected computeVerticalScrollRange():number { // TODO: Account for vertical spacing too const numColumns:number = this.mNumColumns; const rowCount:number = (this.mItemCount + numColumns - 1) / numColumns; let result:number = Math.max(rowCount * 100, 0); if (this.mScrollY != 0) { // Compensate for overscroll result += Math.abs(Math.floor((<number> this.mScrollY / this.getHeight() * rowCount * 100))); } return result; } } }
the_stack
import { faviconUrlSetting } from '../../components/common/HeadTags'; import { Comments } from '../../lib/collections/comments'; import { commentGetPageUrlFromDB, commentGetRSSUrl } from '../../lib/collections/comments/helpers'; import { Posts } from '../../lib/collections/posts/collection'; import { postGetPageUrl } from '../../lib/collections/posts/helpers'; import Users from '../../lib/collections/users/collection'; import { userGetProfileUrl } from '../../lib/collections/users/helpers'; import { forumTypeSetting } from '../../lib/instanceSettings'; import { legacyRouteAcronymSetting } from '../../lib/publicSettings'; import { onStartup } from '../../lib/executionEnvironment'; import { addStaticRoute } from '../vulcan-lib'; import type { ServerResponse } from 'http'; // Some legacy routes have an optional subreddit prefix, which is either // omitted, is /r/all, /r/discussion, or /r/lesswrong. The is followed by // /lw/postid possibly followed by a slug, comment ID, filter settings, or other // things, some of which is supported and some of which isn't. // // If a route has this optional prefix, use `subredditPrefixRoute` to represent // that part. It contains two optional parameters, constrained to be `r` and // a subreddit name, respectively (the subreddits being lesswrong, discussion, // and all). Since old-LW made all post IDs non-overlapping, we just ignore // which subreddit was specified. // // (In old LW, the set of possible subreddits may also have included user // account names, for things in users' draft folders. We don't support getting // old drafts via legacy routes; I'm not sure whether we support getting them // through other UI). const subredditPrefixRoute = "/:section(r)?/:subreddit(all|discussion|lesswrong)?"; async function findPostByLegacyId(legacyId: string) { const parsedId = parseInt(legacyId, 36); return await Posts.findOne({"legacyId": parsedId.toString()}); } async function findCommentByLegacyId(legacyId: string) { const parsedId = parseInt(legacyId, 36); return await Comments.findOne({"legacyId": parsedId.toString()}); } function makeRedirect(res: ServerResponse, destination: string) { res.writeHead(301, {"Location": destination}); res.end(); } async function findPostByLegacyAFId(legacyId: number) { return await Posts.findOne({"agentFoundationsId": legacyId}) } async function findCommentByLegacyAFId(legacyId: number) { return await Comments.findOne({"agentFoundationsId": legacyId}) } //Route for redirecting LessWrong legacy posts // addRoute({ name: 'lessWrongLegacy', path: 'lw/:id/:slug/:commentId', componentName: 'LegacyPostRedirect'}); // Route for old post links // Disabled because this is now properly in the routes table, as Components.LegacyPostRedirect. /*addStaticRoute(subredditPrefixRoute+`/${legacyRouteAcronym}/:id/:slug?`, async (params, req, res, next) => { if(params.id){ try { const post = await findPostByLegacyId(params.id); if (post) { return makeRedirect(res, postGetPageUrl(post)); } else { // don't redirect if we can't find a post for that link //eslint-disable-next-line no-console console.log('// Missing legacy post', params); res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } } catch (error) { //eslint-disable-next-line no-console console.error('// Legacy Post error', error, params) res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } } else { res.statusCode = 404 res.end("Please provide a URL"); } }); // Route for old comment links addStaticRoute(subredditPrefixRoute+`/${legacyRouteAcronym}/:id/:slug/:commentId`, async (params, req, res, next) => { if(params.id){ try { const post = await findPostByLegacyId(params.id); const comment = await findCommentByLegacyId(params.commentId); if (post && comment) { return makeRedirect(res, await commentGetPageUrlFromDB(comment)); } else if (post) { return makeRedirect(res, postGetPageUrl(post)); } else { // don't redirect if we can't find a post for that link res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } } catch (error) { //eslint-disable-next-line no-console console.log('// Legacy comment error', error, params) res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } } else { res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } });*/ // Route for old user links addStaticRoute('/user/:slug/:category?/:filter?', async (params, req, res, next) => { res.statusCode = 404 if(params.slug){ try { const user = await Users.findOne({$or: [{slug: params.slug}, {username: params.slug}]}); if (user) { return makeRedirect(res, userGetProfileUrl(user)); } else { //eslint-disable-next-line no-console console.log('// Missing legacy user', params); res.statusCode = 404 res.end(`No legacy user found with: ${params.slug}`); } } catch (error) { //eslint-disable-next-line no-console console.log('// Legacy User error', error, params); res.statusCode = 404 res.end(`No legacy user found with: ${params.slug}`); } } else { res.statusCode = 404 res.end(`No legacy user found with: ${params.slug}`); } }); // Route for old comment links addStaticRoute('/posts/:_id/:slug/:commentId', async (params, req, res, next) => { if(params.commentId){ try { const comment = await Comments.findOne({_id: params.commentId}); if (comment) { return makeRedirect(res, await commentGetPageUrlFromDB(comment)); } else { // don't redirect if we can't find a post for that link //eslint-disable-next-line no-console console.log('// Missing legacy comment', params); res.statusCode = 404 res.end(`No comment found with: ${params.commentId}`); } } catch (error) { //eslint-disable-next-line no-console console.error('// Legacy Comment error', error, params) res.statusCode = 404 res.end(`No comment found with: ${params.commentId}`); } } else { res.statusCode = 404 res.end("Please provide a URL"); } }); // Route for old images addStaticRoute('/static/imported/:year/:month/:day/:imageName', (params, req, res, next) => { if(params.imageName){ try { return makeRedirect(res, `https://raw.githubusercontent.com/tricycle/lesswrong/master/r2/r2/public/static/imported/${params.year}/${params.month}/${params.day}/${params.imageName}`); } catch (error) { //eslint-disable-next-line no-console console.error('// Legacy Comment error', error, params) res.statusCode = 404; res.end("Invalid image url") } } else { res.statusCode = 404; res.end("Please provide a URL") } }); // Legacy RSS Routes // Route for old comment rss feeds onStartup(() => { // Because the EA Forum was identical except for the change from /lw/ to /ea/ const legacyRouteAcronym = legacyRouteAcronymSetting.get() addStaticRoute(subredditPrefixRoute+`/${legacyRouteAcronym}/:id/:slug/:commentId/.rss`, async (params, req, res, next) => { if(params.id){ try { const post = await findPostByLegacyId(params.id); const comment = await findCommentByLegacyId(params.commentId); if (post && comment) { return makeRedirect(res, commentGetRSSUrl(comment)); } else if (post) { return makeRedirect(res, postGetPageUrl(post)); } else { // don't redirect if we can't find a post for that link res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } } catch (error) { //eslint-disable-next-line no-console console.log('// Legacy comment error', error, params) res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } } else { res.statusCode = 404 res.end(`No legacy post found with: id=${params.id} slug=${params.slug}`); } }); }); // Route for old general RSS (all posts) addStaticRoute('/.rss', (params, req, res, next) => { return makeRedirect(res, "/feed.xml"); }); // Route for old general RSS (all comments) addStaticRoute('comments/.rss', (params, req, res, next) => { return makeRedirect(res, '/feed.xml?type=comments'); }); addStaticRoute('/rss/comments.xml', (params, req, res, next) => { return makeRedirect(res, '/feed.xml?type=comments'); }); addStaticRoute('/daily', (params, req, res, next) => { return makeRedirect(res, '/allPosts'); }); // Route for old general RSS (all posts) addStaticRoute('/:section?/:subreddit?/:new?/.rss', (params, req, res, next) => { return makeRedirect(res, '/feed.xml'); }); addStaticRoute('/promoted', (params, req, res, next) => { return makeRedirect(res, '/allPosts?filter=curated&sortedBy=new&timeframe=allTime'); }); // Route for old promoted RSS (promoted posts) addStaticRoute('/promoted/.rss', (params, req, res, next) => { return makeRedirect(res, '/feed.xml?view=curated-rss'); }); // Route for old agent-foundations post and commentlinks addStaticRoute('/item', async (params, req, res, next) => { if(params.query.id){ const id = parseInt(params.query.id) try { const post = await findPostByLegacyAFId(id); if (post) { return makeRedirect(res, postGetPageUrl(post)); } else { const comment = await findCommentByLegacyAFId(id); if (comment) { return makeRedirect(res, await commentGetPageUrlFromDB(comment)) } else { // don't redirect if we can't find a post for that link //eslint-disable-next-line no-console console.log('// Missing legacy af item', params); res.statusCode = 404 res.end(`No af legacy item found with: id=${params.query.id}`); } } } catch (error) { //eslint-disable-next-line no-console console.error('// Legacy item error', error, params) res.statusCode = 404 res.end(`No legacy item found with: params=${params}`); } } else { res.statusCode = 404 res.end("Please provide a URL"); } }); // Secondary way of specifying favicon for browser or RSS readers that don't // support using a meta tag (the preferred approach). addStaticRoute('/favicon.ico', (params, req, res, next) => { return makeRedirect(res, faviconUrlSetting.get()); }); addStaticRoute('/featured', (params, req, res, next) => { return makeRedirect(res, '/allPosts?filter=curated&view=new&timeframe=allTime') }) addStaticRoute('/recentComments', (params, req, res, next) => { return makeRedirect(res, '/allComments'); }) if (forumTypeSetting.get() === "AlignmentForum") { addStaticRoute('/newcomments', (params, req, res, next) => { return makeRedirect(res, '/allComments'); }) addStaticRoute('/how-to-contribute', (params, req, res, next) => { return makeRedirect(res, '/posts/FoiiRDC3EhjHx7ayY/introducing-the-ai-alignment-forum-faq'); }) addStaticRoute('/submitted', (params, req, res, next) => { return makeRedirect(res, `/users/${params.query?.id}`); }) addStaticRoute('/threads', (params, req, res, next) => { return makeRedirect(res, `/users/${params.query?.id}`); }) addStaticRoute('/user', (params, req, res, next) => { return makeRedirect(res, `/users/${params.query?.id}`); }) addStaticRoute('/submit', (params, req, res, next) => { return makeRedirect(res, `/newPost`); }) addStaticRoute('/rss', (params, req, res, next) => { return makeRedirect(res, `/feed.xml`); }) addStaticRoute('/drafts', (params, req, res, next) => { return makeRedirect(res, `/account`); }) addStaticRoute('/saved', (params, req, res, next) => { return makeRedirect(res, `/account`); }) }
the_stack
import { Radio, Dropdown, DropdownToggle, Checkbox, Tooltip, TooltipPosition } from '@patternfly/react-core'; import * as React from 'react'; import { connect } from 'react-redux'; import { ThunkDispatch } from 'redux-thunk'; import { bindActionCreators } from 'redux'; import { KialiAppState } from '../../../store/Store'; import { GraphToolbarActions } from '../../../actions/GraphToolbarActions'; import { TrafficRate, isGrpcRate, isHttpRate, isTcpRate } from '../../../types/Graph'; import { KialiAppAction } from 'actions/KialiAppAction'; import * as _ from 'lodash'; import { trafficRatesSelector } from 'store/Selectors'; import { BoundingClientAwareComponent, PropertyType } from 'components/BoundingClientAwareComponent/BoundingClientAwareComponent'; import { KialiIcon } from 'config/KialiIcon'; import { containerStyle, infoStyle, itemStyleWithInfo, itemStyleWithoutInfo, menuStyle, menuEntryStyle } from 'styles/DropdownStyles'; type ReduxProps = { trafficRates: TrafficRate[]; setTrafficRates: (trafficRates: TrafficRate[]) => void; }; type GraphTrafficProps = ReduxProps & { disabled: boolean; }; type GraphTrafficState = { isOpen: boolean }; interface TrafficRateOptionType { id: string; disabled?: boolean; labelText: string; isChecked: boolean; onChange?: () => void; tooltip?: React.ReactNode; } const marginBottom = 20; class GraphTraffic extends React.PureComponent<GraphTrafficProps, GraphTrafficState> { constructor(props: GraphTrafficProps) { super(props); this.state = { isOpen: false }; } private onToggle = isOpen => { this.setState({ isOpen }); }; render() { return ( <Dropdown toggle={ <DropdownToggle id="graph-traffic-dropdown" onToggle={this.onToggle}> Traffic </DropdownToggle> } disabled={this.props.disabled} isOpen={this.state.isOpen} > {this.getPopoverContent()} </Dropdown> ); } private getPopoverContent() { const trafficRates = this.props.trafficRates; const trafficRateOptions: TrafficRateOptionType[] = [ { id: TrafficRate.GRPC_GROUP, labelText: _.startCase(TrafficRate.GRPC_GROUP), isChecked: trafficRates.includes(TrafficRate.GRPC_GROUP), tooltip: ( <div style={{ textAlign: 'left' }}> Displays active gRPC Edges for the time period, using the selected gRPC rate. To see idle gRPC Edges enable the "Idle Edges" Display menu option. Default: Requests. </div> ) }, { id: TrafficRate.HTTP_GROUP, labelText: _.startCase(TrafficRate.HTTP_GROUP), isChecked: trafficRates.includes(TrafficRate.HTTP_GROUP), tooltip: ( <div style={{ textAlign: 'left' }}> Displays active HTTP Edges for the time period, using the selected HTTP rate. To see idle HTTP Edges enable the "Idle Edges" Display menu option. Default: Requests. </div> ) }, { id: TrafficRate.TCP_GROUP, labelText: _.startCase(TrafficRate.TCP_GROUP), isChecked: trafficRates.includes(TrafficRate.TCP_GROUP), tooltip: ( <div style={{ textAlign: 'left' }}> Displays active TCP Edges for the time period, using the selected TCP rate. To see inactive TCP Edges enable the "Idle Edges" Display menu option. Default: Sent Bytes. </div> ) } ]; const grpcOptions: TrafficRateOptionType[] = [ { id: TrafficRate.GRPC_RECEIVED, labelText: 'Received Messages', isChecked: trafficRates.includes(TrafficRate.GRPC_RECEIVED), tooltip: ( <div style={{ textAlign: 'left' }}> Received (i.e. Response) message rate in messages-per-second (mps). Captures server streaming RPCs. </div> ) }, { id: TrafficRate.GRPC_REQUEST, labelText: 'Requests', isChecked: trafficRates.includes(TrafficRate.GRPC_REQUEST), tooltip: ( <div style={{ textAlign: 'left' }}> Request message rate in requests-per-second (rps). Captures unary RPC, with status codes. </div> ) }, { id: TrafficRate.GRPC_SENT, labelText: 'Sent Messages', isChecked: trafficRates.includes(TrafficRate.GRPC_SENT), tooltip: ( <div style={{ textAlign: 'left' }}> Sent (i.e. Request) message rate in messages-per-second (mps). Captures client streaming RPCs. </div> ) }, { id: TrafficRate.GRPC_TOTAL, labelText: 'Total Messages', isChecked: trafficRates.includes(TrafficRate.GRPC_TOTAL), tooltip: ( <div style={{ textAlign: 'left' }}> Combined (Sent + Received) message rate in messages-per-second (mps). Captures all streaming RPCs. </div> ) } ]; const httpOptions: TrafficRateOptionType[] = [ { id: TrafficRate.HTTP_REQUEST, labelText: 'Requests', isChecked: trafficRates.includes(TrafficRate.HTTP_REQUEST), tooltip: ( <div style={{ textAlign: 'left' }}> Request message rate in requests-per-second (rps). Captures status codes. </div> ) } ]; const tcpOptions: TrafficRateOptionType[] = [ { id: TrafficRate.TCP_RECEIVED, labelText: 'Received Bytes', isChecked: trafficRates.includes(TrafficRate.TCP_RECEIVED), tooltip: <div style={{ textAlign: 'left' }}>Received bytes rate in bytes-per-second (bps).</div> }, { id: TrafficRate.TCP_SENT, labelText: 'Sent Bytes', isChecked: trafficRates.includes(TrafficRate.TCP_SENT), tooltip: <div style={{ textAlign: 'left' }}>Sent bytes rate in bytes-per-second (bps).</div> }, { id: TrafficRate.TCP_TOTAL, labelText: 'Total Bytes', isChecked: trafficRates.includes(TrafficRate.TCP_TOTAL), tooltip: ( <div style={{ textAlign: 'left' }}>Combined (Sent + Received) byte rate in bytes-per-second (mps).</div> ) } ]; return ( <BoundingClientAwareComponent className={containerStyle} maxHeight={{ type: PropertyType.VIEWPORT_HEIGHT_MINUS_TOP, margin: marginBottom }} > <div id="graph-traffic-menu" className={menuStyle} style={{ width: '16.5em' }}> {trafficRateOptions.map((trafficRateOption: TrafficRateOptionType) => ( <div key={trafficRateOption.id} className={menuEntryStyle}> <label key={trafficRateOption.id} className={!!trafficRateOption.tooltip ? itemStyleWithInfo : itemStyleWithoutInfo} > <Checkbox id={trafficRateOption.id} name="trafficRateOptions" isChecked={trafficRateOption.isChecked} label={trafficRateOption.labelText} onChange={this.toggleTrafficRate} value={trafficRateOption.id} /> </label> {!!trafficRateOption.tooltip && ( <Tooltip key={`tooltip_${trafficRateOption.id}`} position={TooltipPosition.right} content={trafficRateOption.tooltip} > <KialiIcon.Info className={infoStyle} /> </Tooltip> )} {trafficRateOption.id === TrafficRate.GRPC_GROUP && grpcOptions.some(o => o.isChecked) && ( <div> {grpcOptions.map((grpcOption: TrafficRateOptionType) => ( <div key={grpcOption.id} className={menuEntryStyle}> <label key={grpcOption.id} className={!!grpcOption.tooltip ? itemStyleWithInfo : itemStyleWithoutInfo} style={{ paddingLeft: '35px' }} > <Radio id={grpcOption.id} style={{ paddingLeft: '5px' }} name="grpcOptions" isChecked={grpcOption.isChecked} label={grpcOption.labelText} onChange={this.toggleTrafficRateGrpc} value={grpcOption.id} /> </label> {!!grpcOption.tooltip && ( <Tooltip key={`tooltip_${grpcOption.id}`} position={TooltipPosition.right} content={grpcOption.tooltip} > <KialiIcon.Info className={infoStyle} /> </Tooltip> )} </div> ))} </div> )} {trafficRateOption.id === TrafficRate.HTTP_GROUP && httpOptions.some(o => o.isChecked) && ( <div> {httpOptions.map((httpOption: TrafficRateOptionType) => ( <div key={httpOption.id} className={menuEntryStyle}> <label key={httpOption.id} className={!!httpOption.tooltip ? itemStyleWithInfo : itemStyleWithoutInfo} style={{ paddingLeft: '35px' }} > <Radio id={httpOption.id} style={{ paddingLeft: '5px' }} name="httpOptions" isChecked={httpOption.isChecked} label={httpOption.labelText} onChange={this.toggleTrafficRateHttp} value={httpOption.id} /> </label> {!!httpOption.tooltip && ( <Tooltip key={`tooltip_${httpOption.id}`} position={TooltipPosition.right} content={httpOption.tooltip} > <KialiIcon.Info className={infoStyle} /> </Tooltip> )} </div> ))} </div> )} {trafficRateOption.id === TrafficRate.TCP_GROUP && tcpOptions.some(o => o.isChecked) && ( <div> {tcpOptions.map((tcpOption: TrafficRateOptionType) => ( <div key={tcpOption.id} className={menuEntryStyle}> <label key={tcpOption.id} className={!!tcpOption.tooltip ? itemStyleWithInfo : itemStyleWithoutInfo} style={{ paddingLeft: '35px' }} > <Radio id={tcpOption.id} style={{ paddingLeft: '5px' }} name="tcpOptions" isChecked={tcpOption.isChecked} label={tcpOption.labelText} onChange={this.toggleTrafficRateTcp} value={tcpOption.id} /> </label> {!!tcpOption.tooltip && ( <Tooltip key={`tooltip_${tcpOption.id}`} position={TooltipPosition.right} content={tcpOption.tooltip} > <KialiIcon.Info className={infoStyle} /> </Tooltip> )} </div> ))} </div> )} </div> ))} </div> </BoundingClientAwareComponent> ); } private toggleTrafficRate = (_, event) => { const rate = event.target.value as TrafficRate; if (this.props.trafficRates.includes(rate)) { let newRates; switch (rate) { case TrafficRate.GRPC_GROUP: newRates = this.props.trafficRates.filter(r => !isGrpcRate(r)); break; case TrafficRate.HTTP_GROUP: newRates = this.props.trafficRates.filter(r => !isHttpRate(r)); break; case TrafficRate.TCP_GROUP: newRates = this.props.trafficRates.filter(r => !isTcpRate(r)); break; default: newRates = this.props.trafficRates.filter(r => r !== rate); } this.props.setTrafficRates(newRates); } else { switch (rate) { case TrafficRate.GRPC_GROUP: this.props.setTrafficRates([...this.props.trafficRates, rate, TrafficRate.GRPC_REQUEST]); break; case TrafficRate.HTTP_GROUP: this.props.setTrafficRates([...this.props.trafficRates, rate, TrafficRate.HTTP_REQUEST]); break; case TrafficRate.TCP_GROUP: this.props.setTrafficRates([...this.props.trafficRates, rate, TrafficRate.TCP_SENT]); break; default: this.props.setTrafficRates([...this.props.trafficRates, rate]); } } }; private toggleTrafficRateGrpc = (_, event) => { const rate = event.target.value as TrafficRate; const newRates = this.props.trafficRates.filter(r => !isGrpcRate(r)); this.props.setTrafficRates([...newRates, TrafficRate.GRPC_GROUP, rate]); }; private toggleTrafficRateHttp = (_, event) => { const rate = event.target.value as TrafficRate; const newRates = this.props.trafficRates.filter(r => !isHttpRate(r)); this.props.setTrafficRates([...newRates, TrafficRate.HTTP_GROUP, rate]); }; private toggleTrafficRateTcp = (_, event) => { const rate = event.target.value as TrafficRate; const newRates = this.props.trafficRates.filter(r => !isTcpRate(r)); this.props.setTrafficRates([...newRates, TrafficRate.TCP_GROUP, rate]); }; } // Allow Redux to map sections of our global app state to our props const mapStateToProps = (state: KialiAppState) => ({ trafficRates: trafficRatesSelector(state) }); // Map our actions to Redux const mapDispatchToProps = (dispatch: ThunkDispatch<KialiAppState, void, KialiAppAction>) => { return { setTrafficRates: bindActionCreators(GraphToolbarActions.setTrafficRates, dispatch) }; }; // hook up to Redux for our State to be mapped to props const GraphTrafficContainer = connect(mapStateToProps, mapDispatchToProps)(GraphTraffic); export default GraphTrafficContainer;
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A Cloud Identity resource representing a Group. * * To get more information about Group, see: * * * [API documentation](https://cloud.google.com/identity/docs/reference/rest/v1beta1/groups) * * How-to Guides * * [Official Documentation](https://cloud.google.com/identity/docs/how-to/setup) * * > **Warning:** If you are using User ADCs (Application Default Credentials) with this resource, * you must specify a `billingProject` and set `userProjectOverride` to true * in the provider configuration. Otherwise the Cloud Identity API will return a 403 error. * Your account must have the `serviceusage.services.use` permission on the * `billingProject` you defined. * * ## Example Usage * ### Cloud Identity Groups Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const cloudIdentityGroupBasic = new gcp.cloudidentity.Group("cloud_identity_group_basic", { * displayName: "my-identity-group", * groupKey: { * id: "my-identity-group@example.com", * }, * initialGroupConfig: "WITH_INITIAL_OWNER", * labels: { * "cloudidentity.googleapis.com/groups.discussion_forum": "", * }, * parent: "customers/A01b123xz", * }); * ``` * * ## Import * * Group can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:cloudidentity/group:Group default {{name}} * ``` */ export class Group extends pulumi.CustomResource { /** * Get an existing Group 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?: GroupState, opts?: pulumi.CustomResourceOptions): Group { return new Group(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:cloudidentity/group:Group'; /** * Returns true if the given object is an instance of Group. 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 Group { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Group.__pulumiType; } /** * The time when the Group was created. */ public /*out*/ readonly createTime!: pulumi.Output<string>; /** * An extended description to help users determine the purpose of a Group. * Must not be longer than 4,096 characters. */ public readonly description!: pulumi.Output<string | undefined>; /** * The display name of the Group. */ public readonly displayName!: pulumi.Output<string | undefined>; /** * EntityKey of the Group. * Structure is documented below. */ public readonly groupKey!: pulumi.Output<outputs.cloudidentity.GroupGroupKey>; /** * The initial configuration options for creating a Group. * See the * [API reference](https://cloud.google.com/identity/docs/reference/rest/v1beta1/groups/create#initialgroupconfig) * for possible values. * Default value is `EMPTY`. * Possible values are `INITIAL_GROUP_CONFIG_UNSPECIFIED`, `WITH_INITIAL_OWNER`, and `EMPTY`. */ public readonly initialGroupConfig!: pulumi.Output<string | undefined>; /** * The labels that apply to the Group. * Must not contain more than one entry. Must contain the entry * 'cloudidentity.googleapis.com/groups.discussion_forum': '' if the Group is a Google Group or * 'system/groups/external': '' if the Group is an external-identity-mapped group. */ public readonly labels!: pulumi.Output<{[key: string]: string}>; /** * Resource name of the Group in the format: groups/{group_id}, where group_id is the unique ID assigned to the Group. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * The resource name of the entity under which this Group resides in the * Cloud Identity resource hierarchy. * Must be of the form identitysources/{identity_source_id} for external-identity-mapped * groups or customers/{customer_id} for Google Groups. */ public readonly parent!: pulumi.Output<string>; /** * The time when the Group was last updated. */ public /*out*/ readonly updateTime!: pulumi.Output<string>; /** * Create a Group 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: GroupArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: GroupArgs | GroupState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as GroupState | undefined; inputs["createTime"] = state ? state.createTime : undefined; inputs["description"] = state ? state.description : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["groupKey"] = state ? state.groupKey : undefined; inputs["initialGroupConfig"] = state ? state.initialGroupConfig : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["name"] = state ? state.name : undefined; inputs["parent"] = state ? state.parent : undefined; inputs["updateTime"] = state ? state.updateTime : undefined; } else { const args = argsOrState as GroupArgs | undefined; if ((!args || args.groupKey === undefined) && !opts.urn) { throw new Error("Missing required property 'groupKey'"); } if ((!args || args.labels === undefined) && !opts.urn) { throw new Error("Missing required property 'labels'"); } if ((!args || args.parent === undefined) && !opts.urn) { throw new Error("Missing required property 'parent'"); } inputs["description"] = args ? args.description : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["groupKey"] = args ? args.groupKey : undefined; inputs["initialGroupConfig"] = args ? args.initialGroupConfig : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["parent"] = args ? args.parent : undefined; inputs["createTime"] = undefined /*out*/; inputs["name"] = undefined /*out*/; inputs["updateTime"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Group.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Group resources. */ export interface GroupState { /** * The time when the Group was created. */ createTime?: pulumi.Input<string>; /** * An extended description to help users determine the purpose of a Group. * Must not be longer than 4,096 characters. */ description?: pulumi.Input<string>; /** * The display name of the Group. */ displayName?: pulumi.Input<string>; /** * EntityKey of the Group. * Structure is documented below. */ groupKey?: pulumi.Input<inputs.cloudidentity.GroupGroupKey>; /** * The initial configuration options for creating a Group. * See the * [API reference](https://cloud.google.com/identity/docs/reference/rest/v1beta1/groups/create#initialgroupconfig) * for possible values. * Default value is `EMPTY`. * Possible values are `INITIAL_GROUP_CONFIG_UNSPECIFIED`, `WITH_INITIAL_OWNER`, and `EMPTY`. */ initialGroupConfig?: pulumi.Input<string>; /** * The labels that apply to the Group. * Must not contain more than one entry. Must contain the entry * 'cloudidentity.googleapis.com/groups.discussion_forum': '' if the Group is a Google Group or * 'system/groups/external': '' if the Group is an external-identity-mapped group. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Resource name of the Group in the format: groups/{group_id}, where group_id is the unique ID assigned to the Group. */ name?: pulumi.Input<string>; /** * The resource name of the entity under which this Group resides in the * Cloud Identity resource hierarchy. * Must be of the form identitysources/{identity_source_id} for external-identity-mapped * groups or customers/{customer_id} for Google Groups. */ parent?: pulumi.Input<string>; /** * The time when the Group was last updated. */ updateTime?: pulumi.Input<string>; } /** * The set of arguments for constructing a Group resource. */ export interface GroupArgs { /** * An extended description to help users determine the purpose of a Group. * Must not be longer than 4,096 characters. */ description?: pulumi.Input<string>; /** * The display name of the Group. */ displayName?: pulumi.Input<string>; /** * EntityKey of the Group. * Structure is documented below. */ groupKey: pulumi.Input<inputs.cloudidentity.GroupGroupKey>; /** * The initial configuration options for creating a Group. * See the * [API reference](https://cloud.google.com/identity/docs/reference/rest/v1beta1/groups/create#initialgroupconfig) * for possible values. * Default value is `EMPTY`. * Possible values are `INITIAL_GROUP_CONFIG_UNSPECIFIED`, `WITH_INITIAL_OWNER`, and `EMPTY`. */ initialGroupConfig?: pulumi.Input<string>; /** * The labels that apply to the Group. * Must not contain more than one entry. Must contain the entry * 'cloudidentity.googleapis.com/groups.discussion_forum': '' if the Group is a Google Group or * 'system/groups/external': '' if the Group is an external-identity-mapped group. */ labels: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The resource name of the entity under which this Group resides in the * Cloud Identity resource hierarchy. * Must be of the form identitysources/{identity_source_id} for external-identity-mapped * groups or customers/{customer_id} for Google Groups. */ parent: pulumi.Input<string>; }
the_stack
import { PDFPage, PDFFont, PDFDocument, PDFImage, PDFEmbeddedPage, rgb, degrees, setCharacterSpacing, TransformationMatrix, } from 'pdf-lib'; import { ToBufferOptions } from 'bwip-js'; import bwipjsNode from 'bwip-js/dist/node-bwipjs'; import bwipjsBrowser from 'bwip-js/dist/bwip-js'; import { getB64BasePdf, b64toUint8Array, validateBarcodeInput, Schema, TextSchema, isTextSchema, ImageSchema, isImageSchema, BarcodeSchema, isBarcodeSchema, Font, BasePdf, BarCodeType, Alignment, DEFAULT_FONT_SIZE, DEFAULT_ALIGNMENT, DEFAULT_LINE_HEIGHT, DEFAULT_CHARACTER_SPACING, DEFAULT_FONT_COLOR, } from '@pdfme/common'; export interface InputImageCache { [key: string]: PDFImage | undefined; } const barCodeType2Bcid = (type: BarCodeType) => (type === 'nw7' ? 'rationalizedCodabar' : type); export const createBarCode = async (arg: { type: BarCodeType; input: string; width: number; height: number; backgroundColor?: string; }): Promise<Buffer> => { const { type, input, width, height, backgroundColor } = arg; const bcid = barCodeType2Bcid(type); const includetext = true; const scale = 5; const bwipjsArg: ToBufferOptions = { bcid, text: input, width, height, scale, includetext }; if (backgroundColor) { bwipjsArg.backgroundcolor = backgroundColor; } let res: Buffer; if (typeof window !== 'undefined') { const canvas = document.createElement('canvas'); bwipjsBrowser.toCanvas(canvas, bwipjsArg); const dataUrl = canvas.toDataURL('image/png'); res = b64toUint8Array(dataUrl).buffer as Buffer; } else { res = await bwipjsNode.toBuffer(bwipjsArg); } return res; }; type EmbedPdfBox = { mediaBox: { x: number; y: number; width: number; height: number }; bleedBox: { x: number; y: number; width: number; height: number }; trimBox: { x: number; y: number; width: number; height: number }; }; export const embedAndGetFontObj = async (arg: { pdfDoc: PDFDocument; font: Font }) => { const { pdfDoc, font } = arg; const fontValues = await Promise.all( Object.values(font).map((v) => pdfDoc.embedFont(v.data, { subset: typeof v.subset === 'undefined' ? true : v.subset, }) ) ); return Object.keys(font).reduce( (acc, cur, i) => Object.assign(acc, { [cur]: fontValues[i] }), {} as { [key: string]: PDFFont } ); }; export const getEmbeddedPagesAndEmbedPdfBoxes = async (arg: { pdfDoc: PDFDocument; basePdf: BasePdf; }) => { const { pdfDoc, basePdf } = arg; let embeddedPages: PDFEmbeddedPage[] = []; let embedPdfBoxes: EmbedPdfBox[] = []; const willLoadPdf = typeof basePdf === 'string' ? await getB64BasePdf(basePdf) : basePdf; const embedPdf = await PDFDocument.load(willLoadPdf); const embedPdfPages = embedPdf.getPages(); embedPdfBoxes = embedPdfPages.map((p) => ({ mediaBox: p.getMediaBox(), bleedBox: p.getBleedBox(), trimBox: p.getTrimBox(), })); const boundingBoxes = embedPdfPages.map((p) => { const { x, y, width, height } = p.getMediaBox(); return { left: x, bottom: y, right: width, top: height + y }; }); const transformationMatrices = embedPdfPages.map( () => [1, 0, 0, 1, 0, 0] as TransformationMatrix ); embeddedPages = await pdfDoc.embedPages(embedPdfPages, boundingBoxes, transformationMatrices); return { embeddedPages, embedPdfBoxes }; }; const mm2pt = (mm: number): number => { // https://www.ddc.co.jp/words/archives/20090701114500.html const ptRatio = 2.8346; return parseFloat(String(mm)) * ptRatio; }; const getSchemaSizeAndRotate = (schema: Schema) => { const width = mm2pt(schema.width); const height = mm2pt(schema.height); const rotate = degrees(schema.rotate ? schema.rotate : 0); return { width, height, rotate }; }; const hex2rgb = (hex: string) => { if (hex.slice(0, 1) === '#') hex = hex.slice(1); if (hex.length === 3) hex = hex.slice(0, 1) + hex.slice(0, 1) + hex.slice(1, 2) + hex.slice(1, 2) + hex.slice(2, 3) + hex.slice(2, 3); return [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map((str) => parseInt(str, 16)); }; const hex2RgbColor = (hexString: string | undefined) => { if (hexString) { const [r, g, b] = hex2rgb(hexString); return rgb(r / 255, g / 255, b / 255); } // eslint-disable-next-line no-undefined return undefined; }; const getFontProp = (schema: TextSchema) => { const size = schema.fontSize ?? DEFAULT_FONT_SIZE; const color = hex2RgbColor(schema.fontColor ?? DEFAULT_FONT_COLOR); const alignment = schema.alignment ?? DEFAULT_ALIGNMENT; const lineHeight = schema.lineHeight ?? DEFAULT_LINE_HEIGHT; const characterSpacing = schema.characterSpacing ?? DEFAULT_CHARACTER_SPACING; return { size, color, alignment, lineHeight, characterSpacing }; }; const calcX = (x: number, alignment: Alignment, boxWidth: number, textWidth: number) => { let addition = 0; if (alignment === 'center') { addition = (boxWidth - textWidth) / 2; } else if (alignment === 'right') { addition = boxWidth - textWidth; } return mm2pt(x) + addition; }; const calcY = (y: number, height: number, itemHeight: number) => height - mm2pt(y) - itemHeight; const drawBackgroundColor = (arg: { templateSchema: TextSchema; page: PDFPage; pageHeight: number; }) => { const { templateSchema, page, pageHeight } = arg; if (!templateSchema.backgroundColor) return; const { width, height } = getSchemaSizeAndRotate(templateSchema); const color = hex2RgbColor(templateSchema.backgroundColor); page.drawRectangle({ x: calcX(templateSchema.position.x, 'left', width, width), y: calcY(templateSchema.position.y, pageHeight, height), width, height, color, }); }; type IsOverEval = (testString: string) => boolean; /** * Incrementally check the current line for it's real length * and return the position where it exceeds the box width. * * return `null` to indicate if inputLine is shorter as the available bbox */ const getOverPosition = (inputLine: string, isOverEval: IsOverEval) => { for (let i = 0; i <= inputLine.length; i += 1) { if (isOverEval(inputLine.substr(0, i))) { return i; } } return null; }; /** * Get position of the split. Split the exceeding line at * the last whitespace over it exceeds the bounding box width. */ const getSplitPosition = (inputLine: string, isOverEval: IsOverEval) => { const overPos = getOverPosition(inputLine, isOverEval); /** * if input line is shorter as the available space. We split at the end of the line */ if (overPos === null) return inputLine.length; let overPosTmp = overPos; while (inputLine[overPosTmp] !== ' ' && overPosTmp >= 0) overPosTmp -= 1; /** * for very long lines with no whitespace use the original overPos and * split one char over so we do not overfill the box */ return overPosTmp > 0 ? overPosTmp : overPos - 1; }; /** * recursively split the line at getSplitPosition. * If there is some leftover, split the rest again in the same manner. */ const getSplittedLines = (inputLine: string, isOverEval: IsOverEval): string[] => { const splitPos = getSplitPosition(inputLine, isOverEval); const splittedLine = inputLine.substr(0, splitPos); const rest = inputLine.slice(splitPos).trimLeft(); /** * end recursion if there is no rest, return single splitted line in an array * so we can join them over the recursion */ if (rest.length === 0) { return [splittedLine]; } return [splittedLine, ...getSplittedLines(rest, isOverEval)]; }; interface TextSchemaSetting { fontObj: { [key: string]: PDFFont; }; fallbackFontName: string; splitThreshold: number; } const drawInputByTextSchema = (arg: { input: string; templateSchema: TextSchema; pdfDoc: PDFDocument; page: PDFPage; pageHeight: number; textSchemaSetting: TextSchemaSetting; }) => { const { input, templateSchema, page, pageHeight, textSchemaSetting } = arg; const { fontObj, fallbackFontName, splitThreshold } = textSchemaSetting; const fontValue = fontObj[templateSchema.fontName ? templateSchema.fontName : fallbackFontName]; drawBackgroundColor({ templateSchema, page, pageHeight }); const { width, rotate } = getSchemaSizeAndRotate(templateSchema); const { size, color, alignment, lineHeight, characterSpacing } = getFontProp(templateSchema); page.pushOperators(setCharacterSpacing(characterSpacing)); let beforeLineOver = 0; input.split(/\r|\n|\r\n/g).forEach((inputLine, inputLineIndex) => { const isOverEval = (testString: string) => { const testStringWidth = fontValue.widthOfTextAtSize(testString, size) + (testString.length - 1) * characterSpacing; /** * split if the difference is less then two pixel * (found out / tested this threshold heuristically, most probably widthOfTextAtSize is unprecise) **/ return width - testStringWidth <= splitThreshold; }; const splitedLines = getSplittedLines(inputLine, isOverEval); const drawLine = (splitedLine: string, splitedLineIndex: number) => { const textWidth = fontValue.widthOfTextAtSize(splitedLine, size) + (splitedLine.length - 1) * characterSpacing; page.drawText(splitedLine, { x: calcX(templateSchema.position.x, alignment, width, textWidth), y: calcY(templateSchema.position.y, pageHeight, size) - lineHeight * size * (inputLineIndex + splitedLineIndex + beforeLineOver) - (lineHeight === 0 ? 0 : ((lineHeight - 1) * size) / 2), rotate, size, color, lineHeight: lineHeight * size, maxWidth: width, font: fontValue, wordBreaks: [''], }); if (splitedLines.length === splitedLineIndex + 1) beforeLineOver += splitedLineIndex; }; splitedLines.forEach(drawLine); }); }; const getCacheKey = (templateSchema: Schema, input: string) => `${templateSchema.type}${input}`; const drawInputByImageSchema = async (arg: { input: string; templateSchema: ImageSchema; pageHeight: number; pdfDoc: PDFDocument; page: PDFPage; inputImageCache: InputImageCache; }) => { const { input, templateSchema, pageHeight, pdfDoc, page, inputImageCache } = arg; const { width, height, rotate } = getSchemaSizeAndRotate(templateSchema); const opt = { x: calcX(templateSchema.position.x, 'left', width, width), y: calcY(templateSchema.position.y, pageHeight, height), rotate, width, height, }; const inputImageCacheKey = getCacheKey(templateSchema, input); let image = inputImageCache[inputImageCacheKey]; if (!image) { const isPng = input.startsWith('data:image/png;'); image = await (isPng ? pdfDoc.embedPng(input) : pdfDoc.embedJpg(input)); } inputImageCache[inputImageCacheKey] = image; page.drawImage(image, opt); }; const drawInputByBarcodeSchema = async (arg: { input: string; templateSchema: BarcodeSchema; pageHeight: number; pdfDoc: PDFDocument; page: PDFPage; inputImageCache: InputImageCache; }) => { const { input, templateSchema, pageHeight, pdfDoc, page, inputImageCache } = arg; if (!validateBarcodeInput(templateSchema.type as BarCodeType, input)) return; const { width, height, rotate } = getSchemaSizeAndRotate(templateSchema); const opt = { x: calcX(templateSchema.position.x, 'left', width, width), y: calcY(templateSchema.position.y, pageHeight, height), rotate, width, height, }; const inputBarcodeCacheKey = getCacheKey(templateSchema, input); let image = inputImageCache[inputBarcodeCacheKey]; if (!image) { const imageBuf = await createBarCode( Object.assign(templateSchema, { type: templateSchema.type as BarCodeType, input }) ); image = await pdfDoc.embedPng(imageBuf); } inputImageCache[inputBarcodeCacheKey] = image; page.drawImage(image, opt); }; export const drawInputByTemplateSchema = async (arg: { input: string; templateSchema: Schema; pdfDoc: PDFDocument; page: PDFPage; pageHeight: number; textSchemaSetting: TextSchemaSetting; inputImageCache: InputImageCache; }) => { if (!arg.input || !arg.templateSchema) return; if (isTextSchema(arg.templateSchema)) { const templateSchema = arg.templateSchema as TextSchema; drawInputByTextSchema({ ...arg, templateSchema }); } else if (isImageSchema(arg.templateSchema)) { const templateSchema = arg.templateSchema as ImageSchema; await drawInputByImageSchema({ ...arg, templateSchema }); } else if (isBarcodeSchema(arg.templateSchema)) { const templateSchema = arg.templateSchema as BarcodeSchema; await drawInputByBarcodeSchema({ ...arg, templateSchema }); } }; export const drawEmbeddedPage = (arg: { page: PDFPage; embeddedPage: PDFEmbeddedPage; embedPdfBox: EmbedPdfBox; }) => { const { page, embeddedPage, embedPdfBox } = arg; page.drawPage(embeddedPage); const { mediaBox: mb, bleedBox: bb, trimBox: tb } = embedPdfBox; page.setMediaBox(mb.x, mb.y, mb.width, mb.height); page.setBleedBox(bb.x, bb.y, bb.width, bb.height); page.setTrimBox(tb.x, tb.y, tb.width, tb.height); };
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [cloud9](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscloud9.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Cloud9 extends PolicyStatement { public servicePrefix = 'cloud9'; /** * Statement provider for service [cloud9](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscloud9.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to start the Amazon EC2 instance that your AWS Cloud9 IDE connects to * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toActivateEC2Remote() { return this.to('ActivateEC2Remote'); } /** * Grants permission to create an AWS Cloud9 development environment, launches an Amazon Elastic Compute Cloud (Amazon EC2) instance, and then hosts the environment on the instance * * Access Level: Write * * Possible conditions: * - .ifEnvironmentName() * - .ifInstanceType() * - .ifSubnetId() * - .ifUserArn() * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:DescribeSubnets * - ec2:DescribeVpcs * - iam:CreateServiceLinkedRole * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_CreateEnvironmentEC2.html */ public toCreateEnvironmentEC2() { return this.to('CreateEnvironmentEC2'); } /** * Grants permission to add an environment member to an AWS Cloud9 development environment * * Access Level: Write * * Possible conditions: * - .ifUserArn() * - .ifEnvironmentId() * - .ifPermissions() * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_CreateEnvironmentMembership.html */ public toCreateEnvironmentMembership() { return this.to('CreateEnvironmentMembership'); } /** * Grants permission to create an AWS Cloud9 SSH development environment * * Access Level: Write * * Possible conditions: * - .ifEnvironmentName() * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toCreateEnvironmentSSH() { return this.to('CreateEnvironmentSSH'); } /** * Grants permission to create an authentication token that allows a connection between the AWS Cloud9 IDE and the user's environment * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toCreateEnvironmentToken() { return this.to('CreateEnvironmentToken'); } /** * Grants permission to delete an AWS Cloud9 development environment. If the environment is hosted on an Amazon Elastic Compute Cloud (Amazon EC2) instance, also terminates the instance * * Access Level: Write * * Dependent actions: * - iam:CreateServiceLinkedRole * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_DeleteEnvironment.html */ public toDeleteEnvironment() { return this.to('DeleteEnvironment'); } /** * Grants permission to delete an environment member from an AWS Cloud9 development environment * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_DeleteEnvironmentMembership.html */ public toDeleteEnvironmentMembership() { return this.to('DeleteEnvironmentMembership'); } /** * Grants permission to get details about the connection to the EC2 development environment, including host, user, and port * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toDescribeEC2Remote() { return this.to('DescribeEC2Remote'); } /** * Grants permission to get information about environment members for an AWS Cloud9 development environment * * Access Level: Read * * Possible conditions: * - .ifUserArn() * - .ifEnvironmentId() * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_DescribeEnvironmentMemberships.html */ public toDescribeEnvironmentMemberships() { return this.to('DescribeEnvironmentMemberships'); } /** * Grants permission to get status information for an AWS Cloud9 development environment * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_DescribeEnvironmentStatus.html */ public toDescribeEnvironmentStatus() { return this.to('DescribeEnvironmentStatus'); } /** * Grants permission to get information about AWS Cloud9 development environments * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_DescribeEnvironments.html */ public toDescribeEnvironments() { return this.to('DescribeEnvironments'); } /** * Grants permission to get details about the connection to the SSH development environment, including host, user, and port * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toDescribeSSHRemote() { return this.to('DescribeSSHRemote'); } /** * Grants permission to get configuration information that's used to initialize the AWS Cloud9 IDE * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toGetEnvironmentConfig() { return this.to('GetEnvironmentConfig'); } /** * Grants permission to get the AWS Cloud9 IDE settings for a specified development environment * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toGetEnvironmentSettings() { return this.to('GetEnvironmentSettings'); } /** * Grants permission to get the AWS Cloud9 IDE settings for a specified environment member * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toGetMembershipSettings() { return this.to('GetMembershipSettings'); } /** * Grants permission to get the user's public SSH key, which is used by AWS Cloud9 to connect to SSH development environments * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toGetUserPublicKey() { return this.to('GetUserPublicKey'); } /** * Grants permission to get the AWS Cloud9 IDE settings for a specified user * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toGetUserSettings() { return this.to('GetUserSettings'); } /** * Grants permission to get a list of AWS Cloud9 development environment identifiers * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_ListEnvironments.html */ public toListEnvironments() { return this.to('ListEnvironments'); } /** * Grants permission to list tags for a cloud9 environment * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to set AWS managed temporary credentials on the Amazon EC2 instance that's used by the AWS Cloud9 integrated development environment (IDE) * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toModifyTemporaryCredentialsOnEnvironmentEC2() { return this.to('ModifyTemporaryCredentialsOnEnvironmentEC2'); } /** * Grants permission to add tags to a cloud9 environment * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove tags from a cloud9 environment * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to change the settings of an existing AWS Cloud9 development environment * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_UpdateEnvironment.html */ public toUpdateEnvironment() { return this.to('UpdateEnvironment'); } /** * Grants permission to change the settings of an existing environment member for an AWS Cloud9 development environment * * Access Level: Write * * Possible conditions: * - .ifUserArn() * - .ifEnvironmentId() * - .ifPermissions() * * https://docs.aws.amazon.com/cloud9/latest/APIReference/API_UpdateEnvironmentMembership.html */ public toUpdateEnvironmentMembership() { return this.to('UpdateEnvironmentMembership'); } /** * Grants permission to update the AWS Cloud9 IDE settings for a specified development environment * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toUpdateEnvironmentSettings() { return this.to('UpdateEnvironmentSettings'); } /** * Grants permission to update the AWS Cloud9 IDE settings for a specified environment member * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toUpdateMembershipSettings() { return this.to('UpdateMembershipSettings'); } /** * Grants permission to update details about the connection to the SSH development environment, including host, user, and port * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toUpdateSSHRemote() { return this.to('UpdateSSHRemote'); } /** * Grants permission to update IDE-specific settings of an AWS Cloud9 user * * Access Level: Write * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toUpdateUserSettings() { return this.to('UpdateUserSettings'); } /** * Grants permission to validate the environment name during the process of creating an AWS Cloud9 development environment * * Access Level: Read * * https://docs.aws.amazon.com/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-ref-matrix */ public toValidateEnvironmentName() { return this.to('ValidateEnvironmentName'); } protected accessLevelList: AccessLevelList = { "Write": [ "ActivateEC2Remote", "CreateEnvironmentEC2", "CreateEnvironmentMembership", "CreateEnvironmentSSH", "DeleteEnvironment", "DeleteEnvironmentMembership", "ModifyTemporaryCredentialsOnEnvironmentEC2", "UpdateEnvironment", "UpdateEnvironmentMembership", "UpdateEnvironmentSettings", "UpdateMembershipSettings", "UpdateSSHRemote", "UpdateUserSettings" ], "Read": [ "CreateEnvironmentToken", "DescribeEC2Remote", "DescribeEnvironmentMemberships", "DescribeEnvironmentStatus", "DescribeEnvironments", "DescribeSSHRemote", "GetEnvironmentConfig", "GetEnvironmentSettings", "GetMembershipSettings", "GetUserPublicKey", "GetUserSettings", "ListEnvironments", "ListTagsForResource", "ValidateEnvironmentName" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type environment to the statement * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloud9.html##awscloud9-environment * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onEnvironment(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:cloud9:${Region}:${Account}:environment:${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access by the AWS Cloud9 environment ID * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloud9.html##awscloud9-cloud9_EnvironmentId * * Applies to actions: * - .toCreateEnvironmentMembership() * - .toDescribeEnvironmentMemberships() * - .toUpdateEnvironmentMembership() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifEnvironmentId(value: string | string[], operator?: Operator | string) { return this.if(`EnvironmentId`, value, operator || 'StringLike'); } /** * Filters access by the AWS Cloud9 environment name * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloud9.html##awscloud9-cloud9_EnvironmentName * * Applies to actions: * - .toCreateEnvironmentEC2() * - .toCreateEnvironmentSSH() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifEnvironmentName(value: string | string[], operator?: Operator | string) { return this.if(`EnvironmentName`, value, operator || 'StringLike'); } /** * Filters access by the instance type of the AWS Cloud9 environment's Amazon EC2 instance * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloud9.html##awscloud9-cloud9_InstanceType * * Applies to actions: * - .toCreateEnvironmentEC2() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifInstanceType(value: string | string[], operator?: Operator | string) { return this.if(`InstanceType`, value, operator || 'StringLike'); } /** * Filters access by the type of AWS Cloud9 permissions * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloud9.html##awscloud9-cloud9_Permissions * * Applies to actions: * - .toCreateEnvironmentMembership() * - .toUpdateEnvironmentMembership() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifPermissions(value: string | string[], operator?: Operator | string) { return this.if(`Permissions`, value, operator || 'StringLike'); } /** * Filters access by the subnet ID that the AWS Cloud9 environment will be created in * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloud9.html##awscloud9-cloud9_SubnetId * * Applies to actions: * - .toCreateEnvironmentEC2() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifSubnetId(value: string | string[], operator?: Operator | string) { return this.if(`SubnetId`, value, operator || 'StringLike'); } /** * Filters access by the user ARN specified * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloud9.html##awscloud9-cloud9_UserArn * * Applies to actions: * - .toCreateEnvironmentEC2() * - .toCreateEnvironmentMembership() * - .toDescribeEnvironmentMemberships() * - .toUpdateEnvironmentMembership() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifUserArn(value: string | string[], operator?: Operator | string) { return this.if(`UserArn`, value, operator || 'ArnLike'); } }
the_stack
export type RowType = { [key: string]: any; }; // Fields ============================================================== export type Number64 = string; export type Range = [number | string, number | string]; export type Dataset = any[]; export type IFieldType = "boolean" | "number" | "number64" | "string" | "range" | "dataset" | "set" | "object"; export interface IFieldBoolean { type: "boolean"; id: string; default?: boolean; } export interface IFieldNumber { type: "number"; id: string; default?: number; } export interface IFieldNumber64 { type: "number64"; id: string; default?: Number64; } export interface IFieldString { type: "string"; id: string; default?: string; } export interface IFieldRange { type: "range"; id: string; default?: Range; } export interface IFieldDataset { type: "dataset"; id: string; default?: Dataset; children: IField[]; } export interface IFieldSet { type: "set"; id: string; default?: Array<string | number>; fieldType: "string" | "number"; } export interface IFieldObject { type: "object"; id: string; default?: object; fields: { [key: string]: IField }; } export type IField = IFieldBoolean | IFieldNumber | IFieldNumber64 | IFieldString | IFieldRange | IFieldDataset | IFieldSet | IFieldObject; // Datasources ============================================================== export type IDatasourceType = "wuresult" | "logicalfile" | "roxie" | "hipie" | "rest" | "form" | "databomb"; export type DatasourceType = IWUResult | ILogicalFile | IRoxieService | IHipieService | IRestService | IForm | IDatabomb; export interface IDatasource { type: IDatasourceType; id: string; } export interface IService extends IDatasource { url: string; } export interface IOutput { fields: IField[]; } export type OutputDict = { [key: string]: IOutput }; export interface IWUResult extends IService { type: "wuresult"; wuid: string; outputs: OutputDict; } export interface ILogicalFile extends IService { type: "logicalfile"; logicalFile: string; fields: IField[]; } export interface IRoxieService extends IService { type: "roxie"; querySet: string; queryID: string; inputs: IField[]; outputs: OutputDict; } export interface IHipieService extends IService { type: "hipie"; querySet: string; queryID: string; inputs: IField[]; outputs: OutputDict; } export interface IRestService extends IService { type: "rest"; action: string; mode?: "get" | "post"; inputs: IField[]; outputs: OutputDict; } export interface IForm extends IDatasource { type: "form"; fields: IField[]; } export type IDatabombFormat = "csv" | "tsv" | "json"; export interface IDatabomb extends IDatasource { type: "databomb"; fields: IField[]; format: IDatabombFormat; payload?: string; } // IDatasorceRef --- export interface IDatasourceBaseRef { id: string; } export interface IDatabombRef extends IDatasourceBaseRef { } export interface IWUResultRef extends IDatasourceBaseRef { output: string; } export interface IRestResultRef extends IDatasourceBaseRef { responseField: string; } export interface IHipieSqlRef extends IDatasourceBaseRef { } export interface IRequestField { localFieldID: string; source: string; remoteFieldID: string; value: string; } export interface IRoxieServiceRef extends IDatasourceBaseRef { request: IRequestField[]; output: string; } export type IDatasourceRef = IDatabombRef | IWUResultRef | IRoxieServiceRef | IHipieSqlRef; export function isDatabombRef(ref: IDatasourceRef): ref is IDatabombRef { return !isWUResultRef(ref) && !isRoxieServiceRef(ref); } export function isWUResultRef(ref: IDatasourceRef): ref is IWUResultRef { return (ref as IWUResultRef).output !== undefined && !isRoxieServiceRef(ref); } export function isRoxieServiceRef(ref: IDatasourceRef): ref is IRoxieServiceRef { return (ref as IRoxieServiceRef).request !== undefined; } // Activities =============================================================== export type IActivityType = "filter" | "project" | "groupby" | "sort" | "limit" | "mappings"; export type ActivityType = IFilter | IProject | IGroupBy | ISort | ILimit | IMappings; export interface IActivity { type: IActivityType; } // Filter =================================================================== export type IMappingConditionType = "==" | "!=" | ">" | ">=" | "<" | "<=" | "range" | "in"; export interface IMapping { remoteFieldID: string; localFieldID: string; condition: IMappingConditionType; nullable: boolean; } export interface IFilterCondition { viewID: string; mappings: IMapping[]; } export interface IFilterStaticCondition { localFieldID: string; condition: IMappingConditionType; value: string | number; } export type FilterCondition = IFilterCondition | IFilterStaticCondition; export function isIFilterCondition(fc: FilterCondition): fc is IFilterCondition { return !!(fc as IFilterCondition).viewID; } export interface IFilter extends IActivity { type: "filter"; conditions: FilterCondition[]; } export function isFilterActivity(activity: IActivity): activity is IFilter { return activity.type === "filter"; } // Project ================================================================== export interface IEquals { fieldID: string; type: "="; sourceFieldID: string; transformations?: MultiTransformationType[]; } export type ICalculatedType = "+" | "-" | "*" | "/"; export interface ICalculated { fieldID: string; type: ICalculatedType; sourceFieldID1: string; sourceFieldID2: string; } export interface IScale { fieldID: string; type: "scale"; sourceFieldID: string; factor: number; } export interface ITemplate { fieldID: string; type: "template"; template: string; } export interface IMapMapping { value: any; newValue: any; } export interface IMap { fieldID: string; type: "map"; sourceFieldID: string; default: any; mappings: IMapMapping[]; } export type MultiTransformationType = IEquals | ICalculated | IScale | ITemplate | IMap; export interface IMulti { fieldID: string; type: "multi"; transformations: MultiTransformationType[]; } export type ProjectTransformationType = MultiTransformationType | IMulti; export interface IProject extends IActivity { type: "project"; transformations: ProjectTransformationType[]; } export function isProjectActivity(activity: IActivity): activity is IProject { return activity.type === "project"; } export interface IMappings extends IActivity { type: "mappings"; transformations: ProjectTransformationType[]; } export function isMappingsActivity(activity: IActivity): activity is IMappings { return activity.type === "mappings"; } // GroupBy ================================================================== export type IAggregateType = "min" | "max" | "sum" | "mean" | "variance" | "deviation"; export interface IAggregate { fieldID: string; type: IAggregateType; inFieldID: string; baseCountFieldID?: string; } export interface ICount { fieldID: string; type: "count"; } export type AggregateType = IAggregate | ICount; export interface IGroupBy extends IActivity { type: "groupby"; groupByIDs: string[]; aggregates: AggregateType[]; } export function isGroupByActivity(activity: IActivity): activity is IGroupBy { return activity.type === "groupby"; } // Sort ===================================================================== export interface ISortCondition { fieldID: string; descending: boolean; } export interface ISort extends IActivity { type: "sort"; conditions: ISortCondition[]; } export function isSortActivity(activity: IActivity): activity is ISort { return activity.type === "sort"; } // Limit ==================================================================== export interface ILimit extends IActivity { type: "limit"; limit: number; } export function isLimitActivity(activity: IActivity): activity is ILimit { return activity.type === "limit"; } // Visualization ============================================================ export interface IWidgetProperties { __class: string; [propID: string]: string | string[] | number | boolean | undefined | IWidgetProperties | IWidgetProperties[]; } export interface IWidget { id: string; chartType: string; __class: string; properties: IWidgetProperties; } export type VisibilityType = "normal" | "flyout"; export const VisibilitySet: VisibilityType[] = ["normal", "flyout"]; export interface IVisualization extends IWidget { title: string; description?: string; visibility: VisibilityType; mappings: IMappings; secondaryDataviewID?: string; } // View ===================================================================== export interface IView { id: string; datasource: IDatasourceRef; activities: ActivityType[]; visualization: IVisualization; } // DDL ====================================================================== export interface IProperties { [propID: string]: any; } export interface Schema { version: "2.2.1"; createdBy: { name: string; version: string; }; datasources: DatasourceType[]; dataviews: IView[]; properties?: IProperties; hipieProperties?: IProperties; // The following defs are only provided to assist the Java code generation (from the the generated schema) --- defs?: { fieldTypes: { number64: Number64; range: Range; dataset: Dataset; fieldType: IFieldType; fieldBoolean: IFieldBoolean; fieldNumber: IFieldNumber; fieldNumber64: IFieldNumber64 fieldString: IFieldString; fieldRange: IFieldRange; fieldDataset: IFieldDataset; fieldSet: IFieldSet; fieldObject: IFieldObject; field: IField; }; datasourceTypes: { datasource: IDatasource; logicalFile: ILogicalFile; form: IForm; databomb: IDatabomb; wuresult: IWUResult; hipieService: IHipieService; roxieService: IRoxieService; }; datasourceRefTypes: { wuResultRef: IWUResultRef; roxieServiceRef: IRoxieServiceRef; }; activityTypes: { filter: IFilter; project: IProject; groupby: IGroupBy; sort: ISort; limit: ILimit; mappings: IMappings; }; aggregateTypes: { aggregate: IAggregate; count: ICount; }; transformationTypes: { equals: IEquals; calculated: ICalculated; scale: IScale; template: ITemplate; map: IMap; multi: IMulti; }; }; }
the_stack
import { SearchParameters } from 'algoliasearch-helper'; import connectConfigureRelatedItems from '../connectConfigureRelatedItems'; jest.mock('../../core/createConnector', () => (x) => x); const connect = connectConfigureRelatedItems as any; const hit = { objectID: '1', name: 'Amazon - Fire TV Stick with Alexa Voice Remote - Black', description: 'Enjoy smart access to videos, games and apps with this Amazon Fire TV stick.', brand: 'Amazon', categories: ['TV & Home Theater', 'Streaming Media Players'], hierarchicalCategories: { lvl0: 'TV & Home Theater', lvl1: 'TV & Home Theater > Streaming Media Players', }, price: 39.99, free_shipping: false, rating: 4, _snippetResult: { description: { value: 'Enjoy smart access to videos, games and apps with this Amazon Fire TV stick. Its […]', matchLevel: 'none', }, }, _highlightResult: { description: { value: 'Enjoy smart access to videos, games and apps with this Amazon Fire TV stick. Its […]', matchLevel: 'none', matchedWords: [], }, }, }; describe('connectConfigure', () => { describe('single index', () => { const contextValue = { mainTargetedIndex: 'index' }; const defaultProps = { transformSearchParameters: (x) => x, contextValue, }; it('does not provide props', () => { const providedProps = connect.getProvidedProps({ contextValue }, null, { results: {}, }); expect(providedProps).toEqual({}); }); it('sets the optionalFilters search parameter based on matchingPatterns', () => { const searchParameters = connect.getSearchParameters.call( { contextValue }, new SearchParameters(), { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, } ); expect(searchParameters).toEqual( expect.objectContaining({ facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], }) ); }); it('sets the optionalFilters search parameter based on matchingPatterns with nested attributes', () => { const searchParameters = connect.getSearchParameters.call( { contextValue }, new SearchParameters(), { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, 'hierarchicalCategories.lvl0': { score: 2 }, }, } ); expect(searchParameters).toEqual( expect.objectContaining({ facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', 'hierarchicalCategories.lvl0:TV & Home Theater<score=2>', ], }) ); }); it('sets transformed search parameters based on transformSearchParameters', () => { const searchParameters = connect.getSearchParameters.call( { contextValue }, new SearchParameters(), { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, transformSearchParameters(parameters) { return { ...parameters, optionalWords: hit.name.split(' '), }; }, } ); expect(searchParameters).toEqual( expect.objectContaining({ facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], optionalWords: [ 'Amazon', '-', 'Fire', 'TV', 'Stick', 'with', 'Alexa', 'Voice', 'Remote', '-', 'Black', ], }) ); }); it('filters out and warns for incorrect optionalFilters value type', () => { // We need to simulate being in development mode and to mock the global console object // in this test to assert that development warnings are displayed correctly. const originalNodeEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); const searchParameters = connect.getSearchParameters.call( { contextValue }, new SearchParameters(), { ...defaultProps, hit, matchingPatterns: { rating: { score: 1 }, // `rating` is a number, which is not supported by the `optionalFilters` API brand: { score: 3 }, categories: { score: 2 }, }, } ); expect(warnSpy).toHaveBeenCalledTimes(1); expect(warnSpy).toHaveBeenCalledWith( 'The `matchingPatterns` option returned a value of type Number for the "rating" key. This value was not sent to Algolia because `optionalFilters` only supports strings and array of strings.\n\n' + 'You can remove the "rating" key from the `matchingPatterns` option.\n\n' + 'See https://www.algolia.com/doc/api-reference/api-parameters/optionalFilters/' ); expect(searchParameters).toEqual( expect.objectContaining({ facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], }) ); process.env.NODE_ENV = originalNodeEnv; warnSpy.mockRestore(); }); it('calling transitionState should add configure parameters to the search state', () => { const instance = {}; let searchState = connect.transitionState.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, {}, {} ); expect(searchState).toEqual({ configure: { facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], }, }); searchState = connect.transitionState.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, }, }, { configure: { facets: ['categories'] } }, { configure: { facets: ['categories'] } } ); expect(searchState).toEqual({ configure: { facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: ['brand:Amazon<score=3>'], facets: ['categories'], }, }); }); it('calling cleanUp should remove configure parameters from the search state', () => { const instance = {}; // Running `transitionState` allows to set previous search parameters // in the connector state. let searchState = connect.transitionState.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, {}, {} ); searchState = connect.cleanUp.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, { configure: { facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: ['brand:Amazon<score=3>'], facets: ['categories'], }, } ); expect(searchState).toEqual({ configure: { facets: ['categories'], }, }); searchState = connect.cleanUp.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, { configure: { facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: ['brand:Amazon<score=3>'], }, } ); expect(searchState).toEqual({ configure: {} }); }); }); describe('multi index', () => { const contextValue = { mainTargetedIndex: 'first' }; const indexContextValue = { targetedIndex: 'second' }; const defaultProps = { transformSearchParameters: (x) => x, contextValue, indexContextValue, }; it('does not provide props', () => { const providedProps = connect.getProvidedProps({ contextValue }, null, { results: {}, }); expect(providedProps).toEqual({}); }); it('sets the optionalFilters search parameter based on matchingPatterns', () => { const searchParameters = connect.getSearchParameters.call( { contextValue }, new SearchParameters(), { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, } ); expect(searchParameters).toEqual( expect.objectContaining({ facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], }) ); }); it('sets transformed search parameters based on transformSearchParameters', () => { const searchParameters = connect.getSearchParameters.call( { contextValue }, new SearchParameters(), { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, transformSearchParameters(parameters) { return { ...parameters, optionalWords: hit.name.split(' '), }; }, } ); expect(searchParameters).toEqual( expect.objectContaining({ facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], optionalWords: [ 'Amazon', '-', 'Fire', 'TV', 'Stick', 'with', 'Alexa', 'Voice', 'Remote', '-', 'Black', ], }) ); }); it('filters out and warns for incorrect optionalFilters value type', () => { // We need to simulate being in development mode and to mock the global console object // in this test to assert that development warnings are displayed correctly. const originalNodeEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); const searchParameters = connect.getSearchParameters.call( { contextValue }, new SearchParameters(), { ...defaultProps, hit, matchingPatterns: { rating: { score: 1 }, // `rating` is a number, which is not supported by the `optionalFilters` API brand: { score: 3 }, categories: { score: 2 }, }, } ); expect(warnSpy).toHaveBeenCalledTimes(1); expect(warnSpy).toHaveBeenCalledWith( 'The `matchingPatterns` option returned a value of type Number for the "rating" key. This value was not sent to Algolia because `optionalFilters` only supports strings and array of strings.\n\n' + 'You can remove the "rating" key from the `matchingPatterns` option.\n\n' + 'See https://www.algolia.com/doc/api-reference/api-parameters/optionalFilters/' ); expect(searchParameters).toEqual( expect.objectContaining({ facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], }) ); process.env.NODE_ENV = originalNodeEnv; warnSpy.mockRestore(); }); it('calling transitionState should add configure parameters to the search state', () => { const instance = {}; const searchState = connect.transitionState.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, {}, {} ); expect(searchState).toEqual({ indices: { second: { configure: { facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: [ 'brand:Amazon<score=3>', [ 'categories:TV & Home Theater<score=2>', 'categories:Streaming Media Players<score=2>', ], ], }, }, }, }); }); it('calling cleanUp should remove configure parameters from the search state', () => { const instance = {}; // Running `transitionState` allows to set previous search parameters // in the connector state. let searchState = connect.transitionState.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, {}, {} ); searchState = connect.cleanUp.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, { indices: { second: { configure: { facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: ['brand:Amazon<score=3>'], facets: ['categories'], }, }, }, } ); expect(searchState).toEqual({ indices: { second: { configure: { facets: ['categories'], }, }, }, }); searchState = connect.cleanUp.call( instance, { ...defaultProps, hit, matchingPatterns: { brand: { score: 3 }, categories: { score: 2 }, }, }, { indices: { second: { configure: { facetFilters: ['objectID:-1'], sumOrFiltersScores: true, optionalFilters: ['brand:Amazon<score=3>'], }, }, }, } ); expect(searchState).toEqual({ indices: { second: { configure: {} } } }); }); }); });
the_stack
import {ResourceBase, ResourceTag} from '../resource' import {Value, List} from '../dataTypes' export class HlsInputSettings { BufferSegments?: Value<number> Retries?: Value<number> Bandwidth?: Value<number> RetryInterval?: Value<number> constructor(properties: HlsInputSettings) { Object.assign(this, properties) } } export class DvbSubDestinationSettings { BackgroundOpacity?: Value<number> FontResolution?: Value<number> OutlineColor?: Value<string> FontColor?: Value<string> ShadowColor?: Value<string> ShadowOpacity?: Value<number> Font?: InputLocation ShadowYOffset?: Value<number> Alignment?: Value<string> XPosition?: Value<number> FontSize?: Value<string> YPosition?: Value<number> OutlineSize?: Value<number> TeletextGridControl?: Value<string> FontOpacity?: Value<number> ShadowXOffset?: Value<number> BackgroundColor?: Value<string> constructor(properties: DvbSubDestinationSettings) { Object.assign(this, properties) } } export class Rec709Settings { constructor(properties: Rec709Settings) { Object.assign(this, properties) } } export class VideoCodecSettings { Mpeg2Settings?: Mpeg2Settings FrameCaptureSettings?: FrameCaptureSettings H264Settings?: H264Settings H265Settings?: H265Settings constructor(properties: VideoCodecSettings) { Object.assign(this, properties) } } export class HlsSettings { StandardHlsSettings?: StandardHlsSettings AudioOnlyHlsSettings?: AudioOnlyHlsSettings Fmp4HlsSettings?: Fmp4HlsSettings FrameCaptureHlsSettings?: FrameCaptureHlsSettings constructor(properties: HlsSettings) { Object.assign(this, properties) } } export class FrameCaptureSettings { CaptureInterval?: Value<number> CaptureIntervalUnits?: Value<string> constructor(properties: FrameCaptureSettings) { Object.assign(this, properties) } } export class MotionGraphicsSettings { HtmlMotionGraphicsSettings?: HtmlMotionGraphicsSettings constructor(properties: MotionGraphicsSettings) { Object.assign(this, properties) } } export class FrameCaptureCdnSettings { FrameCaptureS3Settings?: FrameCaptureS3Settings constructor(properties: FrameCaptureCdnSettings) { Object.assign(this, properties) } } export class InputLossBehavior { InputLossImageColor?: Value<string> BlackFrameMsec?: Value<number> InputLossImageType?: Value<string> InputLossImageSlate?: InputLocation RepeatFrameMsec?: Value<number> constructor(properties: InputLossBehavior) { Object.assign(this, properties) } } export class MultiplexProgramChannelDestinationSettings { MultiplexId?: Value<string> ProgramName?: Value<string> constructor(properties: MultiplexProgramChannelDestinationSettings) { Object.assign(this, properties) } } export class HlsCdnSettings { HlsWebdavSettings?: HlsWebdavSettings HlsS3Settings?: HlsS3Settings HlsAkamaiSettings?: HlsAkamaiSettings HlsBasicPutSettings?: HlsBasicPutSettings HlsMediaStoreSettings?: HlsMediaStoreSettings constructor(properties: HlsCdnSettings) { Object.assign(this, properties) } } export class HlsOutputSettings { NameModifier?: Value<string> HlsSettings?: HlsSettings H265PackagingType?: Value<string> SegmentModifier?: Value<string> constructor(properties: HlsOutputSettings) { Object.assign(this, properties) } } export class EmbeddedPlusScte20DestinationSettings { constructor(properties: EmbeddedPlusScte20DestinationSettings) { Object.assign(this, properties) } } export class FrameCaptureS3Settings { CannedAcl?: Value<string> constructor(properties: FrameCaptureS3Settings) { Object.assign(this, properties) } } export class ArchiveCdnSettings { ArchiveS3Settings?: ArchiveS3Settings constructor(properties: ArchiveCdnSettings) { Object.assign(this, properties) } } export class Scte27SourceSettings { Pid?: Value<number> constructor(properties: Scte27SourceSettings) { Object.assign(this, properties) } } export class AudioTrackSelection { Tracks?: List<AudioTrack> constructor(properties: AudioTrackSelection) { Object.assign(this, properties) } } export class EbuTtDDestinationSettings { FontFamily?: Value<string> FillLineGap?: Value<string> StyleControl?: Value<string> CopyrightHolder?: Value<string> constructor(properties: EbuTtDDestinationSettings) { Object.assign(this, properties) } } export class VideoSelectorPid { Pid?: Value<number> constructor(properties: VideoSelectorPid) { Object.assign(this, properties) } } export class FailoverCondition { FailoverConditionSettings?: FailoverConditionSettings constructor(properties: FailoverCondition) { Object.assign(this, properties) } } export class Hdr10Settings { MaxCll?: Value<number> MaxFall?: Value<number> constructor(properties: Hdr10Settings) { Object.assign(this, properties) } } export class StaticKeySettings { KeyProviderServer?: InputLocation StaticKeyValue?: Value<string> constructor(properties: StaticKeySettings) { Object.assign(this, properties) } } export class InputLocation { Username?: Value<string> PasswordParam?: Value<string> Uri?: Value<string> constructor(properties: InputLocation) { Object.assign(this, properties) } } export class AudioLanguageSelection { LanguageCode?: Value<string> LanguageSelectionPolicy?: Value<string> constructor(properties: AudioLanguageSelection) { Object.assign(this, properties) } } export class CaptionRectangle { TopOffset?: Value<number> Height?: Value<number> Width?: Value<number> LeftOffset?: Value<number> constructor(properties: CaptionRectangle) { Object.assign(this, properties) } } export class ArchiveS3Settings { CannedAcl?: Value<string> constructor(properties: ArchiveS3Settings) { Object.assign(this, properties) } } export class SmpteTtDestinationSettings { constructor(properties: SmpteTtDestinationSettings) { Object.assign(this, properties) } } export class AribSourceSettings { constructor(properties: AribSourceSettings) { Object.assign(this, properties) } } export class Mp2Settings { CodingMode?: Value<string> SampleRate?: Value<number> Bitrate?: Value<number> constructor(properties: Mp2Settings) { Object.assign(this, properties) } } export class AudioSilenceFailoverSettings { AudioSelectorName?: Value<string> AudioSilenceThresholdMsec?: Value<number> constructor(properties: AudioSilenceFailoverSettings) { Object.assign(this, properties) } } export class Fmp4HlsSettings { AudioRenditionSets?: Value<string> NielsenId3Behavior?: Value<string> TimedMetadataBehavior?: Value<string> constructor(properties: Fmp4HlsSettings) { Object.assign(this, properties) } } export class Scte35SpliceInsert { AdAvailOffset?: Value<number> WebDeliveryAllowedFlag?: Value<string> NoRegionalBlackoutFlag?: Value<string> constructor(properties: Scte35SpliceInsert) { Object.assign(this, properties) } } export class AudioChannelMapping { OutputChannel?: Value<number> InputChannelLevels?: List<InputChannelLevel> constructor(properties: AudioChannelMapping) { Object.assign(this, properties) } } export class FeatureActivations { InputPrepareScheduleActions?: Value<string> constructor(properties: FeatureActivations) { Object.assign(this, properties) } } export class OutputGroup { Outputs?: List<Output> OutputGroupSettings?: OutputGroupSettings Name?: Value<string> constructor(properties: OutputGroup) { Object.assign(this, properties) } } export class UdpOutputSettings { Destination?: OutputLocationRef FecOutputSettings?: FecOutputSettings ContainerSettings?: UdpContainerSettings BufferMsec?: Value<number> constructor(properties: UdpOutputSettings) { Object.assign(this, properties) } } export class Ac3Settings { CodingMode?: Value<string> DrcProfile?: Value<string> MetadataControl?: Value<string> Dialnorm?: Value<number> LfeFilter?: Value<string> BitstreamMode?: Value<string> Bitrate?: Value<number> constructor(properties: Ac3Settings) { Object.assign(this, properties) } } export class Eac3Settings { CodingMode?: Value<string> SurroundMode?: Value<string> PassthroughControl?: Value<string> Dialnorm?: Value<number> LoRoSurroundMixLevel?: Value<number> PhaseControl?: Value<string> LtRtCenterMixLevel?: Value<number> LfeFilter?: Value<string> LfeControl?: Value<string> Bitrate?: Value<number> DrcLine?: Value<string> DcFilter?: Value<string> MetadataControl?: Value<string> LtRtSurroundMixLevel?: Value<number> LoRoCenterMixLevel?: Value<number> DrcRf?: Value<string> AttenuationControl?: Value<string> BitstreamMode?: Value<string> SurroundExMode?: Value<string> StereoDownmix?: Value<string> constructor(properties: Eac3Settings) { Object.assign(this, properties) } } export class MediaPackageOutputSettings { constructor(properties: MediaPackageOutputSettings) { Object.assign(this, properties) } } export class Rec601Settings { constructor(properties: Rec601Settings) { Object.assign(this, properties) } } export class H264Settings { NumRefFrames?: Value<number> TemporalAq?: Value<string> Slices?: Value<number> FramerateControl?: Value<string> QvbrQualityLevel?: Value<number> FramerateNumerator?: Value<number> ParControl?: Value<string> GopClosedCadence?: Value<number> FlickerAq?: Value<string> Profile?: Value<string> QualityLevel?: Value<string> MinIInterval?: Value<number> SceneChangeDetect?: Value<string> ForceFieldPictures?: Value<string> FramerateDenominator?: Value<number> Softness?: Value<number> GopSize?: Value<number> AdaptiveQuantization?: Value<string> FilterSettings?: H264FilterSettings ColorSpaceSettings?: H264ColorSpaceSettings EntropyEncoding?: Value<string> SpatialAq?: Value<string> ParDenominator?: Value<number> FixedAfd?: Value<string> GopSizeUnits?: Value<string> AfdSignaling?: Value<string> Bitrate?: Value<number> ParNumerator?: Value<number> RateControlMode?: Value<string> ScanType?: Value<string> BufSize?: Value<number> TimecodeInsertion?: Value<string> ColorMetadata?: Value<string> BufFillPct?: Value<number> GopBReference?: Value<string> LookAheadRateControl?: Value<string> Level?: Value<string> MaxBitrate?: Value<number> Syntax?: Value<string> SubgopLength?: Value<string> GopNumBFrames?: Value<number> constructor(properties: H264Settings) { Object.assign(this, properties) } } export class H264FilterSettings { TemporalFilterSettings?: TemporalFilterSettings constructor(properties: H264FilterSettings) { Object.assign(this, properties) } } export class FailoverConditionSettings { AudioSilenceSettings?: AudioSilenceFailoverSettings VideoBlackSettings?: VideoBlackFailoverSettings InputLossSettings?: InputLossFailoverSettings constructor(properties: FailoverConditionSettings) { Object.assign(this, properties) } } export class Mpeg2Settings { ColorSpace?: Value<string> FixedAfd?: Value<string> GopSizeUnits?: Value<string> FramerateNumerator?: Value<number> GopClosedCadence?: Value<number> AfdSignaling?: Value<string> DisplayAspectRatio?: Value<string> ScanType?: Value<string> TimecodeInsertion?: Value<string> ColorMetadata?: Value<string> FramerateDenominator?: Value<number> GopSize?: Value<number> AdaptiveQuantization?: Value<string> SubgopLength?: Value<string> FilterSettings?: Mpeg2FilterSettings GopNumBFrames?: Value<number> constructor(properties: Mpeg2Settings) { Object.assign(this, properties) } } export class AudioSelectorSettings { AudioPidSelection?: AudioPidSelection AudioLanguageSelection?: AudioLanguageSelection AudioTrackSelection?: AudioTrackSelection constructor(properties: AudioSelectorSettings) { Object.assign(this, properties) } } export class UdpContainerSettings { M2tsSettings?: M2tsSettings constructor(properties: UdpContainerSettings) { Object.assign(this, properties) } } export class TimecodeConfig { SyncThreshold?: Value<number> Source?: Value<string> constructor(properties: TimecodeConfig) { Object.assign(this, properties) } } export class VideoSelector { ColorSpaceSettings?: VideoSelectorColorSpaceSettings SelectorSettings?: VideoSelectorSettings ColorSpace?: Value<string> ColorSpaceUsage?: Value<string> constructor(properties: VideoSelector) { Object.assign(this, properties) } } export class DvbTdtSettings { RepInterval?: Value<number> constructor(properties: DvbTdtSettings) { Object.assign(this, properties) } } export class HlsGroupSettings { SegmentationMode?: Value<string> Destination?: OutputLocationRef CodecSpecification?: Value<string> IvSource?: Value<string> TimedMetadataId3Frame?: Value<string> KeyFormatVersions?: Value<string> RedundantManifest?: Value<string> OutputSelection?: Value<string> KeyProviderSettings?: KeyProviderSettings StreamInfResolution?: Value<string> CaptionLanguageMappings?: List<CaptionLanguageMapping> HlsId3SegmentTagging?: Value<string> IFrameOnlyPlaylists?: Value<string> CaptionLanguageSetting?: Value<string> KeepSegments?: Value<number> ConstantIv?: Value<string> DirectoryStructure?: Value<string> EncryptionType?: Value<string> AdMarkers?: List<Value<string>> HlsCdnSettings?: HlsCdnSettings IndexNSegments?: Value<number> DiscontinuityTags?: Value<string> InputLossAction?: Value<string> Mode?: Value<string> TsFileMode?: Value<string> BaseUrlManifest1?: Value<string> ClientCache?: Value<string> MinSegmentLength?: Value<number> KeyFormat?: Value<string> IvInManifest?: Value<string> BaseUrlContent1?: Value<string> ManifestCompression?: Value<string> ManifestDurationFormat?: Value<string> TimedMetadataId3Period?: Value<number> IncompleteSegmentBehavior?: Value<string> ProgramDateTimePeriod?: Value<number> SegmentLength?: Value<number> TimestampDeltaMilliseconds?: Value<number> ProgramDateTime?: Value<string> SegmentsPerSubdirectory?: Value<number> BaseUrlContent?: Value<string> BaseUrlManifest?: Value<string> constructor(properties: HlsGroupSettings) { Object.assign(this, properties) } } export class OutputDestinationSettings { StreamName?: Value<string> Username?: Value<string> PasswordParam?: Value<string> Url?: Value<string> constructor(properties: OutputDestinationSettings) { Object.assign(this, properties) } } export class AvailConfiguration { AvailSettings?: AvailSettings constructor(properties: AvailConfiguration) { Object.assign(this, properties) } } export class TeletextDestinationSettings { constructor(properties: TeletextDestinationSettings) { Object.assign(this, properties) } } export class H265Settings { Slices?: Value<number> QvbrQualityLevel?: Value<number> FramerateNumerator?: Value<number> GopClosedCadence?: Value<number> FlickerAq?: Value<string> Profile?: Value<string> MinIInterval?: Value<number> SceneChangeDetect?: Value<string> FramerateDenominator?: Value<number> GopSize?: Value<number> AdaptiveQuantization?: Value<string> FilterSettings?: H265FilterSettings AlternativeTransferFunction?: Value<string> ColorSpaceSettings?: H265ColorSpaceSettings Tier?: Value<string> ParDenominator?: Value<number> FixedAfd?: Value<string> GopSizeUnits?: Value<string> AfdSignaling?: Value<string> Bitrate?: Value<number> ParNumerator?: Value<number> RateControlMode?: Value<string> ScanType?: Value<string> BufSize?: Value<number> TimecodeInsertion?: Value<string> ColorMetadata?: Value<string> LookAheadRateControl?: Value<string> Level?: Value<string> MaxBitrate?: Value<number> constructor(properties: H265Settings) { Object.assign(this, properties) } } export class AudioCodecSettings { Eac3Settings?: Eac3Settings Ac3Settings?: Ac3Settings Mp2Settings?: Mp2Settings PassThroughSettings?: PassThroughSettings WavSettings?: WavSettings AacSettings?: AacSettings constructor(properties: AudioCodecSettings) { Object.assign(this, properties) } } export class DvbNitSettings { NetworkName?: Value<string> RepInterval?: Value<number> NetworkId?: Value<number> constructor(properties: DvbNitSettings) { Object.assign(this, properties) } } export class WebvttDestinationSettings { constructor(properties: WebvttDestinationSettings) { Object.assign(this, properties) } } export class AacSettings { CodingMode?: Value<string> RateControlMode?: Value<string> SampleRate?: Value<number> InputType?: Value<string> VbrQuality?: Value<string> RawFormat?: Value<string> Spec?: Value<string> Bitrate?: Value<number> Profile?: Value<string> constructor(properties: AacSettings) { Object.assign(this, properties) } } export class Scte35TimeSignalApos { AdAvailOffset?: Value<number> WebDeliveryAllowedFlag?: Value<string> NoRegionalBlackoutFlag?: Value<string> constructor(properties: Scte35TimeSignalApos) { Object.assign(this, properties) } } export class FecOutputSettings { RowLength?: Value<number> ColumnDepth?: Value<number> IncludeFec?: Value<string> constructor(properties: FecOutputSettings) { Object.assign(this, properties) } } export class OutputDestination { MultiplexSettings?: MultiplexProgramChannelDestinationSettings Id?: Value<string> Settings?: List<OutputDestinationSettings> MediaPackageSettings?: List<MediaPackageOutputDestinationSettings> constructor(properties: OutputDestination) { Object.assign(this, properties) } } export class AncillarySourceSettings { SourceAncillaryChannelNumber?: Value<number> constructor(properties: AncillarySourceSettings) { Object.assign(this, properties) } } export class Mpeg2FilterSettings { TemporalFilterSettings?: TemporalFilterSettings constructor(properties: Mpeg2FilterSettings) { Object.assign(this, properties) } } export class CaptionSelector { LanguageCode?: Value<string> SelectorSettings?: CaptionSelectorSettings Name?: Value<string> constructor(properties: CaptionSelector) { Object.assign(this, properties) } } export class VideoBlackFailoverSettings { VideoBlackThresholdMsec?: Value<number> BlackDetectThreshold?: Value<number> constructor(properties: VideoBlackFailoverSettings) { Object.assign(this, properties) } } export class RtmpOutputSettings { Destination?: OutputLocationRef CertificateMode?: Value<string> NumRetries?: Value<number> ConnectionRetryInterval?: Value<number> constructor(properties: RtmpOutputSettings) { Object.assign(this, properties) } } export class RtmpCaptionInfoDestinationSettings { constructor(properties: RtmpCaptionInfoDestinationSettings) { Object.assign(this, properties) } } export class TtmlDestinationSettings { StyleControl?: Value<string> constructor(properties: TtmlDestinationSettings) { Object.assign(this, properties) } } export class M2tsSettings { EtvPlatformPid?: Value<string> PatInterval?: Value<number> ProgramNum?: Value<number> RateMode?: Value<string> KlvDataPids?: Value<string> NullPacketBitrate?: Value<number> PmtInterval?: Value<number> AribCaptionsPid?: Value<string> EsRateInPes?: Value<string> VideoPid?: Value<string> TransportStreamId?: Value<number> EbpPlacement?: Value<string> DvbSubPids?: Value<string> SegmentationStyle?: Value<string> Scte35Pid?: Value<string> AudioStreamType?: Value<string> Klv?: Value<string> EbpLookaheadMs?: Value<number> DvbTdtSettings?: DvbTdtSettings TimedMetadataBehavior?: Value<string> EbpAudioInterval?: Value<string> FragmentTime?: Value<number> DvbTeletextPid?: Value<string> Scte35Control?: Value<string> PcrPeriod?: Value<number> NielsenId3Behavior?: Value<string> PcrPid?: Value<string> SegmentationTime?: Value<number> CcDescriptor?: Value<string> AudioFramesPerPes?: Value<number> AbsentInputAudioBehavior?: Value<string> Bitrate?: Value<number> PmtPid?: Value<string> Scte27Pids?: Value<string> SegmentationMarkers?: Value<string> DvbNitSettings?: DvbNitSettings DvbSdtSettings?: DvbSdtSettings EtvSignalPid?: Value<string> Arib?: Value<string> BufferModel?: Value<string> EcmPid?: Value<string> TimedMetadataPid?: Value<string> AudioPids?: Value<string> AudioBufferModel?: Value<string> Ebif?: Value<string> AribCaptionsPidControl?: Value<string> PcrControl?: Value<string> constructor(properties: M2tsSettings) { Object.assign(this, properties) } } export class HlsWebdavSettings { FilecacheDuration?: Value<number> NumRetries?: Value<number> RestartDelay?: Value<number> ConnectionRetryInterval?: Value<number> HttpTransferMode?: Value<string> constructor(properties: HlsWebdavSettings) { Object.assign(this, properties) } } export class NielsenConfiguration { DistributorId?: Value<string> NielsenPcmToId3Tagging?: Value<string> constructor(properties: NielsenConfiguration) { Object.assign(this, properties) } } export class GlobalConfiguration { InputEndAction?: Value<string> OutputTimingSource?: Value<string> OutputLockingMode?: Value<string> SupportLowFramerateInputs?: Value<string> InitialAudioGain?: Value<number> InputLossBehavior?: InputLossBehavior constructor(properties: GlobalConfiguration) { Object.assign(this, properties) } } export class MediaPackageOutputDestinationSettings { ChannelId?: Value<string> constructor(properties: MediaPackageOutputDestinationSettings) { Object.assign(this, properties) } } export class AudioOnlyHlsSettings { SegmentType?: Value<string> AudioTrackType?: Value<string> AudioOnlyImage?: InputLocation AudioGroupId?: Value<string> constructor(properties: AudioOnlyHlsSettings) { Object.assign(this, properties) } } export class OutputLocationRef { DestinationRefId?: Value<string> constructor(properties: OutputLocationRef) { Object.assign(this, properties) } } export class Scte27DestinationSettings { constructor(properties: Scte27DestinationSettings) { Object.assign(this, properties) } } export class AutomaticInputFailoverSettings { FailoverConditions?: List<FailoverCondition> InputPreference?: Value<string> SecondaryInputId?: Value<string> ErrorClearTimeMsec?: Value<number> constructor(properties: AutomaticInputFailoverSettings) { Object.assign(this, properties) } } export class FrameCaptureGroupSettings { FrameCaptureCdnSettings?: FrameCaptureCdnSettings Destination?: OutputLocationRef constructor(properties: FrameCaptureGroupSettings) { Object.assign(this, properties) } } export class ArchiveOutputSettings { Extension?: Value<string> NameModifier?: Value<string> ContainerSettings?: ArchiveContainerSettings constructor(properties: ArchiveOutputSettings) { Object.assign(this, properties) } } export class ArchiveGroupSettings { Destination?: OutputLocationRef ArchiveCdnSettings?: ArchiveCdnSettings RolloverInterval?: Value<number> constructor(properties: ArchiveGroupSettings) { Object.assign(this, properties) } } export class RawSettings { constructor(properties: RawSettings) { Object.assign(this, properties) } } export class DvbSdtSettings { ServiceProviderName?: Value<string> OutputSdt?: Value<string> ServiceName?: Value<string> RepInterval?: Value<number> constructor(properties: DvbSdtSettings) { Object.assign(this, properties) } } export class VideoSelectorProgramId { ProgramId?: Value<number> constructor(properties: VideoSelectorProgramId) { Object.assign(this, properties) } } export class InputAttachment { InputAttachmentName?: Value<string> InputId?: Value<string> AutomaticInputFailoverSettings?: AutomaticInputFailoverSettings InputSettings?: InputSettings constructor(properties: InputAttachment) { Object.assign(this, properties) } } export class InputChannelLevel { InputChannel?: Value<number> Gain?: Value<number> constructor(properties: InputChannelLevel) { Object.assign(this, properties) } } export class StandardHlsSettings { AudioRenditionSets?: Value<string> M3u8Settings?: M3u8Settings constructor(properties: StandardHlsSettings) { Object.assign(this, properties) } } export class PassThroughSettings { constructor(properties: PassThroughSettings) { Object.assign(this, properties) } } export class ArchiveContainerSettings { RawSettings?: RawSettings M2tsSettings?: M2tsSettings constructor(properties: ArchiveContainerSettings) { Object.assign(this, properties) } } export class EmbeddedSourceSettings { Source608ChannelNumber?: Value<number> Scte20Detection?: Value<string> Source608TrackNumber?: Value<number> Convert608To708?: Value<string> constructor(properties: EmbeddedSourceSettings) { Object.assign(this, properties) } } export class InputSpecification { Codec?: Value<string> MaximumBitrate?: Value<string> Resolution?: Value<string> constructor(properties: InputSpecification) { Object.assign(this, properties) } } export class FrameCaptureOutputSettings { NameModifier?: Value<string> constructor(properties: FrameCaptureOutputSettings) { Object.assign(this, properties) } } export class EncoderSettings { AudioDescriptions?: List<AudioDescription> VideoDescriptions?: List<VideoDescription> FeatureActivations?: FeatureActivations GlobalConfiguration?: GlobalConfiguration CaptionDescriptions?: List<CaptionDescription> AvailConfiguration?: AvailConfiguration MotionGraphicsConfiguration?: MotionGraphicsConfiguration OutputGroups?: List<OutputGroup> AvailBlanking?: AvailBlanking NielsenConfiguration?: NielsenConfiguration BlackoutSlate?: BlackoutSlate TimecodeConfig?: TimecodeConfig constructor(properties: EncoderSettings) { Object.assign(this, properties) } } export class AvailSettings { Scte35SpliceInsert?: Scte35SpliceInsert Scte35TimeSignalApos?: Scte35TimeSignalApos constructor(properties: AvailSettings) { Object.assign(this, properties) } } export class H264ColorSpaceSettings { Rec601Settings?: Rec601Settings Rec709Settings?: Rec709Settings ColorSpacePassthroughSettings?: ColorSpacePassthroughSettings constructor(properties: H264ColorSpaceSettings) { Object.assign(this, properties) } } export class MediaPackageGroupSettings { Destination?: OutputLocationRef constructor(properties: MediaPackageGroupSettings) { Object.assign(this, properties) } } export class MultiplexOutputSettings { Destination?: OutputLocationRef constructor(properties: MultiplexOutputSettings) { Object.assign(this, properties) } } export class H265ColorSpaceSettings { Rec601Settings?: Rec601Settings Rec709Settings?: Rec709Settings ColorSpacePassthroughSettings?: ColorSpacePassthroughSettings Hdr10Settings?: Hdr10Settings constructor(properties: H265ColorSpaceSettings) { Object.assign(this, properties) } } export class EmbeddedDestinationSettings { constructor(properties: EmbeddedDestinationSettings) { Object.assign(this, properties) } } export class AvailBlanking { State?: Value<string> AvailBlankingImage?: InputLocation constructor(properties: AvailBlanking) { Object.assign(this, properties) } } export class InputSettings { DeblockFilter?: Value<string> FilterStrength?: Value<number> InputFilter?: Value<string> SourceEndBehavior?: Value<string> VideoSelector?: VideoSelector Smpte2038DataPreference?: Value<string> AudioSelectors?: List<AudioSelector> CaptionSelectors?: List<CaptionSelector> DenoiseFilter?: Value<string> NetworkInputSettings?: NetworkInputSettings constructor(properties: InputSettings) { Object.assign(this, properties) } } export class AudioNormalizationSettings { TargetLkfs?: Value<number> Algorithm?: Value<string> AlgorithmControl?: Value<string> constructor(properties: AudioNormalizationSettings) { Object.assign(this, properties) } } export class MultiplexGroupSettings { constructor(properties: MultiplexGroupSettings) { Object.assign(this, properties) } } export class InputLossFailoverSettings { InputLossThresholdMsec?: Value<number> constructor(properties: InputLossFailoverSettings) { Object.assign(this, properties) } } export class AudioSelector { SelectorSettings?: AudioSelectorSettings Name?: Value<string> constructor(properties: AudioSelector) { Object.assign(this, properties) } } export class AudioPidSelection { Pid?: Value<number> constructor(properties: AudioPidSelection) { Object.assign(this, properties) } } export class CaptionLanguageMapping { LanguageCode?: Value<string> LanguageDescription?: Value<string> CaptionChannel?: Value<number> constructor(properties: CaptionLanguageMapping) { Object.assign(this, properties) } } export class DvbSubSourceSettings { Pid?: Value<number> constructor(properties: DvbSubSourceSettings) { Object.assign(this, properties) } } export class CaptionSelectorSettings { DvbSubSourceSettings?: DvbSubSourceSettings Scte27SourceSettings?: Scte27SourceSettings AribSourceSettings?: AribSourceSettings EmbeddedSourceSettings?: EmbeddedSourceSettings Scte20SourceSettings?: Scte20SourceSettings TeletextSourceSettings?: TeletextSourceSettings AncillarySourceSettings?: AncillarySourceSettings constructor(properties: CaptionSelectorSettings) { Object.assign(this, properties) } } export class VideoSelectorSettings { VideoSelectorProgramId?: VideoSelectorProgramId VideoSelectorPid?: VideoSelectorPid constructor(properties: VideoSelectorSettings) { Object.assign(this, properties) } } export class VpcOutputSettings { PublicAddressAllocationIds?: List<Value<string>> SecurityGroupIds?: List<Value<string>> SubnetIds?: List<Value<string>> constructor(properties: VpcOutputSettings) { Object.assign(this, properties) } } export class TeletextSourceSettings { OutputRectangle?: CaptionRectangle PageNumber?: Value<string> constructor(properties: TeletextSourceSettings) { Object.assign(this, properties) } } export class CaptionDescription { DestinationSettings?: CaptionDestinationSettings LanguageCode?: Value<string> LanguageDescription?: Value<string> CaptionSelectorName?: Value<string> Name?: Value<string> constructor(properties: CaptionDescription) { Object.assign(this, properties) } } export class MotionGraphicsConfiguration { MotionGraphicsSettings?: MotionGraphicsSettings MotionGraphicsInsertion?: Value<string> constructor(properties: MotionGraphicsConfiguration) { Object.assign(this, properties) } } export class VideoSelectorColorSpaceSettings { Hdr10Settings?: Hdr10Settings constructor(properties: VideoSelectorColorSpaceSettings) { Object.assign(this, properties) } } export class Output { OutputSettings?: OutputSettings CaptionDescriptionNames?: List<Value<string>> AudioDescriptionNames?: List<Value<string>> OutputName?: Value<string> VideoDescriptionName?: Value<string> constructor(properties: Output) { Object.assign(this, properties) } } export class NetworkInputSettings { ServerValidation?: Value<string> HlsInputSettings?: HlsInputSettings constructor(properties: NetworkInputSettings) { Object.assign(this, properties) } } export class H265FilterSettings { TemporalFilterSettings?: TemporalFilterSettings constructor(properties: H265FilterSettings) { Object.assign(this, properties) } } export class HlsBasicPutSettings { FilecacheDuration?: Value<number> NumRetries?: Value<number> RestartDelay?: Value<number> ConnectionRetryInterval?: Value<number> constructor(properties: HlsBasicPutSettings) { Object.assign(this, properties) } } export class Scte20PlusEmbeddedDestinationSettings { constructor(properties: Scte20PlusEmbeddedDestinationSettings) { Object.assign(this, properties) } } export class Scte20SourceSettings { Source608ChannelNumber?: Value<number> Convert608To708?: Value<string> constructor(properties: Scte20SourceSettings) { Object.assign(this, properties) } } export class AudioTrack { Track?: Value<number> constructor(properties: AudioTrack) { Object.assign(this, properties) } } export class AudioDescription { AudioNormalizationSettings?: AudioNormalizationSettings LanguageCode?: Value<string> RemixSettings?: RemixSettings AudioSelectorName?: Value<string> StreamName?: Value<string> LanguageCodeControl?: Value<string> AudioType?: Value<string> AudioTypeControl?: Value<string> CodecSettings?: AudioCodecSettings Name?: Value<string> constructor(properties: AudioDescription) { Object.assign(this, properties) } } export class BurnInDestinationSettings { BackgroundOpacity?: Value<number> FontResolution?: Value<number> OutlineColor?: Value<string> FontColor?: Value<string> ShadowColor?: Value<string> ShadowOpacity?: Value<number> Font?: InputLocation ShadowYOffset?: Value<number> Alignment?: Value<string> XPosition?: Value<number> FontSize?: Value<string> YPosition?: Value<number> OutlineSize?: Value<number> TeletextGridControl?: Value<string> FontOpacity?: Value<number> ShadowXOffset?: Value<number> BackgroundColor?: Value<string> constructor(properties: BurnInDestinationSettings) { Object.assign(this, properties) } } export class RtmpGroupSettings { AuthenticationScheme?: Value<string> CacheLength?: Value<number> AdMarkers?: List<Value<string>> InputLossAction?: Value<string> RestartDelay?: Value<number> CaptionData?: Value<string> CacheFullBehavior?: Value<string> constructor(properties: RtmpGroupSettings) { Object.assign(this, properties) } } export class MsSmoothOutputSettings { NameModifier?: Value<string> H265PackagingType?: Value<string> constructor(properties: MsSmoothOutputSettings) { Object.assign(this, properties) } } export class CaptionDestinationSettings { AribDestinationSettings?: AribDestinationSettings EbuTtDDestinationSettings?: EbuTtDDestinationSettings SmpteTtDestinationSettings?: SmpteTtDestinationSettings EmbeddedPlusScte20DestinationSettings?: EmbeddedPlusScte20DestinationSettings TtmlDestinationSettings?: TtmlDestinationSettings Scte20PlusEmbeddedDestinationSettings?: Scte20PlusEmbeddedDestinationSettings DvbSubDestinationSettings?: DvbSubDestinationSettings TeletextDestinationSettings?: TeletextDestinationSettings BurnInDestinationSettings?: BurnInDestinationSettings WebvttDestinationSettings?: WebvttDestinationSettings EmbeddedDestinationSettings?: EmbeddedDestinationSettings RtmpCaptionInfoDestinationSettings?: RtmpCaptionInfoDestinationSettings Scte27DestinationSettings?: Scte27DestinationSettings constructor(properties: CaptionDestinationSettings) { Object.assign(this, properties) } } export class MsSmoothGroupSettings { SegmentationMode?: Value<string> Destination?: OutputLocationRef EventStopBehavior?: Value<string> FilecacheDuration?: Value<number> CertificateMode?: Value<string> AcquisitionPointId?: Value<string> StreamManifestBehavior?: Value<string> InputLossAction?: Value<string> FragmentLength?: Value<number> RestartDelay?: Value<number> SparseTrackType?: Value<string> EventIdMode?: Value<string> TimestampOffsetMode?: Value<string> AudioOnlyTimecodeControl?: Value<string> NumRetries?: Value<number> TimestampOffset?: Value<string> EventId?: Value<string> SendDelayMs?: Value<number> ConnectionRetryInterval?: Value<number> constructor(properties: MsSmoothGroupSettings) { Object.assign(this, properties) } } export class WavSettings { CodingMode?: Value<string> SampleRate?: Value<number> BitDepth?: Value<number> constructor(properties: WavSettings) { Object.assign(this, properties) } } export class KeyProviderSettings { StaticKeySettings?: StaticKeySettings constructor(properties: KeyProviderSettings) { Object.assign(this, properties) } } export class CdiInputSpecification { Resolution?: Value<string> constructor(properties: CdiInputSpecification) { Object.assign(this, properties) } } export class OutputGroupSettings { HlsGroupSettings?: HlsGroupSettings FrameCaptureGroupSettings?: FrameCaptureGroupSettings MultiplexGroupSettings?: MultiplexGroupSettings ArchiveGroupSettings?: ArchiveGroupSettings MediaPackageGroupSettings?: MediaPackageGroupSettings UdpGroupSettings?: UdpGroupSettings MsSmoothGroupSettings?: MsSmoothGroupSettings RtmpGroupSettings?: RtmpGroupSettings constructor(properties: OutputGroupSettings) { Object.assign(this, properties) } } export class HtmlMotionGraphicsSettings { constructor(properties: HtmlMotionGraphicsSettings) { Object.assign(this, properties) } } export class OutputSettings { MediaPackageOutputSettings?: MediaPackageOutputSettings MsSmoothOutputSettings?: MsSmoothOutputSettings FrameCaptureOutputSettings?: FrameCaptureOutputSettings HlsOutputSettings?: HlsOutputSettings RtmpOutputSettings?: RtmpOutputSettings UdpOutputSettings?: UdpOutputSettings MultiplexOutputSettings?: MultiplexOutputSettings ArchiveOutputSettings?: ArchiveOutputSettings constructor(properties: OutputSettings) { Object.assign(this, properties) } } export class HlsS3Settings { CannedAcl?: Value<string> constructor(properties: HlsS3Settings) { Object.assign(this, properties) } } export class VideoDescription { ScalingBehavior?: Value<string> RespondToAfd?: Value<string> Height?: Value<number> Sharpness?: Value<number> Width?: Value<number> CodecSettings?: VideoCodecSettings Name?: Value<string> constructor(properties: VideoDescription) { Object.assign(this, properties) } } export class BlackoutSlate { NetworkEndBlackout?: Value<string> State?: Value<string> NetworkId?: Value<string> NetworkEndBlackoutImage?: InputLocation BlackoutSlateImage?: InputLocation constructor(properties: BlackoutSlate) { Object.assign(this, properties) } } export class ColorSpacePassthroughSettings { constructor(properties: ColorSpacePassthroughSettings) { Object.assign(this, properties) } } export class HlsMediaStoreSettings { FilecacheDuration?: Value<number> NumRetries?: Value<number> MediaStoreStorageClass?: Value<string> RestartDelay?: Value<number> ConnectionRetryInterval?: Value<number> constructor(properties: HlsMediaStoreSettings) { Object.assign(this, properties) } } export class M3u8Settings { PatInterval?: Value<number> ProgramNum?: Value<number> PcrPeriod?: Value<number> PmtInterval?: Value<number> NielsenId3Behavior?: Value<string> PcrPid?: Value<string> VideoPid?: Value<string> AudioFramesPerPes?: Value<number> TransportStreamId?: Value<number> PmtPid?: Value<string> Scte35Pid?: Value<string> Scte35Behavior?: Value<string> EcmPid?: Value<string> TimedMetadataPid?: Value<string> AudioPids?: Value<string> PcrControl?: Value<string> TimedMetadataBehavior?: Value<string> constructor(properties: M3u8Settings) { Object.assign(this, properties) } } export class AribDestinationSettings { constructor(properties: AribDestinationSettings) { Object.assign(this, properties) } } export class UdpGroupSettings { TimedMetadataId3Frame?: Value<string> TimedMetadataId3Period?: Value<number> InputLossAction?: Value<string> constructor(properties: UdpGroupSettings) { Object.assign(this, properties) } } export class FrameCaptureHlsSettings { constructor(properties: FrameCaptureHlsSettings) { Object.assign(this, properties) } } export class RemixSettings { ChannelsOut?: Value<number> ChannelMappings?: List<AudioChannelMapping> ChannelsIn?: Value<number> constructor(properties: RemixSettings) { Object.assign(this, properties) } } export class TemporalFilterSettings { PostFilterSharpening?: Value<string> Strength?: Value<string> constructor(properties: TemporalFilterSettings) { Object.assign(this, properties) } } export class HlsAkamaiSettings { Salt?: Value<string> FilecacheDuration?: Value<number> NumRetries?: Value<number> Token?: Value<string> RestartDelay?: Value<number> ConnectionRetryInterval?: Value<number> HttpTransferMode?: Value<string> constructor(properties: HlsAkamaiSettings) { Object.assign(this, properties) } } export interface ChannelProperties { InputAttachments?: List<InputAttachment> InputSpecification?: InputSpecification ChannelClass?: Value<string> EncoderSettings?: EncoderSettings Destinations?: List<OutputDestination> Vpc?: VpcOutputSettings CdiInputSpecification?: CdiInputSpecification LogLevel?: Value<string> RoleArn?: Value<string> Tags?: {[key: string]: any} Name?: Value<string> } export default class Channel extends ResourceBase<ChannelProperties> { static HlsInputSettings = HlsInputSettings static DvbSubDestinationSettings = DvbSubDestinationSettings static Rec709Settings = Rec709Settings static VideoCodecSettings = VideoCodecSettings static HlsSettings = HlsSettings static FrameCaptureSettings = FrameCaptureSettings static MotionGraphicsSettings = MotionGraphicsSettings static FrameCaptureCdnSettings = FrameCaptureCdnSettings static InputLossBehavior = InputLossBehavior static MultiplexProgramChannelDestinationSettings = MultiplexProgramChannelDestinationSettings static HlsCdnSettings = HlsCdnSettings static HlsOutputSettings = HlsOutputSettings static EmbeddedPlusScte20DestinationSettings = EmbeddedPlusScte20DestinationSettings static FrameCaptureS3Settings = FrameCaptureS3Settings static ArchiveCdnSettings = ArchiveCdnSettings static Scte27SourceSettings = Scte27SourceSettings static AudioTrackSelection = AudioTrackSelection static EbuTtDDestinationSettings = EbuTtDDestinationSettings static VideoSelectorPid = VideoSelectorPid static FailoverCondition = FailoverCondition static Hdr10Settings = Hdr10Settings static StaticKeySettings = StaticKeySettings static InputLocation = InputLocation static AudioLanguageSelection = AudioLanguageSelection static CaptionRectangle = CaptionRectangle static ArchiveS3Settings = ArchiveS3Settings static SmpteTtDestinationSettings = SmpteTtDestinationSettings static AribSourceSettings = AribSourceSettings static Mp2Settings = Mp2Settings static AudioSilenceFailoverSettings = AudioSilenceFailoverSettings static Fmp4HlsSettings = Fmp4HlsSettings static Scte35SpliceInsert = Scte35SpliceInsert static AudioChannelMapping = AudioChannelMapping static FeatureActivations = FeatureActivations static OutputGroup = OutputGroup static UdpOutputSettings = UdpOutputSettings static Ac3Settings = Ac3Settings static Eac3Settings = Eac3Settings static MediaPackageOutputSettings = MediaPackageOutputSettings static Rec601Settings = Rec601Settings static H264Settings = H264Settings static H264FilterSettings = H264FilterSettings static FailoverConditionSettings = FailoverConditionSettings static Mpeg2Settings = Mpeg2Settings static AudioSelectorSettings = AudioSelectorSettings static UdpContainerSettings = UdpContainerSettings static TimecodeConfig = TimecodeConfig static VideoSelector = VideoSelector static DvbTdtSettings = DvbTdtSettings static HlsGroupSettings = HlsGroupSettings static OutputDestinationSettings = OutputDestinationSettings static AvailConfiguration = AvailConfiguration static TeletextDestinationSettings = TeletextDestinationSettings static H265Settings = H265Settings static AudioCodecSettings = AudioCodecSettings static DvbNitSettings = DvbNitSettings static WebvttDestinationSettings = WebvttDestinationSettings static AacSettings = AacSettings static Scte35TimeSignalApos = Scte35TimeSignalApos static FecOutputSettings = FecOutputSettings static OutputDestination = OutputDestination static AncillarySourceSettings = AncillarySourceSettings static Mpeg2FilterSettings = Mpeg2FilterSettings static CaptionSelector = CaptionSelector static VideoBlackFailoverSettings = VideoBlackFailoverSettings static RtmpOutputSettings = RtmpOutputSettings static RtmpCaptionInfoDestinationSettings = RtmpCaptionInfoDestinationSettings static TtmlDestinationSettings = TtmlDestinationSettings static M2tsSettings = M2tsSettings static HlsWebdavSettings = HlsWebdavSettings static NielsenConfiguration = NielsenConfiguration static GlobalConfiguration = GlobalConfiguration static MediaPackageOutputDestinationSettings = MediaPackageOutputDestinationSettings static AudioOnlyHlsSettings = AudioOnlyHlsSettings static OutputLocationRef = OutputLocationRef static Scte27DestinationSettings = Scte27DestinationSettings static AutomaticInputFailoverSettings = AutomaticInputFailoverSettings static FrameCaptureGroupSettings = FrameCaptureGroupSettings static ArchiveOutputSettings = ArchiveOutputSettings static ArchiveGroupSettings = ArchiveGroupSettings static RawSettings = RawSettings static DvbSdtSettings = DvbSdtSettings static VideoSelectorProgramId = VideoSelectorProgramId static InputAttachment = InputAttachment static InputChannelLevel = InputChannelLevel static StandardHlsSettings = StandardHlsSettings static PassThroughSettings = PassThroughSettings static ArchiveContainerSettings = ArchiveContainerSettings static EmbeddedSourceSettings = EmbeddedSourceSettings static InputSpecification = InputSpecification static FrameCaptureOutputSettings = FrameCaptureOutputSettings static EncoderSettings = EncoderSettings static AvailSettings = AvailSettings static H264ColorSpaceSettings = H264ColorSpaceSettings static MediaPackageGroupSettings = MediaPackageGroupSettings static MultiplexOutputSettings = MultiplexOutputSettings static H265ColorSpaceSettings = H265ColorSpaceSettings static EmbeddedDestinationSettings = EmbeddedDestinationSettings static AvailBlanking = AvailBlanking static InputSettings = InputSettings static AudioNormalizationSettings = AudioNormalizationSettings static MultiplexGroupSettings = MultiplexGroupSettings static InputLossFailoverSettings = InputLossFailoverSettings static AudioSelector = AudioSelector static AudioPidSelection = AudioPidSelection static CaptionLanguageMapping = CaptionLanguageMapping static DvbSubSourceSettings = DvbSubSourceSettings static CaptionSelectorSettings = CaptionSelectorSettings static VideoSelectorSettings = VideoSelectorSettings static VpcOutputSettings = VpcOutputSettings static TeletextSourceSettings = TeletextSourceSettings static CaptionDescription = CaptionDescription static MotionGraphicsConfiguration = MotionGraphicsConfiguration static VideoSelectorColorSpaceSettings = VideoSelectorColorSpaceSettings static Output = Output static NetworkInputSettings = NetworkInputSettings static H265FilterSettings = H265FilterSettings static HlsBasicPutSettings = HlsBasicPutSettings static Scte20PlusEmbeddedDestinationSettings = Scte20PlusEmbeddedDestinationSettings static Scte20SourceSettings = Scte20SourceSettings static AudioTrack = AudioTrack static AudioDescription = AudioDescription static BurnInDestinationSettings = BurnInDestinationSettings static RtmpGroupSettings = RtmpGroupSettings static MsSmoothOutputSettings = MsSmoothOutputSettings static CaptionDestinationSettings = CaptionDestinationSettings static MsSmoothGroupSettings = MsSmoothGroupSettings static WavSettings = WavSettings static KeyProviderSettings = KeyProviderSettings static CdiInputSpecification = CdiInputSpecification static OutputGroupSettings = OutputGroupSettings static HtmlMotionGraphicsSettings = HtmlMotionGraphicsSettings static OutputSettings = OutputSettings static HlsS3Settings = HlsS3Settings static VideoDescription = VideoDescription static BlackoutSlate = BlackoutSlate static ColorSpacePassthroughSettings = ColorSpacePassthroughSettings static HlsMediaStoreSettings = HlsMediaStoreSettings static M3u8Settings = M3u8Settings static AribDestinationSettings = AribDestinationSettings static UdpGroupSettings = UdpGroupSettings static FrameCaptureHlsSettings = FrameCaptureHlsSettings static RemixSettings = RemixSettings static TemporalFilterSettings = TemporalFilterSettings static HlsAkamaiSettings = HlsAkamaiSettings constructor(properties?: ChannelProperties) { super('AWS::MediaLive::Channel', properties || {}) } }
the_stack
import { difference, differenceWith, intersection, isEqual } from 'lodash'; import { join, normalize, relative, resolve } from 'path'; import { DeclarationInfo } from './declarations/DeclarationInfo'; import { ModuleDeclaration } from './declarations/ModuleDeclaration'; import { AllExport } from './exports/AllExport'; import { AssignedExport } from './exports/AssignedExport'; import { NamedExport } from './exports/NamedExport'; import { File } from './resources/File'; import { Module } from './resources/Module'; import { Namespace } from './resources/Namespace'; import { Resource } from './resources/Resource'; import { isExportableDeclaration } from './type-guards/TypescriptHeroGuards'; import { TypescriptParser } from './TypescriptParser'; import { normalizeFilename, normalizePathUri, toPosix } from './utilities/PathHelpers'; /** * Returns the name of the node folder. Is used as the library name for indexing. * (e.g. ./node_modules/webpack returns webpack) * * @param {string} path * @returns {string} */ function getNodeLibraryName(path: string): string { const dirs = path.split(/\/|\\/); const nodeIndex = dirs.indexOf('node_modules'); return normalizeFilename(dirs.slice(nodeIndex + 1).join('/')) .replace(new RegExp(`/(index|${dirs[nodeIndex + 1]}|${dirs[dirs.length - 2]})$`), ''); } /** * Helper type to index all possible resources of the current workspace. */ type Resources = { [name: string]: Resource }; /** * IndexDelta type, is calculated by the declaration index to give an overview, what has changed in the index. * Returns a list of deleted declarations, newly added declarations (with the corresponding infos) and * which declarations have been updated (with all declarations under that name). */ export type IndexDelta = { added: { [declaration: string]: DeclarationInfo[] }; updated: { [declaration: string]: DeclarationInfo[] }; deleted: string[]; }; /** * Interface for file changes. Contains lists of file uri's to the specific action. * * @export * @interface FileChanges */ export interface FileChanges { created: string[]; updated: string[]; deleted: string[]; } /** * Global index of declarations. Contains declarations and origins. * Provides reverse index for search and declaration info for imports. * * @export * @class DeclarationIndex */ export class DeclarationIndex { private building: boolean = false; /** * Hash of parsed resources. Contains all parsed files / namespaces / declarations * of the current workspace. * * @private * @type {Resources} * @memberof DeclarationIndex */ private parsedResources: Resources = Object.create(null); /** * Declaration index. Reverse index from a name to many declarations assotiated to the name. * * @private * @type {({ [declaration: string]: DeclarationInfo[] } | undefined)} * @memberof DeclarationIndex */ private _index: { [declaration: string]: DeclarationInfo[] } | undefined; /** * Indicator if the first index was loaded and calculated or not. * * @readonly * @type {boolean} * @memberof DeclarationIndex */ public get indexReady(): boolean { return this._index !== undefined; // && this._indexWithBarrels !== undefined; } /** * Reverse index of the declarations. * * @readonly * @type {({ [declaration: string]: DeclarationInfo[] } | undefined)} * @memberof DeclarationIndex */ public get index(): { [declaration: string]: DeclarationInfo[] } | undefined { return this._index; } /** * List of all declaration information. Contains the typescript declaration and the * "from" information (from where the symbol is imported). * * @readonly * @type {DeclarationInfo[]} * @memberof DeclarationIndex */ public get declarationInfos(): DeclarationInfo[] { return Object .keys(this.index!) .sort() .reduce((all, key) => all.concat(this.index![key]), <DeclarationInfo[]>[]); } constructor(private parser: TypescriptParser, private rootPath: string) { } /** * Calculates the differences between two indices. Calculates removed, added and updated declarations. * The updated declarations are calculated and all declarations that the new index contains are inserted in the list. * * @static * @param {{ [declaration: string]: DeclarationInfo[] }} oldIndex * @param {{ [declaration: string]: DeclarationInfo[] }} newIndex * @returns {IndexDelta} * @memberof DeclarationIndex */ public static calculateIndexDelta( oldIndex: { [declaration: string]: DeclarationInfo[] }, newIndex: { [declaration: string]: DeclarationInfo[] }, ): IndexDelta { const oldKeys = Object.keys(oldIndex); const newKeys = Object.keys(newIndex); return { added: difference(newKeys, oldKeys).reduce( (obj, currentKey) => { obj[currentKey] = newIndex[currentKey]; return obj; }, {} as { [declaration: string]: DeclarationInfo[] }, ), updated: intersection(oldKeys, newKeys).reduce( (obj, currentKey) => { const old = oldIndex[currentKey]; const neu = newIndex[currentKey]; if (differenceWith(neu, old, isEqual).length > 0 || differenceWith(old, neu, isEqual).length > 0) { obj[currentKey] = neu; } return obj; }, {} as { [declaration: string]: DeclarationInfo[] }, ), deleted: difference(oldKeys, newKeys), }; } /** * Resets the whole index. Does delete everything. Period. * Is useful for unit testing or similar things. * * @memberof DeclarationIndex */ public reset(): void { this.parsedResources = Object.create(null); this._index = undefined; } /** * Tells the index to build a new index. * Can be canceled with a cancellationToken. * * @param {string[]} filePathes * @returns {Promise<void>} * * @memberof DeclarationIndex */ public async buildIndex(filePathes: string[]): Promise<void> { if (this.building) { return; } try { this.building = true; const parsed = await this.parser.parseFiles(filePathes, this.rootPath); this.parsedResources = await this.parseResources(parsed); this._index = await this.createIndex(this.parsedResources); } catch (e) { throw e; } finally { this.building = false; } } /** * Is called when file events happen. Does reindex for the changed files and creates a new index. * Returns the differences for the new index. * * @param {FileEvent[]} changes * @returns {Promise<IndexDelta>} * * @memberof DeclarationIndex */ public async reindexForChanges(changes: FileChanges): Promise<IndexDelta> { const rebuildResources: string[] = []; const removeResources: string[] = []; const rebuildFiles: string[] = []; for (const change of changes.deleted) { const filePath = normalizePathUri(change); const resource = '/' + normalizeFilename(relative(this.rootPath, filePath)); if (removeResources.indexOf(resource) < 0) { removeResources.push(resource); } for (const file of this.getExportedResources(resource)) { if (rebuildFiles.indexOf(file) < 0) { rebuildFiles.push(file); } } } for (const change of (changes.created || []).concat(changes.updated)) { const filePath = normalizePathUri(change); const resource = '/' + normalizeFilename(relative(this.rootPath, filePath)); if (rebuildResources.indexOf(resource) < 0) { rebuildResources.push(resource); } if (rebuildFiles.indexOf(filePath) < 0) { rebuildFiles.push(filePath); } for (const file of this.getExportedResources(resource)) { if (rebuildFiles.indexOf(file) < 0) { rebuildFiles.push(file); } } } const resources = await this.parseResources( await this.parser.parseFiles(rebuildFiles, this.rootPath), ); for (const del of removeResources) { delete this.parsedResources[del]; } for (const key of Object.keys(resources)) { this.parsedResources[key] = resources[key]; } const old = this._index || {}; this._index = await this.createIndex(this.parsedResources); return DeclarationIndex.calculateIndexDelta(old, this._index); } /** * Returns a list of files that export a certain resource (declaration). * * @private * @param {string} resourceToCheck * @returns {string[]} * * @memberof DeclarationIndex */ private getExportedResources(resourceToCheck: string): string[] { const resources: string[] = []; Object .keys(this.parsedResources) .forEach((key) => { const resource = this.parsedResources[key]; if (resource instanceof File && this.doesExportResource(resource, resourceToCheck)) { resources.push(resource.filePath); } }); return resources; } /** * Checks if a file does export another resource. * (i.e. export ... from ...) * * @private * @param {File} resource The file that is checked * @param {string} resourcePath The resource that is searched for * @returns {boolean} * * @memberof DeclarationIndex */ private doesExportResource(resource: File, resourcePath: string): boolean { let exportsResource = false; for (const ex of resource.exports) { if (exportsResource) { break; } if (ex instanceof AllExport || ex instanceof NamedExport) { const exported = '/' + toPosix(relative(this.rootPath, normalize(join(resource.parsedPath.dir, ex.from)))); exportsResource = exported === resourcePath; } } return exportsResource; } /** * Does parse the resources (symbols and declarations) of a given file. * Can be cancelled with the token. * * @private * @param {File[]} [files=[]] * @returns {Promise<Resources>} * * @memberof DeclarationIndex */ private async parseResources(files: File[] = []): Promise<Resources> { const parsedResources: Resources = Object.create(null); for (const file of files) { if (file.filePath.indexOf('typings') > -1 || file.filePath.indexOf('node_modules/@types') > -1) { for (const resource of file.resources) { parsedResources[resource.identifier] = resource; } } else if (file.filePath.indexOf('node_modules') > -1) { const libname = getNodeLibraryName(file.filePath); parsedResources[libname] = file; } else { parsedResources[file.identifier] = file; } } for (const key of Object.keys(parsedResources).sort((k1, k2) => k2.length - k1.length)) { const resource = parsedResources[key]; resource.declarations = resource.declarations.filter( o => isExportableDeclaration(o) && o.isExported, ); this.processResourceExports(parsedResources, resource); } return parsedResources; } /** * Creates a reverse index out of the give resources. * Can be cancelled with the token. * * @private * @param {Resources} resources * @returns {Promise<ResourceIndex>} * * @memberof DeclarationIndex */ private async createIndex(resources: Resources): Promise<{ [declaration: string]: DeclarationInfo[] }> { // Use an empty object without a prototype, so that "toString" (for example) can be indexed // Thanks to @gund in https://github.com/buehler/typescript-hero/issues/79 const index: { [declaration: string]: DeclarationInfo[] } = Object.create(null); for (const key of Object.keys(resources)) { const resource = resources[key]; if (resource instanceof Namespace || resource instanceof Module) { if (!index[resource.name]) { index[resource.name] = []; } index[resource.name].push(new DeclarationInfo( new ModuleDeclaration(resource.getNamespaceAlias(), resource.start, resource.end), resource.name, )); } for (const declaration of resource.declarations) { if (!index[declaration.name]) { index[declaration.name] = []; } const from = key.replace(/\/index$/, '') || '/'; if (!index[declaration.name].some( o => o.declaration.constructor === declaration.constructor && o.from === from, )) { index[declaration.name].push(new DeclarationInfo(declaration, from)); } } } return index; } /** * Process all exports of a the parsed resources. Does move the declarations accordingly to their * export nature. * * @private * @param {Resources} parsedResources * @param {Resource} resource * @param {Resource[]} [processedResources=[]] * @returns {void} * * @memberof DeclarationIndex */ private processResourceExports( parsedResources: Resources, resource: Resource, processedResources: Resource[] = [], ): void { if (processedResources.indexOf(resource) >= 0 || resource.exports.length === 0) { return; } processedResources.push(resource); for (const ex of resource.exports) { if (resource instanceof File && (ex instanceof NamedExport || ex instanceof AllExport)) { if (!ex.from) { return; } let sourceLib = resolve(resource.parsedPath.dir, ex.from); if (sourceLib.indexOf('node_modules') > -1) { sourceLib = getNodeLibraryName(sourceLib); } else { sourceLib = '/' + normalizeFilename(relative(this.rootPath, sourceLib)); } if (!parsedResources[sourceLib]) { return; } const exportedLib = parsedResources[sourceLib]; this.processResourceExports(parsedResources, exportedLib, processedResources); if (ex instanceof AllExport) { this.processAllFromExport(resource, exportedLib); } else { this.processNamedFromExport(ex, resource, exportedLib); } } else { if (ex instanceof AssignedExport) { for (const lib of ex.exported.filter(o => !isExportableDeclaration(o))) { this.processResourceExports(parsedResources, lib as Resource, processedResources); } this.processAssignedExport(ex, resource); } else if (ex instanceof NamedExport && ex.from && parsedResources[ex.from]) { this.processResourceExports( parsedResources, parsedResources[ex.from], processedResources, ); this.processNamedFromExport(ex, resource, parsedResources[ex.from]); } } } } /** * Processes an all export, does move the declarations accordingly. * (i.e. export * from './myFile') * * @private * @param {Resource} exportingLib * @param {Resource} exportedLib * * @memberof DeclarationIndex */ private processAllFromExport(exportingLib: Resource, exportedLib: Resource): void { exportingLib.declarations.push(...exportedLib.declarations); exportedLib.declarations = []; } /** * Processes a named export, does move the declarations accordingly. * (i.e. export {MyClass} from './myFile') * * @private * @param {NamedExport} tsExport * @param {Resource} exportingLib * @param {Resource} exportedLib * * @memberof DeclarationIndex */ private processNamedFromExport( tsExport: NamedExport, exportingLib: Resource, exportedLib: Resource, ): void { exportedLib.declarations .forEach((o) => { if (!tsExport.specifiers) { return; } const ex = tsExport.specifiers.find(s => s.specifier === o.name); if (!ex) { return; } exportedLib.declarations.splice(exportedLib.declarations.indexOf(o), 1); if (ex.alias) { o.name = ex.alias; } exportingLib.declarations.push(o); }); } /** * Processes an assigned export, does move the declarations accordingly. * (i.e. export = namespaceName) * * @private * @param {AssignedExport} tsExport * @param {Resource} exportingLib * * @memberof DeclarationIndex */ private processAssignedExport( tsExport: AssignedExport, exportingLib: Resource, ): void { tsExport.exported.forEach((exported) => { if (isExportableDeclaration(exported)) { exportingLib.declarations.push(exported); } else { exportingLib.declarations.push( ...exported.declarations.filter( o => isExportableDeclaration(o) && o.isExported, ), ); exported.declarations = []; } }); } }
the_stack
import * as cdk from '@aws-cdk/core'; import s3 = require('@aws-cdk/aws-s3'); import iam = require('@aws-cdk/aws-iam'); import dynamodb = require('@aws-cdk/aws-dynamodb'); import lambda = require('@aws-cdk/aws-lambda'); import event_sources = require('@aws-cdk/aws-lambda-event-sources'); import cognito = require('@aws-cdk/aws-cognito'); import { AuthorizationType, PassthroughBehavior } from '@aws-cdk/aws-apigateway'; import { CfnOutput } from "@aws-cdk/core"; import { Duration } from '@aws-cdk/core'; import apigw = require('@aws-cdk/aws-apigateway'); import s3deploy = require('@aws-cdk/aws-s3-deployment'); import { HttpMethods } from '@aws-cdk/aws-s3'; import sqs = require('@aws-cdk/aws-sqs'); import s3n = require('@aws-cdk/aws-s3-notifications'); const imageBucketName = "cdk-rekn-imgagebucket" const resizedBucketName = imageBucketName + "-resized" const websiteBucketName = "cdk-rekn-publicbucket" export class AwsdevhourStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // ===================================================================================== // Image Bucket // ===================================================================================== const imageBucket = new s3.Bucket(this, imageBucketName, { removalPolicy: cdk.RemovalPolicy.DESTROY }); new cdk.CfnOutput(this, 'imageBucket', { value: imageBucket.bucketName }); const imageBucketArn = imageBucket.bucketArn; imageBucket.addCorsRule({ allowedMethods: [HttpMethods.GET, HttpMethods.PUT], allowedOrigins: ["*"], allowedHeaders: ["*"], maxAge: 3000 }); // ===================================================================================== // Thumbnail Bucket // ===================================================================================== const resizedBucket = new s3.Bucket(this, resizedBucketName, { removalPolicy: cdk.RemovalPolicy.DESTROY }); new cdk.CfnOutput(this, 'resizedBucket', {value: resizedBucket.bucketName}); const resizedBucketArn = resizedBucket.bucketArn; resizedBucket.addCorsRule({ allowedMethods: [HttpMethods.GET, HttpMethods.PUT], allowedOrigins: ["*"], allowedHeaders: ["*"], maxAge: 3000 }); // ===================================================================================== // Construct to create our Amazon S3 Bucket to host our website // ===================================================================================== const webBucket = new s3.Bucket(this, websiteBucketName, { websiteIndexDocument: 'index.html', websiteErrorDocument: 'index.html', removalPolicy: cdk.RemovalPolicy.DESTROY // publicReadAccess: true, }); webBucket.addToResourcePolicy(new iam.PolicyStatement({ actions: ['s3:GetObject'], resources: [webBucket.arnForObjects('*')], principals: [new iam.AnyPrincipal()], conditions: { 'IpAddress': { 'aws:SourceIp': [ '*.*.*.*/*' // Please change it to your IP address or from your allowed list ] } } })) new cdk.CfnOutput(this, 'bucketURL', { value: webBucket.bucketWebsiteDomainName }); // ===================================================================================== // Deploy site contents to S3 Bucket // ===================================================================================== new s3deploy.BucketDeployment(this, 'DeployWebsite', { sources: [ s3deploy.Source.asset('./public') ], destinationBucket: webBucket }); // ===================================================================================== // Amazon DynamoDB table for storing image labels // ===================================================================================== const table = new dynamodb.Table(this, 'ImageLabels', { partitionKey: { name: 'image', type: dynamodb.AttributeType.STRING }, removalPolicy: cdk.RemovalPolicy.DESTROY }); new cdk.CfnOutput(this, 'ddbTable', { value: table.tableName }); // ===================================================================================== // Building our AWS Lambda Function; compute for our serverless microservice // ===================================================================================== const layer = new lambda.LayerVersion(this, 'pil', { code: lambda.Code.fromAsset('reklayer'), compatibleRuntimes: [lambda.Runtime.PYTHON_3_7], license: 'Apache-2.0', description: 'A layer to enable the PIL library in our Rekognition Lambda', }); ​ // ===================================================================================== // Building our AWS Lambda Function; compute for our serverless microservice // ===================================================================================== const rekFn = new lambda.Function(this, 'rekognitionFunction', { code: lambda.Code.fromAsset('rekognitionlambda'), runtime: lambda.Runtime.PYTHON_3_7, handler: 'index.handler', timeout: Duration.seconds(30), memorySize: 1024, layers: [layer], environment: { "TABLE": table.tableName, "BUCKET": imageBucket.bucketName, "RESIZEDBUCKET": resizedBucket.bucketName }, }); imageBucket.grantRead(rekFn); resizedBucket.grantPut(rekFn); table.grantWriteData(rekFn); rekFn.addToRolePolicy(new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['rekognition:DetectLabels'], resources: ['*'] })); // ===================================================================================== // Lambda for Synchronous Front End // ===================================================================================== ​ const serviceFn = new lambda.Function(this, 'serviceFunction', { code: lambda.Code.fromAsset('servicelambda'), runtime: lambda.Runtime.PYTHON_3_7, handler: 'index.handler', environment: { "TABLE": table.tableName, "BUCKET": imageBucket.bucketName, "RESIZEDBUCKET": resizedBucket.bucketName }, }); ​ imageBucket.grantWrite(serviceFn); resizedBucket.grantWrite(serviceFn); table.grantReadWriteData(serviceFn); const api = new apigw.LambdaRestApi(this, 'imageAPI', { defaultCorsPreflightOptions: { allowOrigins: apigw.Cors.ALL_ORIGINS, allowMethods: apigw.Cors.ALL_METHODS }, handler: serviceFn, proxy: false, }); // ===================================================================================== // This construct builds a new Amazon API Gateway with AWS Lambda Integration // ===================================================================================== const lambdaIntegration = new apigw.LambdaIntegration(serviceFn, { proxy: false, requestParameters: { 'integration.request.querystring.action': 'method.request.querystring.action', 'integration.request.querystring.key': 'method.request.querystring.key' }, requestTemplates: { 'application/json': JSON.stringify({ action: "$util.escapeJavaScript($input.params('action'))", key: "$util.escapeJavaScript($input.params('key'))" }) }, passthroughBehavior: PassthroughBehavior.WHEN_NO_TEMPLATES, integrationResponses: [ { statusCode: "200", responseParameters: { // We can map response parameters // - Destination parameters (the key) are the response parameters (used in mappings) // - Source parameters (the value) are the integration response parameters or expressions 'method.response.header.Access-Control-Allow-Origin': "'*'" } }, { // For errors, we check if the error message is not empty, get the error data selectionPattern: "(\n|.)+", statusCode: "500", responseParameters: { 'method.response.header.Access-Control-Allow-Origin': "'*'" } } ], }); // ===================================================================================== // Cognito User Pool Authentication // ===================================================================================== const userPool = new cognito.UserPool(this, "UserPool", { selfSignUpEnabled: true, // Allow users to sign up autoVerify: { email: true }, // Verify email addresses by sending a verification code signInAliases: { username: true, email: true }, // Set email as an alias }); const userPoolClient = new cognito.UserPoolClient(this, "UserPoolClient", { userPool, generateSecret: false, // Don't need to generate secret for web app running on browsers }); const identityPool = new cognito.CfnIdentityPool(this, "ImageRekognitionIdentityPool", { allowUnauthenticatedIdentities: false, // Don't allow unathenticated users cognitoIdentityProviders: [ { clientId: userPoolClient.userPoolClientId, providerName: userPool.userPoolProviderName, }, ], }); const auth = new apigw.CfnAuthorizer(this, 'APIGatewayAuthorizer', { name: 'customer-authorizer', identitySource: 'method.request.header.Authorization', providerArns: [userPool.userPoolArn], restApiId: api.restApiId, type: AuthorizationType.COGNITO, }); const authenticatedRole = new iam.Role(this, "ImageRekognitionAuthenticatedRole", { assumedBy: new iam.FederatedPrincipal( "cognito-identity.amazonaws.com", { StringEquals: { "cognito-identity.amazonaws.com:aud": identityPool.ref, }, "ForAnyValue:StringLike": { "cognito-identity.amazonaws.com:amr": "authenticated", }, }, "sts:AssumeRoleWithWebIdentity" ), }); // IAM policy granting users permission to upload, download and delete their own pictures authenticatedRole.addToPolicy( new iam.PolicyStatement({ actions: [ "s3:GetObject", "s3:PutObject" ], effect: iam.Effect.ALLOW, resources: [ imageBucketArn + "/private/${cognito-identity.amazonaws.com:sub}/*", imageBucketArn + "/private/${cognito-identity.amazonaws.com:sub}", resizedBucketArn + "/private/${cognito-identity.amazonaws.com:sub}/*", resizedBucketArn + "/private/${cognito-identity.amazonaws.com:sub}" ], }) ); // IAM policy granting users permission to list their pictures authenticatedRole.addToPolicy( new iam.PolicyStatement({ actions: ["s3:ListBucket"], effect: iam.Effect.ALLOW, resources: [ imageBucketArn, resizedBucketArn ], conditions: {"StringLike": {"s3:prefix": ["private/${cognito-identity.amazonaws.com:sub}/*"]}} }) ); new cognito.CfnIdentityPoolRoleAttachment(this, "IdentityPoolRoleAttachment", { identityPoolId: identityPool.ref, roles: { authenticated: authenticatedRole.roleArn }, }); // Export values of Cognito new CfnOutput(this, "UserPoolId", { value: userPool.userPoolId, }); new CfnOutput(this, "AppClientId", { value: userPoolClient.userPoolClientId, }); new CfnOutput(this, "IdentityPoolId", { value: identityPool.ref, }); // ===================================================================================== // API Gateway // ===================================================================================== const imageAPI = api.root.addResource('images'); ​ // GET /images imageAPI.addMethod('GET', lambdaIntegration, { authorizationType: AuthorizationType.COGNITO, authorizer: { authorizerId: auth.ref }, requestParameters: { 'method.request.querystring.action': true, 'method.request.querystring.key': true }, methodResponses: [ { statusCode: "200", responseParameters: { 'method.response.header.Access-Control-Allow-Origin': true, }, }, { statusCode: "500", responseParameters: { 'method.response.header.Access-Control-Allow-Origin': true, }, } ] }); // DELETE /images imageAPI.addMethod('DELETE', lambdaIntegration, { authorizationType: AuthorizationType.COGNITO, authorizer: { authorizerId: auth.ref }, requestParameters: { 'method.request.querystring.action': true, 'method.request.querystring.key': true }, methodResponses: [ { statusCode: "200", responseParameters: { 'method.response.header.Access-Control-Allow-Origin': true, }, }, { statusCode: "500", responseParameters: { 'method.response.header.Access-Control-Allow-Origin': true, }, } ] }); // ===================================================================================== // Building SQS queue and DeadLetter Queue // ===================================================================================== const dlQueue = new sqs.Queue(this, 'ImageDLQueue', { queueName: 'ImageDLQueue' }) ​ const queue = new sqs.Queue(this, 'ImageQueue', { queueName: 'ImageQueue', visibilityTimeout: cdk.Duration.seconds(30), receiveMessageWaitTime: cdk.Duration.seconds(20), deadLetterQueue: { maxReceiveCount: 2, queue: dlQueue } }); // ===================================================================================== // Building S3 Bucket Create Notification to SQS // ===================================================================================== imageBucket.addObjectCreatedNotification(new s3n.SqsDestination(queue), { prefix: 'private/' }) // ===================================================================================== // Lambda(Rekognition) to consume messages from SQS // ===================================================================================== rekFn.addEventSource(new event_sources.SqsEventSource(queue)); } }
the_stack
import { Menu, webContents, app, BrowserWindow, MenuItem } from 'electron'; import { defaultTabOptions } from '~/constants/tabs'; import { viewSource, saveAs, printPage } from './common-actions'; import { WEBUI_BASE_URL, WEBUI_URL_SUFFIX } from '~/constants/files'; import { AppWindow } from '../windows'; import { Application } from '../application'; import { showMenuDialog } from '../dialogs/menu'; import { getWebUIURL } from '~/common/webui'; const isMac = process.platform === 'darwin'; const createMenuItem = ( shortcuts: string[], action: ( window: AppWindow, menuItem: MenuItem, shortcutIndex: number, ) => void, label: string = null, ) => { const result: any = shortcuts.map((shortcut, key) => ({ accelerator: shortcut, visible: label != null && key === 0, label: label != null && key === 0 ? label : '', click: (menuItem: MenuItem, browserWindow: BrowserWindow) => action( Application.instance.windows.list.find( (x) => x.win.id === browserWindow.id, ), menuItem, key, ), })); return result; }; export const getMainMenu = () => { const template: any = [ ...(isMac ? [ { label: app.name, submenu: [ { role: 'about' }, { type: 'separator' }, { role: 'services' }, { type: 'separator' }, { role: 'hide' }, { role: 'hideothers' }, { role: 'unhide' }, { type: 'separator' }, { role: 'quit' }, ], }, ] : []), { label: 'File', submenu: [ ...createMenuItem( ['CmdOrCtrl+N'], () => { Application.instance.windows.open(); }, 'New window', ), ...createMenuItem( ['CmdOrCtrl+Shift+N'], () => { Application.instance.windows.open(true); }, 'New incognito window', ), ...createMenuItem( ['CmdOrCtrl+T'], (window) => { window.viewManager.create(defaultTabOptions); }, 'New tab', ), ...createMenuItem( ['CmdOrCtrl+Shift+T'], (window) => { window.send('revert-closed-tab'); }, 'Revert closed tab', ), { type: 'separator', }, ...createMenuItem( ['CmdOrCtrl+Shift+W'], (window) => { window.win.close(); }, 'Close window', ), ...createMenuItem( ['CmdOrCtrl+W', 'CmdOrCtrl+F4'], (window) => { window.send('remove-tab', window.viewManager.selectedId); }, 'Close tab', ), { type: 'separator', }, ...createMenuItem( ['CmdOrCtrl+S'], () => { saveAs(); }, 'Save webpage as...', ), { type: 'separator', }, ...createMenuItem( ['CmdOrCtrl+P'], () => { printPage(); }, 'Print', ), // Hidden items // Focus address bar ...createMenuItem(['Ctrl+Space', 'CmdOrCtrl+L', 'Alt+D', 'F6'], () => { Application.instance.dialogs .getPersistent('search') .show(Application.instance.windows.current.win); }), // Toggle menu ...createMenuItem(['Alt+F', 'Alt+E'], () => { Application.instance.windows.current.send('show-menu-dialog'); }), ], }, { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, ...(isMac ? [ { role: 'pasteAndMatchStyle' }, { role: 'delete' }, { role: 'selectAll' }, { type: 'separator' }, { label: 'Speech', submenu: [{ role: 'startspeaking' }, { role: 'stopspeaking' }], }, ] : [{ role: 'delete' }, { type: 'separator' }, { role: 'selectAll' }]), { type: 'separator' }, ...createMenuItem( ['CmdOrCtrl+F'], () => { Application.instance.windows.current.send('find'); }, 'Find in page', ), ], }, { label: 'View', submenu: [ ...createMenuItem( ['CmdOrCtrl+R', 'F5'], () => { Application.instance.windows.current.viewManager.selected.webContents.reload(); }, 'Reload', ), ...createMenuItem( ['CmdOrCtrl+Shift+R', 'Shift+F5'], () => { Application.instance.windows.current.viewManager.selected.webContents.reloadIgnoringCache(); }, 'Reload ignoring cache', ), ], }, { label: 'History', submenu: [ // TODO: Homepage - Ctrl+Shift+H ...createMenuItem( isMac ? ['Cmd+[', 'Cmd+Left'] : ['Alt+Left'], () => { const { selected, } = Application.instance.windows.current.viewManager; if (selected) { selected.webContents.goBack(); } }, 'Go back', ), ...createMenuItem( isMac ? ['Cmd+]', 'Cmd+Right'] : ['Alt+Right'], () => { const { selected, } = Application.instance.windows.current.viewManager; if (selected) { selected.webContents.goForward(); } }, 'Go forward', ), // { type: 'separator' } // TODO: list last closed tabs // { type: 'separator' } // TODO: list last visited { type: 'separator' }, ...createMenuItem( isMac ? ['Cmd+Y'] : ['Ctrl+H'], () => { Application.instance.windows.current.viewManager.create({ url: getWebUIURL('history'), active: true, }); }, 'Manage history', ), ], }, { label: 'Bookmarks', submenu: [ ...createMenuItem( isMac ? ['Cmd+Option+B'] : ['CmdOrCtrl+Shift+O'], () => { Application.instance.windows.current.viewManager.create({ url: getWebUIURL('bookmarks'), active: true, }); }, 'Manage bookmarks', ), ...createMenuItem( ['CmdOrCtrl+Shift+B'], () => { const { bookmarksBar } = Application.instance.settings.object; Application.instance.settings.updateSettings({ bookmarksBar: !bookmarksBar, }); }, 'Toggle bookmarks bar', ), ...createMenuItem( ['CmdOrCtrl+D'], () => { Application.instance.windows.current.webContents.send( 'show-add-bookmark-dialog', ); }, 'Add this website to bookmarks', ), // { type: 'separator' } // TODO: list bookmarks ], }, { label: 'Tools', submenu: [ { label: 'Developer', submenu: [ ...createMenuItem( ['CmdOrCtrl+U'], () => { viewSource(); }, 'View source', ), ...createMenuItem( ['CmdOrCtrl+Shift+I', 'CmdOrCtrl+Shift+J', 'F12'], () => { setTimeout(() => { Application.instance.windows.current.viewManager.selected.webContents.toggleDevTools(); }); }, 'Developer tools...', ), // Developer tools (current webContents) (dev) ...createMenuItem(['CmdOrCtrl+Shift+F12'], () => { setTimeout(() => { webContents .getFocusedWebContents() .openDevTools({ mode: 'detach' }); }); }), ], }, ], }, { label: 'Tab', submenu: [ ...createMenuItem( isMac ? ['Cmd+Option+Right'] : ['Ctrl+Tab', 'Ctrl+PageDown'], () => { Application.instance.windows.current.webContents.send( 'select-next-tab', ); }, 'Select next tab', ), ...createMenuItem( isMac ? ['Cmd+Option+Left'] : ['Ctrl+Shift+Tab', 'Ctrl+PageUp'], () => { Application.instance.windows.current.webContents.send( 'select-previous-tab', ); }, 'Select previous tab', ), ], }, { label: 'Window', submenu: [ { role: 'minimize' }, { role: 'togglefullscreen' }, { role: 'zoom' }, ...(isMac ? [ { type: 'separator' }, { role: 'front' }, { type: 'separator' }, { role: 'window' }, ] : [{ role: 'close', accelerator: '' }]), { type: 'separator' }, { label: 'Always on top', type: 'checkbox', checked: false, click(menuItem: MenuItem, browserWindow: BrowserWindow) { browserWindow.setAlwaysOnTop(!browserWindow.isAlwaysOnTop()); menuItem.checked = browserWindow.isAlwaysOnTop(); }, }, ], }, ]; // Ctrl+1 - Ctrl+8 template[0].submenu = template[0].submenu.concat( createMenuItem( Array.from({ length: 8 }, (v, k) => k + 1).map((i) => `CmdOrCtrl+${i}`), (window, menuItem, i) => { Application.instance.windows.current.webContents.send( 'select-tab-index', i, ); }, ), ); // Ctrl+9 template[0].submenu = template[0].submenu.concat( createMenuItem(['CmdOrCtrl+9'], () => { Application.instance.windows.current.webContents.send('select-last-tab'); }), ); // Ctrl+numadd - Ctrl+= template[0].submenu = template[0].submenu.concat( createMenuItem(['CmdOrCtrl+numadd', 'CmdOrCtrl+='], () => { Application.instance.windows.current.viewManager.changeZoom('in'); }), ); // Ctrl+numsub - Ctrl+- template[0].submenu = template[0].submenu.concat( createMenuItem(['CmdOrCtrl+numsub', 'CmdOrCtrl+-'], () => { Application.instance.windows.current.viewManager.changeZoom('out'); }), ); // Ctrl+0 template[0].submenu = template[0].submenu.concat( createMenuItem(['CmdOrCtrl+0', 'CmdOrCtrl+num0'], () => { Application.instance.windows.current.viewManager.resetZoom(); }), ); return Menu.buildFromTemplate(template); };
the_stack
* Part of Jupyterlab status bar defaults. */ import React from 'react'; import { TextItem } from '../component/text'; import { JupyterLabPlugin, JupyterLab, ApplicationShell } from '@jupyterlab/application'; import { INotebookTracker, NotebookPanel } from '@jupyterlab/notebook'; import { VDomRenderer, VDomModel, ReactElementWidget } from '@jupyterlab/apputils'; import { CodeEditor } from '@jupyterlab/codeeditor'; import { IEditorTracker, FileEditor } from '@jupyterlab/fileeditor'; import { ISignal } from '@phosphor/signaling'; import { Cell, CodeCell } from '@jupyterlab/cells'; import { IDocumentWidget } from '@jupyterlab/docregistry'; import { IDisposable } from '@phosphor/disposable'; import { Token } from '@phosphor/coreutils'; import { Widget } from '@phosphor/widgets'; import { IStatusContext } from '../contexts'; import { showPopup, Popup } from '../component/hover'; import { IDefaultsManager } from './manager'; import { interactiveItem } from '../style/statusBar'; import { lineFormWrapper, lineFormInput, lineFormSearch, lineFormWrapperFocusWithin, lineFormCaption, lineFormButton } from '../style/lineForm'; import { classes } from 'typestyle/lib'; import { Message } from '@phosphor/messaging'; import { IConsoleTracker, ConsolePanel, CodeConsole } from '@jupyterlab/console'; namespace LineForm { export interface IProps { handleSubmit: (value: number) => void; currentLine: number; maxLine: number; } export interface IState { value: string; hasFocus: boolean; } } class LineForm extends React.Component<LineForm.IProps, LineForm.IState> { state = { value: '', hasFocus: false }; private _handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ value: event.currentTarget.value }); }; private _handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const value = parseInt(this._textInput!.value, 10); if ( !isNaN(value) && isFinite(value) && 1 <= value && value <= this.props.maxLine ) { this.props.handleSubmit(value); } return false; }; private _handleFocus = () => { this.setState({ hasFocus: true }); }; private _handleBlur = () => { this.setState({ hasFocus: false }); }; componentDidMount() { this._textInput!.focus(); } render() { return ( <div className={lineFormSearch}> <form name="lineColumnForm" onSubmit={this._handleSubmit} noValidate > <div className={classes( lineFormWrapper, 'p-lineForm-wrapper', this.state.hasFocus ? lineFormWrapperFocusWithin : undefined )} > <input type="text" className={lineFormInput} onChange={this._handleChange} onFocus={this._handleFocus} onBlur={this._handleBlur} value={this.state.value} ref={input => { this._textInput = input; }} /> <input type="submit" className={classes( lineFormButton, 'lineForm-enter-icon' )} value="" /> </div> <label className={lineFormCaption}> Go to line number between 1 and {this.props.maxLine} </label> </form> </div> ); } private _textInput: HTMLInputElement | null = null; } namespace LineColComponent { export interface IProps { line: number; column: number; handleClick: () => void; } } // tslint:disable-next-line:variable-name const LineColComponent = ( props: LineColComponent.IProps ): React.ReactElement<LineColComponent.IProps> => { return ( <TextItem onClick={props.handleClick} source={`Ln ${props.line}, Col ${props.column}`} /> ); }; class LineCol extends VDomRenderer<LineCol.Model> implements ILineCol { constructor(opts: LineCol.IOptions) { super(); this._notebookTracker = opts.notebookTracker; this._editorTracker = opts.editorTracker; this._consoleTracker = opts.consoleTracker; this._shell = opts.shell; this._notebookTracker.activeCellChanged.connect( this._onActiveCellChange ); this._shell.currentChanged.connect(this._onMainAreaCurrentChange); this.model = new LineCol.Model( this._getFocusedEditor(this._shell.currentWidget) ); this.node.title = 'Go to line number'; this.addClass(interactiveItem); } render(): React.ReactElement<LineColComponent.IProps> | null { if (this.model === null) { return null; } else { return ( <LineColComponent line={this.model.line} column={this.model.column} handleClick={this._handleClick} /> ); } } dispose() { super.dispose(); this._notebookTracker.activeCellChanged.disconnect( this._onActiveCellChange ); this._shell.currentChanged.disconnect(this._onMainAreaCurrentChange); } protected onUpdateRequest(msg: Message) { this.model!.editor = this._getFocusedEditor(this._shell.currentWidget); super.onUpdateRequest(msg); } private _handleClick = () => { if (this._popup) { this._popup.dispose(); } const body = new ReactElementWidget( ( <LineForm handleSubmit={this._handleSubmit} currentLine={this.model!.line} maxLine={this.model!.editor!.lineCount} /> ) ); this._popup = showPopup({ body: body, anchor: this, align: 'right' }); }; private _handleSubmit = (value: number) => { this.model!.editor!.setCursorPosition({ line: value - 1, column: 0 }); this._popup!.dispose(); this.model!.editor!.focus(); }; private _onPromptCellCreated = (_console: CodeConsole, cell: CodeCell) => { this.model!.editor = cell.editor; }; private _onActiveCellChange = ( _tracker: INotebookTracker, cell: Cell | null ) => { this.model!.editor = cell && cell.editor; }; private _getFocusedEditor(val: Widget | null): CodeEditor.IEditor | null { if (val === null) { return null; } else { if (this._notebookTracker.has(val)) { const activeCell = (val as NotebookPanel).content.activeCell; if (activeCell === null) { return null; } else { return activeCell!.editor; } } else if (this._editorTracker.has(val)) { return (val as IDocumentWidget<FileEditor>).content.editor; } else if (this._consoleTracker.has(val)) { const promptCell = (val as ConsolePanel).console.promptCell; return promptCell && promptCell.editor; } else { return null; } } } private _onMainAreaCurrentChange = ( shell: ApplicationShell, change: ApplicationShell.IChangedArgs ) => { const { newValue, oldValue } = change; const editor = this._getFocusedEditor(newValue); this.model!.editor = editor; if (newValue && this._consoleTracker.has(newValue)) { (newValue as ConsolePanel).console.promptCellCreated.connect( this._onPromptCellCreated ); } if (oldValue && this._consoleTracker.has(oldValue)) { (oldValue as ConsolePanel).console.promptCellCreated.disconnect( this._onPromptCellCreated ); } }; private _notebookTracker: INotebookTracker; private _editorTracker: IEditorTracker; private _consoleTracker: IConsoleTracker; private _shell: ApplicationShell; private _popup: Popup | null = null; } namespace LineCol { export class Model extends VDomModel implements ILineCol.IModel { constructor(editor: CodeEditor.IEditor | null) { super(); this.editor = editor; } get editor(): CodeEditor.IEditor | null { return this._editor; } set editor(editor: CodeEditor.IEditor | null) { const oldEditor = this._editor; if (oldEditor !== null) { oldEditor.model.selections.changed.disconnect( this._onSelectionChanged ); } const oldState = this._getAllState(); this._editor = editor; if (this._editor === null) { this._column = 1; this._line = 1; } else { this._editor.model.selections.changed.connect( this._onSelectionChanged ); const pos = this._editor.getCursorPosition(); this._column = pos.column + 1; this._line = pos.line + 1; } this._triggerChange(oldState, this._getAllState()); } get line(): number { return this._line; } get column(): number { return this._column; } private _onSelectionChanged = () => { const oldState = this._getAllState(); const pos = this.editor!.getCursorPosition(); this._line = pos.line + 1; this._column = pos.column + 1; this._triggerChange(oldState, this._getAllState()); }; private _getAllState(): [number, number] { return [this._line, this._column]; } private _triggerChange( oldState: [number, number], newState: [number, number] ) { if (oldState[0] !== newState[0] || oldState[1] !== newState[1]) { this.stateChanged.emit(void 0); } } private _line: number = 1; private _column: number = 1; private _editor: CodeEditor.IEditor | null = null; } export interface IOptions { notebookTracker: INotebookTracker; editorTracker: IEditorTracker; consoleTracker: IConsoleTracker; shell: ApplicationShell; } } export interface ILineCol extends IDisposable { readonly model: ILineCol.IModel | null; readonly modelChanged: ISignal<this, void>; } export namespace ILineCol { export interface IModel { readonly line: number; readonly column: number; readonly editor: CodeEditor.IEditor | null; } } // tslint:disable-next-line:variable-name export const ILineCol = new Token<ILineCol>('@jupyterlab/statusbar:ILineCol'); export const lineColItem: JupyterLabPlugin<ILineCol> = { id: '@jupyterlab/statusbar:line-col-item', autoStart: true, provides: ILineCol, requires: [ IDefaultsManager, INotebookTracker, IEditorTracker, IConsoleTracker ], activate: ( app: JupyterLab, defaultsManager: IDefaultsManager, notebookTracker: INotebookTracker, editorTracker: IEditorTracker, consoleTracker: IConsoleTracker ) => { let item = new LineCol({ shell: app.shell, notebookTracker, editorTracker, consoleTracker }); defaultsManager.addDefaultStatus('line-col-item', item, { align: 'right', priority: 2, isActive: IStatusContext.delegateActive(app.shell, [ { tracker: notebookTracker }, { tracker: editorTracker }, { tracker: consoleTracker } ]) }); return item; } };
the_stack
import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { StaticCodeAnalysisCategory, StaticCodeAnalysisCategoryState } from 'app/entities/static-code-analysis-category.model'; import { CategoryIssuesMap } from 'app/entities/programming-exercise-test-case-statistics.model'; import { TranslateService } from '@ngx-translate/core'; import { getColor } from 'app/exercises/programming/manage/grading/charts/programming-grading-charts.utils'; import { ProgrammingGradingChartsDirective } from 'app/exercises/programming/manage/grading/charts/programming-grading-charts.directive'; import { NgxChartsMultiSeriesDataEntry } from 'app/shared/chart/ngx-charts-datatypes'; import { ArtemisNavigationUtilService } from 'app/utils/navigation.utils'; enum ScaChartBarTitle { PENALTY = 'Penalty', ISSUES = 'Issues', DEDUCTIONS_EN = 'Deductions', DEDUCTIONS_DE = 'Punkte', } @Component({ selector: 'jhi-sca-category-distribution-chart', styleUrls: ['./sca-category-distribution-chart.scss'], template: ` <div> <div> <div class="d-flex justify-content-between"> <h4>{{ 'artemisApp.programmingExercise.configureGrading.charts.categoryDistribution.title' | artemisTranslate }}</h4> <button *ngIf="tableFiltered" type="button" class="btn btn-info" (click)="resetTableFilter()"> {{ 'artemisApp.programmingExercise.configureGrading.charts.resetFilter' | artemisTranslate }} </button> </div> <p [innerHTML]="'artemisApp.programmingExercise.configureGrading.charts.categoryDistribution.description' | artemisTranslate"></p> </div> <div #containerRef class="chart bg-light"> <ngx-charts-bar-horizontal-normalized [view]="[containerRef.offsetWidth, containerRef.offsetHeight]" [scheme]="ngxColors" [results]="ngxData" [xAxis]="true" [yAxis]="true" [xAxisTickFormatting]="xAxisFormatting" (select)="onSelect($event)" > <ng-template #tooltipTemplate let-model="model"> <b>{{ model.name }}</b> <br /> <div [ngSwitch]="model.series"> <div *ngSwitchCase="scaChartBarTitle.PENALTY"> <span> {{ 'artemisApp.programmingAssessment.penaltyTooltip' | artemisTranslate: { percentage: model.value.toFixed(2) } }} </span> <br /> <span> {{ 'artemisApp.programmingAssessment.issuesTooltip' | artemisTranslate: { percentage: model.issues.toFixed(2) } }} </span> <br /> <span> {{ 'artemisApp.programmingAssessment.deductionsTooltip' | artemisTranslate: { percentage: model.points.toFixed(2) } }} </span> </div> <div *ngSwitchCase="scaChartBarTitle.ISSUES"> <span> {{ 'artemisApp.programmingAssessment.penaltyTooltip' | artemisTranslate: { percentage: model.penalty.toFixed(2) } }} </span> <br /> <span> {{ 'artemisApp.programmingAssessment.issuesTooltip' | artemisTranslate: { percentage: model.value.toFixed(2) } }} </span> <br /> <span> {{ 'artemisApp.programmingAssessment.deductionsTooltip' | artemisTranslate: { percentage: model.points.toFixed(2) } }} </span> </div> </div> <div *ngIf="[scaChartBarTitle.DEDUCTIONS_EN, scaChartBarTitle.DEDUCTIONS_DE].includes(model.series)"> <span> {{ 'artemisApp.programmingAssessment.penaltyTooltip' | artemisTranslate: { percentage: model.penalty.toFixed(2) } }} </span> <br /> <span> {{ 'artemisApp.programmingAssessment.issuesTooltip' | artemisTranslate: { percentage: model.issues.toFixed(2) } }} </span> <br /> <span> {{ 'artemisApp.programmingAssessment.deductionsTooltip' | artemisTranslate: { percentage: model.value.toFixed(2) } }} </span> </div> </ng-template> </ngx-charts-bar-horizontal-normalized> </div> </div> `, }) export class ScaCategoryDistributionChartComponent extends ProgrammingGradingChartsDirective implements OnChanges { @Input() categories: StaticCodeAnalysisCategory[]; @Input() categoryIssuesMap?: CategoryIssuesMap; @Input() exercise: ProgrammingExercise; @Output() categoryColorsChange = new EventEmitter<{}>(); @Output() scaCategoryFilter = new EventEmitter<number>(); readonly scaChartBarTitle = ScaChartBarTitle; // ngx ngxData: NgxChartsMultiSeriesDataEntry[] = []; constructor(private translateService: TranslateService, private navigationUtilsService: ArtemisNavigationUtilService) { super(); translateService.onLangChange.subscribe(() => { this.updateTranslations(); }); } ngOnChanges(): void { this.ngxData = []; this.ngxColors.domain = []; // update colors for category table const categoryColors = {}; const categoryPenalties = this.categories .map((category) => ({ ...category, penalty: category.state === StaticCodeAnalysisCategoryState.Graded ? category.penalty : 0, maxPenalty: category.state === StaticCodeAnalysisCategoryState.Graded ? category.maxPenalty : 0, })) .map((category) => { const issuesMap = this.categoryIssuesMap ? this.categoryIssuesMap[category.name] || {} : {}; // total number of issues in this category const issuesSum = Object.entries(issuesMap).reduce((sum, [issues, students]) => sum + parseInt(issues, 10) * students, 0); // total number of penalty points in this category let penaltyPointsSum = Object.entries(issuesMap) .map(([issues, students]) => students * Math.min(parseInt(issues, 10) * category.penalty, category.maxPenalty)) .reduce((sum, penaltyPoints) => sum + penaltyPoints, 0); if ((this.exercise.maxStaticCodeAnalysisPenalty || Infinity) < penaltyPointsSum) { penaltyPointsSum = this.exercise.maxStaticCodeAnalysisPenalty!; } return { category, issues: issuesSum || 0, penaltyPoints: penaltyPointsSum }; }); // sum of all penalties const totalPenalty = categoryPenalties.reduce((sum, { category }) => sum + Math.min(category.penalty, category.maxPenalty), 0); // sum of all issues const totalIssues = categoryPenalties.reduce((sum, { issues }) => sum + issues, 0); // sum of all penalty points const totalPenaltyPoints = categoryPenalties.reduce((sum, { penaltyPoints }) => sum + penaltyPoints, 0); const penalty = { name: this.translateService.instant('artemisApp.programmingAssessment.penalty'), series: [] as any[] }; const issue = { name: this.translateService.instant('artemisApp.programmingAssessment.issues'), series: [] as any[] }; const deductions = { name: this.translateService.instant('artemisApp.programmingAssessment.deductions'), series: [] as any[] }; categoryPenalties.forEach((element, index) => { const penaltyScore = totalPenalty > 0 ? Math.max((Math.min(element.category.penalty, element.category.maxPenalty) / totalPenalty) * 100, 0) : 0; const issuesScore = totalIssues > 0 ? Math.max((element.issues / totalIssues) * 100, 0) : 0; const penaltyPoints = totalPenaltyPoints > 0 ? Math.max((element.penaltyPoints / totalPenaltyPoints) * 100, 0) : 0; const color = getColor(index / this.categories.length, 50); penalty.series.push({ name: element.category.name, value: penaltyScore, issues: issuesScore, points: penaltyPoints, isPenalty: true, id: element.category.id }); issue.series.push({ name: element.category.name, value: issuesScore, penalty: penaltyScore, points: penaltyPoints }); deductions.series.push({ name: element.category.name, value: penaltyPoints, penalty: penaltyScore, issues: issuesScore }); this.ngxColors.domain.push(color); categoryColors[element.category.name] = color; }); this.ngxData.push(penalty); this.ngxData.push(issue); this.ngxData.push(deductions); this.ngxData = [...this.ngxData]; this.categoryColorsChange.emit(categoryColors); } /** * Handles the click on a specific category in a specific line of the chart * If the user clicks a category within the penalty bar, the user is delegated to the scores page of the exercise * If the user clicks a category within one of the other two bars, the corresponding table is filtered in order to show this category * @param event the event delegated by ngx-charts after the user clicked a part of the chart */ onSelect(event: any): void { if (!event.isPenalty) { this.navigationUtilsService.routeInNewTab(['course-management', this.exercise.course!.id, 'programming-exercises', this.exercise.id, 'scores']); } else { this.tableFiltered = true; this.scaCategoryFilter.emit(event.id); } } /** * Auxiliary method for the reset button to reset the table view */ resetTableFilter(): void { super.resetTableFilter(); this.scaCategoryFilter.emit(ProgrammingGradingChartsDirective.RESET_TABLE); } /** * Auxiliary method in order to keep the translation of the bar labels up to date */ updateTranslations(): void { const penaltyLabel = this.translateService.instant('artemisApp.programmingAssessment.penalty'); const issueLabel = this.translateService.instant('artemisApp.programmingAssessment.issues'); const deductionsLabel = this.translateService.instant('artemisApp.programmingAssessment.deductions'); const labels = [penaltyLabel, issueLabel, deductionsLabel]; this.ngxData.forEach((category, index) => { category.name = labels[index]; }); this.ngxData = [...this.ngxData]; } }
the_stack
import { Container, AnimatedSprite } from 'pixi.js'; import { EngineView } from './EngineView'; import { existy } from '../utils/calculations'; import { TDirection, DIRECTIONS } from '../utils/constants'; import { TColumnRowPair, ObjectInfoInteractionOffsets, ObjectInfoTextures, ObjectVisualKey, getMovingDirVisualId, getObjectInfo, getStationaryDirVisualId, IObjectInfo, } from '../utils/map'; /** * Visual class for the map-objects. * * @class ObjectView * @extends PIXI.Container */ export class ObjectView extends Container { /** * A reference to the engine view that the map-object sits in. * @property {EngineView} engine * @private * @internal */ private _engine: EngineView; /** * Type-id of the map-object as defined in the json file. * @property * @public */ private type: string; /** * Defines if the map-object is movable onto by other map-objects. * @property * @public */ public isMovableTo: boolean; /** * Defines if the map-object is interactive/selectable. * @property * @public */ public isInteractive: boolean; /** * Number of tiles that map-object covers horizontally on the isometric map * @property * @public */ public columnSpan: number; /** * Number of tiles that map-object covers vertically on the isometric map * @property * @public */ public rowSpan: number; /** * A dictionary for all the textures defined for the map-object. * @property * @private */ private _textures: ObjectInfoTextures; /** * A dictionary for interaction offset points for each visual if defined in the map data file. * @property * @private */ private _interactionOffsets: ObjectInfoInteractionOffsets; /** * If true doesn't allow transparency change on this object * @property * @public */ public noTransparency: boolean; /** * Defines if the object is a floor object or not * @property * @public */ public isFloorObject: boolean; /** * Interaction offset points for the active visual. * @property * @public */ public currentInteractionOffset: TColumnRowPair; /** * Current direction of the object. * @property * @public */ public currentDirection: TDirection; /** * Defines if the map-object is movable onto by other map-objects. * @property * @private * @internal */ private _container: AnimatedSprite; /** * Position of the object in terms of column and row index. * @property * @public */ public mapPos: TColumnRowPair; /** * @property * @function * @private * @internal */ private onContainerAnimCompleteCallback: (objectView: ObjectView) => unknown; /** * @property * @function * @private * @internal */ private onContainerAnimComplete_delayed_binded: () => void; /** * @property * @function * @private * @internal */ private onContainerAnimComplete_binded: () => void; /** * Visual class constructor for the map-objects. * * @constructor * * @param engine {EngineView} the engine instance that the map-object sits in, required * @param type {number} type-id of the object as defined in the JSON file * @param animSpeed {number} animation speed for the animated visuals, default 0.5 */ constructor(engine: EngineView, type: string, animSpeed: number = 0.5) { super(); this.onContainerAnimComplete_delayed_binded = this.onContainerAnimComplete_delayed.bind(this); this.onContainerAnimComplete_binded = this.onContainerAnimComplete.bind(this); this._engine = engine; this.type = type; const info: IObjectInfo = getObjectInfo(this._engine, this.type); this.isMovableTo = info.m; this.isInteractive = info.i; this.interactive = this.interactiveChildren = false; this.isFloorObject = info.f; this.noTransparency = info.nt; this.rowSpan = info.rowSpan; this.columnSpan = info.columnSpan; const xAnchor = this.rowSpan / (this.columnSpan + this.rowSpan); this._textures = info.t; this._interactionOffsets = info.io; this.currentInteractionOffset = this._interactionOffsets.idle; this._container = new AnimatedSprite(this._textures.idle); this._container.interactive = this._container.interactiveChildren = false; this._container.anchor.x = xAnchor; this._container.anchor.y = 1; this.addChild(this._container); this.animSpeed = animSpeed; this._container.gotoAndStop(0); } /** * Animation speed for the animated visuals included in the map-object visuals. * * @property * @default 0.5 */ public get animSpeed(): number { return this._container.animationSpeed; } public set animSpeed(value: number) { this._container.animationSpeed = existy(value) && value > 0 ? value : 0.5; } /** * Changes the map-object's texture(s) according to the specified direction-id and the state of the map-object (moving or stationary). * * @method * @function * @public * * @param direction {TDirection} direction-id as defined in `TRAVISO.DIRECTIONS` * @param moving {boolean} if the requested visuals are for moving or stationary state, default `false` * @param stopOnFirstFrame {boolean} if true stops on the first frame after changing the visuals, default `false` * @param noLoop {boolean} if true the animation will not loop after the first run, default `false` * @param onAnimComplete {Function} callback function to call if 'noLoop' is true after the first run of the animation, default `null` * @param animSpeed {number} animation speed for the animated visuals, stays the same if not defined, default `null` */ public changeVisualToDirection( direction: TDirection, moving: boolean = false, stopOnFirstFrame: boolean = false, noLoop: boolean = false, onAnimComplete: (objectView: ObjectView) => unknown = null, animSpeed: number = null ): void { if ( !this.changeVisual( moving ? getMovingDirVisualId(direction) : getStationaryDirVisualId(direction), stopOnFirstFrame, noLoop, onAnimComplete, animSpeed ) ) { if (!this.changeVisual('idle', stopOnFirstFrame, noLoop, onAnimComplete, animSpeed)) { throw new Error("no 'idle' visual defined as backup for object type " + this.type); } else { this.currentDirection = DIRECTIONS.O; } } else { this.currentDirection = direction; } } /** * Changes the map-object's texture(s) according to the specified visual-id. * * @method * @function * @public * @internal * * @param vId {string} visual-id * @param stopOnFirstFrame {boolean} if true stops on the first frame after changing the visuals, default `false` * @param noLoop {boolean} if true the animation will not loop after the first run, default `false` * @param onAnimComplete {Function} callback function to call if 'noLoop' is true after the first run of the animation, default `null` * @param animSpeed {number} animation speed for the animated visuals, stays the same if not defined, default `null` * @return {boolean} `true` if the visual-id was valid and the visual has changed without errors */ public changeVisual( vId: ObjectVisualKey, stopOnFirstFrame: boolean = false, noLoop: boolean = false, onAnimComplete: (objectView: ObjectView) => unknown = null, animSpeed: number = null ): boolean { if (!this._textures[vId]) { // trace("!!! No textures defined for vId: " + vId); return false; } this.currentInteractionOffset = this._interactionOffsets[vId]; if (this._container.textures === this._textures[vId] && !noLoop) { this._container.loop = !noLoop; if (existy(animSpeed) && animSpeed > 0) { this.animSpeed = animSpeed; } return true; } this._container.textures = this._textures[vId]; if (!stopOnFirstFrame && this._textures[vId].length > 1) { this._container.loop = !noLoop; if (noLoop && onAnimComplete) { this.onContainerAnimCompleteCallback = onAnimComplete; this._container.onComplete = this.onContainerAnimComplete_binded; } if (existy(animSpeed) && animSpeed > 0) { this.animSpeed = animSpeed; } this._container.gotoAndPlay(0); } else { this._container.gotoAndStop(0); } if (this._engine.objectUpdateCallback) { this._engine.objectUpdateCallback(this); } return true; } private onContainerAnimComplete(): void { setTimeout(this.onContainerAnimComplete_delayed_binded, 100); } private onContainerAnimComplete_delayed(): void { this.onContainerAnimCompleteCallback(this); this.onContainerAnimCompleteCallback = null; } /** * Clears all references. * * @method * @function * @public */ public destroy(): void { if (this._container) { this._engine = null; this._textures = null; // this.removeChild(this._container); // this._container.textures = null; this._container.onComplete = null; this._container = null; } } }
the_stack
import React from 'react'; import { createContextScope } from '@radix-ui/react-context'; import { Primitive } from '@radix-ui/react-primitive'; import * as RovingFocusGroup from '@radix-ui/react-roving-focus'; import { createRovingFocusGroupScope } from '@radix-ui/react-roving-focus'; import { Toggle } from '@radix-ui/react-toggle'; import { useControllableState } from '@radix-ui/react-use-controllable-state'; import type * as Radix from '@radix-ui/react-primitive'; import type { Scope } from '@radix-ui/react-context'; /* ------------------------------------------------------------------------------------------------- * ToggleGroup * -----------------------------------------------------------------------------------------------*/ const TOGGLE_GROUP_NAME = 'ToggleGroup'; type ScopedProps<P> = P & { __scopeToggleGroup?: Scope }; const [createToggleGroupContext, createToggleGroupScope] = createContextScope(TOGGLE_GROUP_NAME, [ createRovingFocusGroupScope, ]); const useRovingFocusGroupScope = createRovingFocusGroupScope(); type ToggleGroupElement = ToggleGroupImplSingleElement | ToggleGroupImplMultipleElement; interface ToggleGroupSingleProps extends ToggleGroupImplSingleProps { type: 'single'; } interface ToggleGroupMultipleProps extends ToggleGroupImplMultipleProps { type: 'multiple'; } const ToggleGroup = React.forwardRef< ToggleGroupElement, ToggleGroupSingleProps | ToggleGroupMultipleProps >((props, forwardedRef) => { const { type, ...toggleGroupProps } = props; if (type === 'single') { const singleProps = toggleGroupProps as ToggleGroupImplSingleProps; return <ToggleGroupImplSingle {...singleProps} ref={forwardedRef} />; } if (type === 'multiple') { const multipleProps = toggleGroupProps as ToggleGroupImplMultipleProps; return <ToggleGroupImplMultiple {...multipleProps} ref={forwardedRef} />; } throw new Error(`Missing prop \`type\` expected on \`${TOGGLE_GROUP_NAME}\``); }); ToggleGroup.displayName = TOGGLE_GROUP_NAME; /* -----------------------------------------------------------------------------------------------*/ type ToggleGroupValueContextValue = { value: string[]; onItemActivate(value: string): void; onItemDeactivate(value: string): void; }; const [ToggleGroupValueProvider, useToggleGroupValueContext] = createToggleGroupContext<ToggleGroupValueContextValue>(TOGGLE_GROUP_NAME); type ToggleGroupImplSingleElement = ToggleGroupImplElement; interface ToggleGroupImplSingleProps extends ToggleGroupImplProps { /** * The controlled stateful value of the item that is pressed. */ value?: string; /** * The value of the item that is pressed when initially rendered. Use * `defaultValue` if you do not need to control the state of a toggle group. */ defaultValue?: string; /** * The callback that fires when the value of the toggle group changes. */ onValueChange?(value: string): void; } const ToggleGroupImplSingle = React.forwardRef< ToggleGroupImplSingleElement, ToggleGroupImplSingleProps >((props: ScopedProps<ToggleGroupImplSingleProps>, forwardedRef) => { const { value: valueProp, defaultValue, onValueChange = () => {}, ...toggleGroupSingleProps } = props; const [value, setValue] = useControllableState({ prop: valueProp, defaultProp: defaultValue, onChange: onValueChange, }); return ( <ToggleGroupValueProvider scope={props.__scopeToggleGroup} value={value ? [value] : []} onItemActivate={setValue} onItemDeactivate={React.useCallback(() => setValue(''), [setValue])} > <ToggleGroupImpl {...toggleGroupSingleProps} ref={forwardedRef} /> </ToggleGroupValueProvider> ); }); type ToggleGroupImplMultipleElement = ToggleGroupImplElement; interface ToggleGroupImplMultipleProps extends ToggleGroupImplProps { /** * The controlled stateful value of the items that are pressed. */ value?: string[]; /** * The value of the items that are pressed when initially rendered. Use * `defaultValue` if you do not need to control the state of a toggle group. */ defaultValue?: string[]; /** * The callback that fires when the state of the toggle group changes. */ onValueChange?(value: string[]): void; } const ToggleGroupImplMultiple = React.forwardRef< ToggleGroupImplMultipleElement, ToggleGroupImplMultipleProps >((props: ScopedProps<ToggleGroupImplMultipleProps>, forwardedRef) => { const { value: valueProp, defaultValue, onValueChange = () => {}, ...toggleGroupMultipleProps } = props; const [value = [], setValue] = useControllableState({ prop: valueProp, defaultProp: defaultValue, onChange: onValueChange, }); const handleButtonActivate = React.useCallback( (itemValue) => setValue((prevValue = []) => [...prevValue, itemValue]), [setValue] ); const handleButtonDeactivate = React.useCallback( (itemValue) => setValue((prevValue = []) => prevValue.filter((value) => value !== itemValue)), [setValue] ); return ( <ToggleGroupValueProvider scope={props.__scopeToggleGroup} value={value} onItemActivate={handleButtonActivate} onItemDeactivate={handleButtonDeactivate} > <ToggleGroupImpl {...toggleGroupMultipleProps} ref={forwardedRef} /> </ToggleGroupValueProvider> ); }); ToggleGroup.displayName = TOGGLE_GROUP_NAME; /* -----------------------------------------------------------------------------------------------*/ type ToggleGroupContextValue = { rovingFocus: boolean; disabled: boolean }; const [ToggleGroupContext, useToggleGroupContext] = createToggleGroupContext<ToggleGroupContextValue>(TOGGLE_GROUP_NAME); type RovingFocusGroupProps = Radix.ComponentPropsWithoutRef<typeof RovingFocusGroup.Root>; type ToggleGroupImplElement = React.ElementRef<typeof Primitive.div>; type PrimitiveDivProps = Radix.ComponentPropsWithoutRef<typeof Primitive.div>; interface ToggleGroupImplProps extends PrimitiveDivProps { /** * Whether the group is disabled from user interaction. * @defaultValue false */ disabled?: boolean; /** * Whether the group should maintain roving focus of its buttons. * @defaultValue true */ rovingFocus?: boolean; loop?: RovingFocusGroupProps['loop']; orientation?: RovingFocusGroupProps['orientation']; dir?: RovingFocusGroupProps['dir']; } const ToggleGroupImpl = React.forwardRef<ToggleGroupImplElement, ToggleGroupImplProps>( (props: ScopedProps<ToggleGroupImplProps>, forwardedRef) => { const { __scopeToggleGroup, disabled = false, rovingFocus = true, orientation, dir = 'ltr', loop = true, ...toggleGroupProps } = props; const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeToggleGroup); const commonProps = { role: 'group', dir, ...toggleGroupProps }; return ( <ToggleGroupContext scope={__scopeToggleGroup} rovingFocus={rovingFocus} disabled={disabled}> {rovingFocus ? ( <RovingFocusGroup.Root asChild {...rovingFocusGroupScope} orientation={orientation} dir={dir} loop={loop} > <Primitive.div {...commonProps} ref={forwardedRef} /> </RovingFocusGroup.Root> ) : ( <Primitive.div {...commonProps} ref={forwardedRef} /> )} </ToggleGroupContext> ); } ); /* ------------------------------------------------------------------------------------------------- * ToggleGroupItem * -----------------------------------------------------------------------------------------------*/ const ITEM_NAME = 'ToggleGroupItem'; type ToggleGroupItemElement = ToggleGroupItemImplElement; interface ToggleGroupItemProps extends Omit<ToggleGroupItemImplProps, 'pressed'> {} const ToggleGroupItem = React.forwardRef<ToggleGroupItemElement, ToggleGroupItemProps>( (props: ScopedProps<ToggleGroupItemProps>, forwardedRef) => { const valueContext = useToggleGroupValueContext(ITEM_NAME, props.__scopeToggleGroup); const context = useToggleGroupContext(ITEM_NAME, props.__scopeToggleGroup); const rovingFocusGroupScope = useRovingFocusGroupScope(props.__scopeToggleGroup); const pressed = valueContext.value.includes(props.value); const disabled = context.disabled || props.disabled; const commonProps = { ...props, pressed, disabled }; const ref = React.useRef<HTMLDivElement>(null); return context.rovingFocus ? ( <RovingFocusGroup.Item asChild {...rovingFocusGroupScope} focusable={!disabled} active={pressed} ref={ref} > <ToggleGroupItemImpl {...commonProps} ref={forwardedRef} /> </RovingFocusGroup.Item> ) : ( <ToggleGroupItemImpl {...commonProps} ref={forwardedRef} /> ); } ); ToggleGroupItem.displayName = ITEM_NAME; /* -----------------------------------------------------------------------------------------------*/ type ToggleGroupItemImplElement = React.ElementRef<typeof Toggle>; type ToggleProps = Radix.ComponentPropsWithoutRef<typeof Toggle>; interface ToggleGroupItemImplProps extends Omit<ToggleProps, 'defaultPressed' | 'onPressedChange'> { /** * A string value for the toggle group item. All items within a toggle group should use a unique value. */ value: string; } const ToggleGroupItemImpl = React.forwardRef<ToggleGroupItemImplElement, ToggleGroupItemImplProps>( (props: ScopedProps<ToggleGroupItemImplProps>, forwardedRef) => { const { __scopeToggleGroup, value, ...itemProps } = props; const valueContext = useToggleGroupValueContext(ITEM_NAME, __scopeToggleGroup); return ( <Toggle {...itemProps} ref={forwardedRef} onPressedChange={(pressed) => { if (pressed) { valueContext.onItemActivate(value); } else { valueContext.onItemDeactivate(value); } }} /> ); } ); /* -----------------------------------------------------------------------------------------------*/ const Root = ToggleGroup; const Item = ToggleGroupItem; export { createToggleGroupScope, // ToggleGroup, ToggleGroupItem, // Root, Item, }; export type { ToggleGroupSingleProps, ToggleGroupMultipleProps, ToggleGroupItemProps };
the_stack
import { CountableTimeInterval, TimeInterval } from '../d3-time'; // ------------------------------------------------------------------------------- // Shared Types and Interfaces // ------------------------------------------------------------------------------- export interface InterpolatorFactory<T, U> { (a: T, b: T): ((t: number) => U); } // ------------------------------------------------------------------------------- // Linear Scale Factory // ------------------------------------------------------------------------------- export interface ScaleLinear<Range, Output> { (value: number | { valueOf(): number }): Output; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. Otherwise, returns NaN */ invert(value: number | { valueOf(): number }): number; domain(): Array<number>; domain(domain: Array<number | { valueOf(): number }>): this; range(): Array<Range>; range(range: Array<Range>): this; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. */ rangeRound(range: Array<number | { valueOf(): number }>): this; clamp(): boolean; clamp(clamp: boolean): ScaleLinear<Range, Output>; interpolate(): InterpolatorFactory<any, any>; interpolate(interpolate: InterpolatorFactory<Range, Output>): this; interpolate<NewOutput>(interpolate: InterpolatorFactory<Range, NewOutput>): ScaleLinear<Range, NewOutput>; ticks(count?: number): Array<number>; tickFormat(count?: number, specifier?: string): ((d: number | { valueOf(): number }) => string); nice(count?: number): this; copy(): ScaleLinear<Range, Output>; } export function scaleLinear(): ScaleLinear<number, number>; export function scaleLinear<Output>(): ScaleLinear<Output, Output>; export function scaleLinear<Range, Output>(): ScaleLinear<Range, Output>; // ------------------------------------------------------------------------------- // Power Scale Factories // ------------------------------------------------------------------------------- export interface ScalePower<Range, Output> { (value: number | { valueOf(): number }): Output; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. Otherwise, returns NaN */ invert(value: number | { valueOf(): number }): number; domain(): Array<number>; domain(domain: Array<number | { valueOf(): number }>): this; range(): Array<Range>; range(range: Array<Range>): this; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. */ rangeRound(range: Array<number | { valueOf(): number }>): this; clamp(): boolean; clamp(clamp: boolean): this; interpolate(): InterpolatorFactory<any, any>; interpolate(interpolate: InterpolatorFactory<Range, Output>): this; interpolate<NewOutput>(interpolate: InterpolatorFactory<Range, NewOutput>): ScalePower<Range, NewOutput>; ticks(count?: number): Array<number>; tickFormat(count?: number, specifier?: string): ((d: number | { valueOf(): number }) => string); nice(count?: number): this; copy(): ScalePower<Range, Output>; exponent(): number; exponent(exponent: number): this; } export function scalePow(): ScalePower<number, number>; export function scalePow<Output>(): ScalePower<Output, Output>; export function scalePow<Range, Output>(): ScalePower<Range, Output>; export function scaleSqrt(): ScalePower<number, number>; export function scaleSqrt<Output>(): ScalePower<Output, Output>; export function scaleSqrt<Range, Output>(): ScalePower<Range, Output>; // ------------------------------------------------------------------------------- // Logarithmic Scale Factory // ------------------------------------------------------------------------------- export interface ScaleLogarithmic<Range, Output> { (value: number | { valueOf(): number }): Output; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. Otherwise, returns NaN */ invert(value: number | { valueOf(): number }): number; domain(): Array<number>; domain(domain: Array<number | { valueOf(): number }>): this; range(): Array<Range>; range(range: Array<Range>): this; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. */ rangeRound(range: Array<number | { valueOf(): number }>): this; clamp(): boolean; clamp(clamp: boolean): this; interpolate(): InterpolatorFactory<any, any>; interpolate(interpolate: InterpolatorFactory<Range, Output>): this; interpolate<NewOutput>(interpolate: InterpolatorFactory<Range, NewOutput>): ScaleLogarithmic<Range, NewOutput>; ticks(count?: number): Array<number>; tickFormat(count?: number, specifier?: string): ((d: number | { valueOf(): number }) => string); nice(count?: number): this; copy(): ScaleLogarithmic<Range, Output>; base(): number; base(base: number): this; } export function scaleLog(): ScaleLogarithmic<number, number>; export function scaleLog<Output>(): ScaleLogarithmic<Output, Output>; export function scaleLog<Range, Output>(): ScaleLogarithmic<Range, Output>; // ------------------------------------------------------------------------------- // Identity Scale Factory // ------------------------------------------------------------------------------- export interface ScaleIdentity { (value: number | { valueOf(): number }): number; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. Otherwise, returns NaN */ invert(value: number | { valueOf(): number }): number; domain(): Array<number>; domain(domain: Array<number | { valueOf(): number }>): this; range(): Array<number>; range(range: Array<Range | { valueOf(): number }>): this; ticks(count?: number): Array<number>; tickFormat(count?: number, specifier?: string): ((d: number | { valueOf(): number }) => string); nice(count?: number): this; copy(): ScaleIdentity; } export function scaleIdentity(): ScaleIdentity; // ------------------------------------------------------------------------------- // Time Scale Factories // ------------------------------------------------------------------------------- export interface ScaleTime<Range, Output> { (value: Date): Output; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. Otherwise, returns NaN */ invert(value: number | { valueOf(): number }): Date; domain(): Array<Date>; domain(domain: Array<Date>): this; range(): Array<Range>; range(range: Array<Range>): this; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. */ rangeRound(range: Array<number | { valueOf(): number }>): this; clamp(): boolean; clamp(clamp: boolean): this; interpolate(): InterpolatorFactory<any, any>; interpolate(interpolate: InterpolatorFactory<Range, Output>): this; interpolate<NewOutput>(interpolate: InterpolatorFactory<Range, NewOutput>): ScaleTime<Range, NewOutput>; ticks(): Array<Date>; ticks(count: number): Array<Date>; ticks(interval: TimeInterval): Array<Date>; tickFormat(): ((d: Date) => string); tickFormat(count: number, specifier?: string): ((d: Date) => string); tickFormat(interval: TimeInterval, specifier?: string): ((d: Date) => string); nice(): this; nice(count: number): this; nice(interval: CountableTimeInterval, step?: number): this; copy(): ScaleTime<Range, Output>; } export function scaleTime(): ScaleTime<number, number>; export function scaleTime<Output>(): ScaleTime<Output, Output>; export function scaleTime<Range, Output>(): ScaleTime<Range, Output>; export function scaleUtc(): ScaleTime<number, number>; export function scaleUtc<Output>(): ScaleTime<Output, Output>; export function scaleUtc<Range, Output>(): ScaleTime<Range, Output>; // ------------------------------------------------------------------------------- // Sequential Scale Factory // ------------------------------------------------------------------------------- export interface ScaleSequential<Output> { (value: number | { valueOf(): number }): Output; domain(): [number, number]; domain(domain: [number | { valueOf(): number }, number | { valueOf(): number }]): this; clamp(): boolean; clamp(clamp: boolean): this; interpolator(): ((t: number) => Output); interpolator(interpolator: ((t: number) => Output)): this; interpolator<NewOutput>(interpolator: ((t: number) => NewOutput)): ScaleSequential<NewOutput>; copy(): ScaleSequential<Output>; } export function scaleSequential<Output>(interpolator: ((t: number) => Output)): ScaleSequential<Output>; // ------------------------------------------------------------------------------- // Color Interpolators for Sequential Scale Factory // ------------------------------------------------------------------------------- export function interpolateViridis(t: number): string; export function interpolateMagma(t: number): string; export function interpolateInferno(t: number): string; export function interpolatePlasma(t: number): string; export function interpolateRainbow(t: number): string; export function interpolateWarm(t: number): string; export function interpolateCool(t: number): string; export function interpolateCubehelixDefault(t: number): string; // ------------------------------------------------------------------------------- // Quantize Scale Factory // ------------------------------------------------------------------------------- export interface ScaleQuantize<Range> { (value: number | { valueOf(): number }): Range; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. Otherwise, returns NaN */ invertExtent(value: Range): [number, number]; domain(): [number, number]; domain(domain: [number | { valueOf(): number }, number | { valueOf(): number }]): this; range(): Array<Range>; range(range: Array<Range>): this; ticks(count?: number): Array<number>; tickFormat(count?: number, specifier?: string): ((d: number | { valueOf(): number }) => string); nice(count?: number): this; copy(): ScaleQuantize<Range>; } export function scaleQuantize(): ScaleQuantize<number>; export function scaleQuantize<Range>(): ScaleQuantize<Range>; // ------------------------------------------------------------------------------- // Quantile Scale Factory // ------------------------------------------------------------------------------- export interface ScaleQuantile<Range> { (value: number | { valueOf(): number }): Range; invertExtent(value: Range): [number, number]; domain(): Array<number>; domain(domain: Array<number | { valueOf(): number }>): this; range(): Array<Range>; range(range: Array<Range>): this; quantiles(): Array<number>; copy(): ScaleQuantile<Range>; } export function scaleQuantile(): ScaleQuantile<number>; export function scaleQuantile<Range>(): ScaleQuantile<Range>; // ------------------------------------------------------------------------------- // Threshold Scale Factory // ------------------------------------------------------------------------------- // TODO: review Domain Type, should be naturally orderable export interface ScaleThreshold<Domain extends number | string | Date, Range> { (value: Domain): Range; /** * Important: While value should come out of range R, this is method is only applicable to * values that can be coerced to numeric. Otherwise, returns NaN */ invertExtent(value: Range): [Domain, Domain] | [undefined, Domain] | [Domain, undefined] | [undefined, undefined]; domain(): Array<Domain>; domain(domain: Array<Domain>): this; range(): Array<Range>; range(range: Array<Range>): this; copy(): ScaleThreshold<Domain, Range>; } export function scaleThreshold(): ScaleThreshold<number, number>; export function scaleThreshold<Domain extends number | string | Date, Range>(): ScaleThreshold<Domain, Range>; // ------------------------------------------------------------------------------- // Ordinal Scale Factory // ------------------------------------------------------------------------------- export interface ScaleOrdinal<Domain extends { toString(): string }, Range> { (x: Domain): Range; domain(): Array<Domain>; domain(domain: Array<Domain>): this; range(): Array<Range>; range(range: Array<Range>): this; unknown(): Range | { name: 'implicit' }; unknown(value: Range | { name: 'implicit' }): this; copy(): ScaleOrdinal<Domain, Range>; } export function scaleOrdinal<Range>(range?: Array<Range>): ScaleOrdinal<string, Range>; export function scaleOrdinal<Domain extends { toString(): string }, Range>(range?: Array<Range>): ScaleOrdinal<Domain, Range>; export const scaleImplicit: { name: 'implicit' }; // ------------------------------------------------------------------------------- // Band Scale Factory // ------------------------------------------------------------------------------- export interface ScaleBand<Domain extends { toString(): string }> { (x: Domain): number | undefined; domain(): Array<Domain>; domain(domain: Array<Domain>): this; range(): [number, number]; range(range: [number | { valueOf(): number }, number | { valueOf(): number }]): this; rangeRound(range: [number | { valueOf(): number }, number | { valueOf(): number }]): this; round(): boolean; round(round: boolean): this; paddingInner(): number; paddingInner(padding: number): this; paddingOuter(): number; paddingOuter(padding: number): this; /** * Returns the inner padding. */ padding(): number; /** * A convenience method for setting the inner and outer padding to the same padding value. */ padding(padding: number): this; align(): number; align(align: number): this; bandwidth(): number; step(): number; copy(): ScaleBand<Domain>; } export function scaleBand(): ScaleBand<string>; export function scaleBand<Domain extends { toString(): string }>(): ScaleBand<Domain>; // ------------------------------------------------------------------------------- // Point Scale Factory // ------------------------------------------------------------------------------- export interface ScalePoint<Domain extends { toString(): string }> { (x: Domain): number | undefined; domain(): Array<Domain>; domain(domain: Array<Domain>): this; range(): [number, number]; range(range: [number | { valueOf(): number }, number | { valueOf(): number }]): this; rangeRound(range: [number | { valueOf(): number }, number | { valueOf(): number }]): this; round(): boolean; round(round: boolean): this; /** * Returns the current outer padding which defaults to 0. * The outer padding determines the ratio of the range that is reserved for blank space * before the first point and after the last point. */ padding(): number; /** * Sets the outer padding to the specified value which must be in the range [0, 1]. * The outer padding determines the ratio of the range that is reserved for blank space * before the first point and after the last point. */ padding(padding: number): this; align(): number; align(align: number): this; bandwidth(): number; step(): number; copy(): ScalePoint<Domain>; } export function scalePoint(): ScalePoint<string>; export function scalePoint<Domain extends { toString(): string }>(): ScalePoint<Domain>; // ------------------------------------------------------------------------------- // Categorical Color Schemas for Ordinal Scales // ------------------------------------------------------------------------------- export const schemeCategory10: Array<string>; export const schemeCategory20: Array<string>; export const schemeCategory20b: Array<string>; export const schemeCategory20c: Array<string>;
the_stack
declare namespace Desmos { /** * Which features are enabled for your API key. */ const enabledFeatures: { GraphingCalculator: boolean; FourFunctionCalculator: boolean; ScientificCalculator: boolean; }; /** * An array of language codes suitable for passing into Calculator.updateSettings. */ const supportedLanguages: string[]; /** * The AxisArrowMode specifies whether arrows should be drawn at one or both ends of the x or y axes. It is specified * separately for the x and y axes through the xAxisArrowMode and yAxisArrowMode graph settings. * The default value for both axes is Desmos.AxisArrowMode.NONE. */ const AxisArrowModes: { NONE: "NONE"; POSITIVE: "POSITIVE"; BOTH: "BOTH"; }; /** * Default list of colors */ const Colors: { RED: "#c74440"; BLUE: "#2d70b3"; GREEN: "#388c46"; PURPLE: "#6042a6"; ORANGE: "#fa7e19"; BLACK: "#000000"; }; /** * The dragMode of a point determines whether it can be changed by dragging in the x direction, the y direction, * both, or neither. * In addition, a point may have its dragMode set to Desmos.DragModes.AUTO, in which case the normal calculator rules * for determining point behavior will be applied. For example, a point whose coordinates are both slider variables would * be draggable in both the x and y directions. * The dragMode of a table column determines the behavior of the points represented by the column. The dragMode is only applicable * to explicitly specified column values, and has no effect on computed column values. */ const DragModes: { X: "X"; Y: "Y"; XY: "XY"; NONE: "NONE"; AUTO: "AUTO"; }; /** * Though the calculator's fontSize property can be set to any numeric value, we provide a set of predefined font sizes for convenience. */ const FontSizes: { VERY_SMALL: 9; SMALL: 12; MEDIUM: 16; LARGE: 20; VERY_LARGE: 24; }; /** * The labelOrientation property specifies the desired position of a point's label, relative to the point itself. * This will override the calculator's default behavior of trying to position labels in such a way as to maintain legibility. To restore this behavior, * set the value back to Desmos.LabelOrientations.DEFAULT. * The default value is Desmos.LabelOrientations.DEFAULT. */ const LabelOrientations: { ABOVE: "ABOVE"; BELOW: "BELOW"; LEFT: "LEFT"; RIGHT: "RIGHT"; DEFAULT: "DEFAULT"; }; /** * The labelSize property specifies the text size of a point's label. * The default value is Desmos.LabelSizes.MEDIUM. */ const LabelSizes: { SMALL: "SMALL"; MEDIUM: "MEDIUM"; LARGE: "LARGE"; }; /** * Drawing styles for points and curves may be chosen from a set of predefined values. */ const Styles: { POINT: "POINT"; OPEN: "OPEN"; CROSS: "CROSS"; SOLID: "SOLID"; DASHED: "DASHED"; DOTTED: "DOTTED"; }; /** * Creates a four function calculator object to control the calculator embedded in the DOM element specified by element. */ function FourFunctionCalculator( element: HTMLElement, options?: { /** * Allow external hyperlinks (e.g. to braille examples) * @default true */ links?: boolean; /** * Picks the extra function(s) that appear in the top bar. Maximum 2, minimum 1. * @default ["sqrt"] */ additionalFunctions?: | ("exponent" | "percent" | "fraction" | "sqrt") | ReadonlyArray<"exponent" | "percent" | "fraction" | "sqrt">; /** * Base font size. * @default 16 */ fontSize?: number; /** * Display the calculator with an inverted color scheme. * @default false */ invertedColors?: boolean; /** * Display the settings menu. * @default true */ settingsMenu?: boolean; /** * Language. See the Languages section for more information. * @default "en" */ language?: string; /** * Set the input and output Braille code for persons using refreshable Braille displays. * @default "none" */ brailleMode?: "nemeth" | "ueb" | "none"; /** * Allow users to write six-dot Braille characters using the Home Row keys (S, D, F, J, K, and L). Requires that brailleMode be 'nemeth' or 'ueb'. * @default false */ sixKeyInput?: boolean; /** * Display the calculator in a larger font. * @default false */ projectorMode?: boolean; /** * When true, users are able to toggle between decimal and fraction output in evaluations if Desmos detects a good rational approximation. * @default false */ decimalToFraction?: boolean; /** * Limit the size of an expression to 100 characters. * @default false */ capExpressionSize?: boolean; }, ): BasicCalculator; /** * Creates a calculator object to control the calculator embedded in the DOM element specified by element. */ function GraphingCalculator(element: HTMLElement, options?: GraphConfiguration & GraphSettings): Calculator; /** * Creates a scientific calculator object to control the calculator embedded in the DOM element specified by element. */ function ScientificCalculator( element: HTMLElement, options?: { /** * Allow external hyperlinks (e.g. to braille examples) * @default true */ links?: boolean; /** * Display the keypad in QWERTY layout (false shows an alphabetical layout) * @default true */ qwertyKeyboard?: boolean; /** * When true, trig functions assume arguments are in degrees. Otherwise, arguments are assumed to be in radians. * @default false */ degreeMode?: boolean; /** * Base font size. * @default 16 */ fontSize?: number; /** * Display the calculator with an inverted color scheme. * @default false */ invertedColors?: boolean; /** * Display the settings menu. * @default true */ settingsMenu?: boolean; /** * Language. See the Languages section for more information. * @default "en" */ language?: string; /** * Set the input and output Braille code for persons using refreshable Braille displays. */ brailleMode?: "nemeth" | "ueb" | "none"; /** * Allow users to write six-dot Braille characters using the Home Row keys (S, D, F, J, K, and L). Requires that brailleMode be 'nemeth' or 'ueb'. * @default false */ sixKeyInput?: boolean; /** * Allows the user to export a Braille rendering of the expression list. Requires that brailleMode be 'nemeth' or 'ueb'. * @default true */ brailleExpressionDownload?: boolean; /** * Display the calculator in a larger font. * @default false */ projectorMode?: boolean; /** * When true, users are able to toggle between decimal and fraction output in evaluations if Desmos detects a good rational approximation. * @default true */ decimalToFraction?: boolean; /** * Limit the size of an expression to 100 characters * @default false */ capExpressionSize?: boolean; /** * Allow function definition, i.e. f(x) = 2x * @default true */ functionDefinition?: boolean; /** * Determine whether the calculator should automatically resize whenever there are changes to element's dimensions. If set to false * you will need to explicitly call .resize() in certain situations. See .resize(). * @default true */ autosize?: boolean; }, ): BasicCalculator; function imageFileToDataURL(file: File, cb: (err: Error, url: string) => void): void; type GraphState = unknown; interface BasicCalculator extends Pick< Calculator, | "getState" | "setState" | "setBlank" | "undo" | "redo" | "clearHistory" | "resize" | "focusFirstExpression" | "observeEvent" | "unobserveEvent" | "destroy" > { updateSettings( settings: | Parameters<typeof FourFunctionCalculator>[1] | Parameters<typeof ScientificCalculator>[1], ): void; } /** * The page element which will display your axes, grid-lines, equations, and points. */ interface Calculator { // methods /** * Similar to GraphingCalculator.screenshot, but asynchronous. Rather than returning a PNG data URI directly, * callback will be called with the either a URI string or SVG string as its argument. */ asyncScreenshot( opts: Parameters<Calculator["screenshot"]>[0] & { /** * Determines the format of the generated image. * @default "png" */ format?: "png" | "svg"; /** * Determines the strategy for computing the viewport visible in the screenshot. * @default "contain" */ mode?: "contain" | "stretch" | "preserveX" | "preserveY"; /** * An object representing desired viewport bounds. The current viewport value will be used for any omitted property, * but note that you cannot specify top without bottom or left without right. Passing invalid bounds will log a warning * to the console and use the current viewport bounds in their entirety. */ mathBounds?: Parameters<Calculator["setMathBounds"]>[0]; /** * Determines whether to include point labels in the captured image. * @default false */ showLabels?: boolean; }, callback: (dataUri: string) => void ): void; asyncScreenshot(callback: (dataUri: string) => void): void; /** * Clear the undo/redo history. Does not affect the current state. */ clearHistory(): void; /** * Destroy the GraphingCalculator instance, unbind event listeners, and free resources. This method should be called * whenever a calculator's container element is removed from the DOM. Attempting to call methods on a GraphingCalculator object after it has been destroyed * will result in a no-op and log a warning to the console. */ destroy(): void; /** * Focus the first expression in the expressions list. Note that the first expression isn't focused by default * because if the calculator is embedded in a page that can be scrolled, the browser will typically scroll the focused expression into view * at page load time, which may not be desirable. */ focusFirstExpression(): void; /** * Returns a representation of the current expressions list as an array. */ getExpressions(): ExpressionState[]; /** * Returns a javascript object representing the current state of the calculator. Use in conjunction with GraphingCalculator.setState to save and restore calculator states. * The return value of GraphingCalculator.getState may be serialized to a string using JSON.stringify. * Warning: Calculator states should be treated as opaque values. Manipulating states directly may produce a result that cannot be loaded by GraphingCalculator.setState. */ getState(): GraphState; /** * Whether or not the current viewport projection is uniform with respect to both axes (i.e., the mathematical aspect ratio is square). */ isProjectionUniform(): boolean; /** * Convert math coordinates to pixel coordinates. */ mathToPixels<C extends { x: number } | { y: number } | { x: number; y: number }>(coords: C): C; /** * Update the settings.randomSeed property to a new random value. */ newRandomSeed(): void; observe(eventName: string, callback: () => void): void; /** * The 'change' event is emitted by the calculator whenever any change occurs that will affect the persisted state of the calculator. * This applies to any changes caused either by direct user interaction, or by calls to API methods. * Observing the 'change' event allows implementing periodic saving of a user's work without the need for polling. */ observeEvent(eventName: string, callback: () => void): void; /** * Convert pixel coordinates to math coordinates. */ pixelsToMath<C extends { x: number } | { y: number } | { x: number; y: number }>(coords: C): C; /** * Advance to the next state in the undo/redo history, if available. */ redo(): void; /** * Remove an expression from the expressions list. */ removeExpression(expression_state: { id: string }): void; /** * Remove several expressions from the expressions list. */ removeExpressions( expression_states: ReadonlyArray<{ id: string; }> ): void; /** * Remove the selected expression. Returns the id of the expression that was removed, or undefined if no expression was selected. */ removeSelected(): string; /** * Resize the calculator to fill its container. This will happen automatically unless the autosize constructor option is set to false. * In that case, this method must be called whenever the dimensions of the calculator's container element change, and whenever the container element is added to or removed from the DOM. */ resize(): void; /** * Returns an image of the current graphpaper in the form of a PNG data URI. You can use the returned data URI directly in the src attribute of an image. * To save the data as a traditional image file, you can parse the data and base64 decode it. */ screenshot(opts?: { /** * Width of the screenshot in pixels. Defaults to current width of graphaper. */ width?: number; /** * Height of the screenshot in pixels. Defaults to current height of graphpaper in pixels. */ height?: number; /** * Oversampling factor. Larger values are useful for producing images that will look good on high pixel density ("retina") screens. * @default 1 */ targetPixelRatio?: number; /** * Determines whether to override the default behavior of stripping out the axis numbers from small images. Only relevant if opts.width or opts.height is less than 256px. * @default false */ preserveAxisNumbers?: boolean; }): string; /** * Reset the calculator to a blank state. */ setBlank(options?: { /** * Preserve the undo/redo history. * @default false */ allowUndo?: boolean; }): void; /** * Replace the calculator's "Delete All" button (under the "Edit List" menu) with a "Reset" button that will reset the calculator to the state * represented by obj. Also, if a default state is set, the "home" zoom button will reset the zoom to the viewport associated with the default state instead of the usual Desmos default * (roughly from -10 to 10, centered at the origin). If the showResetButtonOnGraphpaper option is true, a small reset button will appear on the graphpaper. */ setDefaultState(obj: GraphState): void; /** * This will update or create a mathematical expression. */ setExpression(expression: ExpressionState): void; /** * This function will attempt to create expressions for each element in the array. */ setExpressions(expressions: readonly ExpressionState[]): void; /** * Updates the math coordinates of the graphpaper bounds. * If invalid bounds are provided, the graphpaper bounds will not be changed. */ setMathBounds(bounds: { left?: number; right?: number; bottom?: number; top?: number }): void; /** * Reset the calculator to a state previously saved using GraphingCalculator.getState. */ setState( obj: GraphState, options?: { /** * Preserve the undo/redo history. * @default false */ allowUndo?: boolean; /** * Remap colors in the saved state to those in the current Calculator.colors object. See the Colors section. * @default false */ remapColors?: boolean; }, ): void; /** * Return to the previous state in the undo/redo history, if available. */ undo(): void; unobserve(eventName: string): void; /** * Remove all observers added by GraphingCalculator.observeEvent('change'). For finer control over removing observers, see the section on managing observers. */ unobserveEvent(eventName: string): void; /** * Updates any of the properties allowed in the constructor. Only properties that are present will be changed. * Also note that certain combinations of options are mutually exclusive. If an update would produce incompatible options, * additional options may be ignored or adjusted to obtain a compatible set. To prevent the calculator from making those adjustments on your behalf, * you should avoid passing in the following combinations: * - graphpaper: false with expressionsCollapsed: true or zoomButtons: true * - lockViewport: true with zoomButtons: true */ updateSettings(settings: GraphConfiguration & GraphSettings): void; HelperExpression(expression: ExpressionState): { listValue: number[]; numericValue: number; observe(eventName: "numericValue" | "listValue" | string, callback: () => void): void; }; // properties /** * Calculator instance's current color palette */ colors: { [key: string]: string; }; /** * An observable object containing information about the calculator's analysis of each expression. */ expressionAnalysis: { [id: string]: { /** * Does the expression represent something that can be plotted? */ isGraphable: boolean; /** * Does the expression result in an evaluation error? */ isError: boolean; /** * The (localized) error message, if any */ errorMessage?: string; /** * Is evaluation information displayed in the expressions list? */ evaluationDisplayed?: boolean; /** * Numeric value(s) */ evaluation?: { type: "Number"; value: number } | { type: "ListOfNumber"; value: readonly number[] }; }; }; /** * The graphpaperBounds observable property gives the bounds of the graphpaper in both math coordinates and pixel coordinates. */ graphpaperBounds: { mathCoordinates: { top: number; bottom: number; left: number; right: number; width: number; height: number; }; pixelCoordinates: { top: number; bottom: number; left: number; right: number; width: number; height: number; }; }; /** * true when an expression is selected, false when no expression is selected. */ isAnyExpressionSelected: boolean; /** * Observable property that holds the id of the currently selected expression, or undefined when no expression is selected. */ selectedExpressionId: string; /** * Object with observable properties for each public property. */ settings: GraphConfiguration & GraphSettings & { observe(eventName: keyof GraphConfiguration | keyof GraphSettings | string, callback: () => void): void; unobserve(eventName: keyof GraphConfiguration | keyof GraphSettings | string): void; }; /** * Language codes suitable for passing into Calculator.updateSettings. */ supportedLanguages: string[]; } type ExpressionState = | { type?: "expression"; /** * Following Desmos Expressions. */ latex?: string; /** * , hex color. See Colors. Default will cycle through 6 default colors. */ color?: string; /** * Sets the line drawing style of curves or point lists. See Styles. */ lineStyle?: keyof typeof Styles; /** * Determines width of lines in pixels. May be any positive number, or a LaTeX string that evaluates to a positive number. Defaults to 2.5. */ lineWidth?: number | string; /** * Determines opacity of lines. May be a number between 0 and 1, or a LaTeX string that evaluates to a number between 0 and 1. Defaults to 0.9. */ lineOpacity?: number | string; /** * Sets the point drawing style of point lists. See Styles. */ pointStyle?: keyof typeof Styles; /** * Determines diameter of points in pixels. May be any positive number, or a LaTeX string that evaluates to a positive number. Defaults to 9. */ pointSize?: number | string; /** * Determines opacity of points. May be a number between 0 and 1, or a LaTeX string that evaluates to a number between 0 and 1. Defaults to 0.9. */ pointOpacity?: number | string; /** * Determines opacity of the interior of a polygon or parametric curve. May be a number between 0 and 1, or a LaTeX string that evaluates to a number between 0 and 1. Defaults to 0.4. */ fillOpacity?: number | string; /** * Determines whether points are plotted for point lists. */ points?: boolean; /** * Determines whether line segments are plotted for point lists. */ lines?: boolean; /** * Determines whether a polygon or parametric curve has its interior shaded. */ fill?: boolean; /** * Determines whether the graph is drawn. Defaults to false. */ hidden?: boolean; /** * Determines whether the expression should appear in the expressions list. Does not affect graph visibility. Defaults to false. */ secret?: boolean; /** * Sets bounds of slider expressions. If step is omitted, '', or undefined, the slider will be continuously adjustable. See note below. */ sliderBounds?: { min: number | string; max: number | string; step: number | string; }; /** * Sets bounds of parametric curves. See note below. */ parametricDomain?: { min: number | string; max: number | string; }; /** * Sets bounds of polar curves. See note below. */ polarDomain?: { min: number | string; max: number | string; }; /** * Should be a valid property name for a javascript object (letters, numbers, and _). */ id?: string; /** * Sets the drag mode of a point. See Drag Modes. Defaults to DragModes.AUTO. */ dragMode?: keyof typeof DragModes; /** * . Sets the text label of a point. If a label is set to the empty string then the point's default label (its coordinates) will be applied. */ label?: string; /** * Sets the visibility of a point's text label. */ showLabel?: boolean; /** * Sets the size of a point's text label. See LabelSizes. */ labelSize?: keyof typeof LabelSizes; /** * Sets the desired position of a point's text label. See LabelOrientations. */ labelOrientation?: keyof typeof LabelOrientations; } | { type: "table"; /** * Array of Table Columns. */ columns: ReadonlyArray<{ /** * Variable or computed expression used in the column header. */ latex: string; /** * Array of LaTeX strings. Need not be specified in the case of computed table columns. */ values?: string[]; /** * Hex color. See Colors. Default will cycle through 6 default colors. */ color?: string; /** * Determines if graph is drawn. * @default false */ hidden?: boolean; /** * Determines whether points are plotted. */ points?: boolean; /** * Determines whether line segments are plotted. */ lines?: boolean; /** * Sets the drawing style for line segments. See Styles. */ lineStyle?: keyof typeof Styles; /** * Determines width of lines in pixels. May be any positive number, or a LaTeX string that evaluates to a positive number. * @default 2.5 */ lineWidth?: number | string; /** * Determines opacity of lines. May be a number between 0 and 1, or a LaTeX string that evaluates to a number between 0 and 1. * @default 0.9 */ lineOpacity?: number | string; /** * Sets the drawing style for points. See Styles. */ pointStyle?: keyof typeof Styles; /** * Determines diameter of points in pixels. May be any positive number, or a LaTeX string that evaluates to a positive number. * @default 9 */ pointSize?: number | string; /** * Determines opacity of points. May be a number between 0 and 1, or a LaTeX string that evaluates to a number between 0 and 1. * @default 0.9 */ pointOpacity?: number | string; /** * See Drag Modes. Defaults to DragModes.NONE. */ dragMode?: keyof typeof DragModes; }>; id?: string; }; interface GraphConfiguration { /** * Show the onscreen keypad. * @default true */ keypad?: boolean; /** * Show the graphpaper * @default true */ graphpaper?: boolean; /** * Show the expressions list * @default true */ expressions?: boolean; /** * Show the settings wrench, for changing graph display * @default true */ settingsMenu?: boolean; /** * Show onscreen zoom buttons * @default true */ zoomButtons?: boolean; /** * If a default state is set, show an onscreen reset button * @default false */ showResetButtonOnGraphpaper?: boolean; /** * Show the bar on top of the expressions list * @default true */ expressionsTopbar?: boolean; /** * Show Points of Interest (POIs) as gray dots that can be clicked on * @default true */ pointsOfInterest?: boolean; /** * Allow tracing curves to inspect coordinates, and showing point coordinates when clicked * @default true */ trace?: boolean; /** * Add a subtle 1px gray border around the entire calculator * @default true */ border?: boolean; /** * Disable user panning and zooming graphpaper * @default false */ lockViewport?: boolean; /** * Collapse the expressions list * @default false */ expressionsCollapsed?: boolean; /** * Limit the size of an expression to 100 characters * @default false */ capExpressionSize?: boolean; /** * Allow creating secret folders * @default false */ administerSecretFolders?: boolean; /** * Allow adding images * @default true */ images?: boolean; /** * Specify custom processing for user-uploaded images. See Image Uploads for more details. * @param file comment for stuff */ imageUploadCallback?(file: File, cb: (err: Error, url: string) => void): void; /** * Allow the creation of folders in the expressions list * @default true */ folders?: boolean; /** * Allow the creation of text notes in the expressions list * @default true */ notes?: boolean; /** * Allow the creation of sliders in the expressions list * @default true */ sliders?: boolean; /** * Allow hyperlinks in notes/folders, and links to help documentation in the expressions list (e.g. regressions with negative R2 values or plots with unresolved detail) * @default true */ links?: boolean; /** * Display the keypad in QWERTY layout (false shows an alphabetical layout) * @default true */ qwertyKeyboard?: boolean; /** * Enable/disable functions related to univariate data visualizations, statistical distributions, and hypothesis testing * @default true */ distributions?: boolean; /** * Show a restricted menu of available functions * @default false */ restrictedFunctions?: boolean; /** * Force distance and midpoint functions to be enabled, even if restrictedFunctions is set to true. In that case the geometry functions will also be added to the the "Misc" keypad * @default false */ forceEnableGeometryFunctions?: boolean; /** * Paste a valid desmos graph URL to import that graph * @default false */ pasteGraphLink?: boolean; /** * Paste validly formatted table data to create a table up to 50 rows * @default true */ pasteTableData?: boolean; /** * When true, clearing the graph through the UI or calling setBlank() will leave the calculator in degreeMode. Note that, if a default state is set, * resetting the graph through the UI will result in the calculator's degreeMode matching the mode of that state, regardless of this option. * @default false */ clearIntoDegreeMode?: boolean; /** * The color palette that the calculator will cycle through. See the Colors section. */ colors?: { [key: string]: string }; /** * Determine whether the calculator should automatically resize whenever there are changes to element's dimensions. If set to false you will need to * explicitly call .resize() in certain situations. See .resize(). * @default true */ autosize?: boolean; /** * Determine whether the calculator should plot inequalities * @default true */ plotInequalities?: boolean; /** * Determine whether the calculator should plot implicit equations and inequalities * @default true */ plotImplicits?: boolean; /** * Determine whether the calculator should plot single-variable implicit equations * @default true */ plotSingleVariableImplicitEquations?: boolean; /** * When true, fonts and line thicknesses are increased to aid legibility. * @default false */ projectorMode?: boolean; /** * When true, users are able to toggle between decimal and fraction output in evaluations if Desmos detects a good rational approximation. * @default true */ decimalToFraction?: boolean; /** * Base font size. * @default 16 */ fontSize?: number; /** * Display the calculator with an inverted color scheme. * @default false */ invertedColors?: boolean; /** * Language. See the https://www.desmos.com/api/v1.6/docs/index.html#document-languages for more information. * @default "en" */ language?: string; /** * none' Set the input and output Braille code for persons using refreshable Braille displays. Valid options are 'nemeth', 'ueb', or 'none'. * @default "none" */ brailleMode?: "nemeth" | "ueb" | "none"; /** * Allow users to write six-dot Braille characters using the Home Row keys (S, D, F, J, K, and L). Requires that brailleMode be 'nemeth' or 'ueb'. * @default false */ sixKeyInput?: boolean; /** * Show Braille controls in the settings menu and enable shortcut keys for switching between Braille modes. * @default true */ brailleControls?: boolean; /** * When true, tables and distributions will display an icon that allows the user to automatically snap the viewport to appropriate bounds for viewing that expression. * @default true */ zoomFit?: boolean; /** * When true, all linearizable regression models will have log mode enabled by default, and the checkbox used to toggle log mode will be hidden from the expression interface. * @default false */ forceLogModeRegressions?: boolean; } interface GraphSettings { /** * When true, trig functions assume arguments are in degrees. Otherwise, arguments are assumed to be in radians. * @default false */ degreeMode?: boolean; /** * Show or hide grid lines on the graph paper. * @default true */ showGrid?: boolean; /** * When true, use a polar grid. Otherwise, use cartesian grid. * @default false */ polarMode?: boolean; /** * Show or hide the x axis. * @default true */ showXAxis?: boolean; /** * Show or hide the y axis. * @default true */ showYAxis?: boolean; /** * Show or hide numeric tick labels on the x axis. * @default true */ xAxisNumbers?: boolean; /** * Show or hide numeric tick labels on the y axis. * @default true */ yAxisNumbers?: boolean; /** * Show or hide numeric tick labels at successive angles. Only relevant when polarMode is true. * @default true */ polarNumbers?: boolean; /** * Spacing between numeric ticks on the x axis. Will be ignored if set too small to display. When set to 0, tick spacing is chosen automatically. * @default 0 */ xAxisStep?: number; /** * Spacing between numeric ticks on the y axis. Will be ignored if set too small to display. When set to 0, tick spacing is chosen automatically. * @default 0 */ yAxisStep?: number; /** * Subdivisions between ticks on the x axis. Must be an integer between 0 and 5. 1 means that only the major grid lines will be shown. When set to 0, subdivisions are chosen automatically. * @default 0 */ xAxisMinorSubdivisions?: number; /** * Subdivisions between ticks on the y axis. Must be an integer between 0 and 5. 1 means that only the major grid lines will be shown. When set to 0, subdivisions are chosen automatically. * @default 0 */ yAxisMinorSubdivisions?: number; /** * Determines whether to place arrows at one or both ends of the x axis. See Axis Arrow Modes. * @default "NONE" */ xAxisArrowMode?: keyof typeof AxisArrowModes; /** * Determines whether to place arrows at one or both ends of the y axis. See Axis Arrow Modes. * @default "NONE" */ yAxisArrowMode?: keyof typeof AxisArrowModes; /** * Label placed below the x axis. * @default "" */ xAxisLabel?: string; /** * Label placed beside the y axis. * @default "" */ yAxisLabel?: string; /** * Global random seed used for generating values from the calculator's built-in random() function. See the section on random seeds below. * @default "" */ randomSeed?: string; } }
the_stack
import { ResponseCode } from "../../../constants/response"; import { DataDirectoryPath } from "../../../types/module/data/data.types"; import { TCalendarData, TScheduleCreateData, TScheduleData, } from "../../../types/module/data/service/calendar/calendar.types"; import { getDateArray } from "../../datetime"; import log from "../../log"; import { getJsonData, isExists, setJsonData } from "../etc/fileManager"; import { v4 as uuidv4 } from "uuid"; import fs from "fs"; import DataIssueManager from "../issuespace/issueManager"; import { TIssueData } from "../../../types/module/data/service/issuespace/issue.types"; const calendarInfoFileName = "calendarInfo.json"; export default class DataCalendarManager { /** * * @description get Calendar path * @returns calender path */ static getCalendarPath() { return `${DataDirectoryPath}/calendar`; } /** * * @description get Calendar Infomation * @returns calendarInfo if calendar info file exists, undefined if not */ static getCalendarInfo() { const defaultPath = this.getCalendarPath(); const calendarInfoPath = `${defaultPath}/${calendarInfoFileName}`; if (!isExists(calendarInfoPath)) { return undefined; } return getJsonData(calendarInfoPath) as TCalendarData; } /** * * @param calendarData calendarData you want to set * @description set calendar data to calendar info file * @returns true if succeed to set calendar data to calendar info file, false if not */ static setCalendarInfo(calendarData: TCalendarData) { const defaultPath = this.getCalendarPath(); if (!isExists(defaultPath)) { return false; } const calendarInfoPath = `${defaultPath}/${calendarInfoFileName}`; return setJsonData(calendarInfoPath, calendarData); } /** * * @param scheduleId schedule ID to get schedule * @description get schedule which ID is scheduleId * @returns schedule infomation which ID is scheduleId */ static getScheduleInfo(scheduleId: string) { const calendarInfo = this.getCalendarInfo(); return Object.values(calendarInfo) .find((scheduleListInfo: TScheduleData[]) => { return scheduleListInfo.find((scheduleInfo: TScheduleData) => { return scheduleInfo.scheduleId === scheduleId; }); }) ?.find( (scheduleInfo: TScheduleData) => scheduleInfo.scheduleId === scheduleId ); } /** * * @param issueUUID issue ID to get schedule * @description get schedule which issue ID is issueUUID * @returns schedule infomation which issue ID is issueUUID */ static getScheduleIdByIssueUUID(issueUUID: string) { const calendarInfo = this.getCalendarInfo(); if (calendarInfo === undefined || calendarInfo === {}) { return undefined; } return Object.values(calendarInfo) .find((scheduleListInfo: TScheduleData[]) => { return scheduleListInfo.find((scheduleInfo: TScheduleData) => { return scheduleInfo.issue === issueUUID; }); }) ?.find( (scheduleInfo: TScheduleData) => scheduleInfo.issue === issueUUID ).scheduleId; } /** * * @param calendarInfo calendar infomation * @param scheduleId schedule ID to delete from calendarInfo * @param date * @returns */ static deleteScheduleInfo( calendarInfo: TCalendarData, scheduleId: string, date: string ) { calendarInfo[date] === undefined ? (calendarInfo[date] = []) : undefined; const index = calendarInfo[date]?.findIndex( (scheduleInfo: TScheduleData) => { return scheduleInfo.scheduleId === scheduleId; } ); if (index > -1) { calendarInfo[date].splice(index, 1); } return calendarInfo; } static addScheduleInfo( calendarInfo: TCalendarData, scheduleData: TScheduleData, date: string ) { calendarInfo[date] === undefined ? (calendarInfo[date] = []) : undefined; const index = calendarInfo[date]?.findIndex( (scheduleInfo: TScheduleData) => { return scheduleInfo.scheduleId === scheduleData.scheduleId; } ); if (index > -1) { calendarInfo[date].splice(index, 1); } calendarInfo[date].push(scheduleData); return calendarInfo; } static getCalendar(options: Partial<TScheduleData>) { if (!isExists(this.getCalendarPath())) { fs.mkdirSync(this.getCalendarPath(), { recursive: true }); } const calendarInfo = this.getCalendarInfo() ? this.getCalendarInfo() : {}; return Object.keys(calendarInfo) .filter((date) => { return ( (options.startDate === undefined && options.dueDate === undefined) || (options.startDate <= date && date <= options.dueDate) ); }) .reduce((calendarData: TCalendarData, date: string) => { const scheduleInfo = calendarInfo[date].filter( (scheduleData: TScheduleData) => { return ( (options.issue === undefined || options.issue === scheduleData.issue) && (options.kanban === undefined || options.kanban === scheduleData.kanban) && (options.milestone === undefined || options.milestone === scheduleData.milestone) && (options.type === undefined || options.type === scheduleData.type) && (options.title === undefined || options.title === scheduleData.title) && (options.creator === undefined || options.creator === scheduleData.creator) && (options.scheduleId === undefined || options.scheduleId === scheduleData.scheduleId) ); } ); calendarData[date] = scheduleInfo.length > 0 ? scheduleInfo : undefined; return calendarData; }, {}); } static createSchedule( scheduleData: TScheduleCreateData, isCalledIssue: boolean = false ) { if (!isExists(this.getCalendarPath())) { fs.mkdirSync(this.getCalendarPath(), { recursive: true }); } if ( scheduleData?.startDate === undefined || scheduleData?.dueDate === undefined ) { log.error( `[DataCalendarManager] create : startdate or dueDate is undefined ` ); return { code: ResponseCode.missingParameter, message: "Please input start date and due date", }; } let startDate = scheduleData.startDate; startDate = startDate.split("-")[0]?.length === 4 ? startDate.substr(2) : startDate; let dueDate = scheduleData.dueDate; dueDate = dueDate.split("-")[0]?.length === 4 ? dueDate.substr(2) : dueDate; const calendarInfo = this.getCalendarInfo() ? this.getCalendarInfo() : {}; const scheduleId = uuidv4(); if (isCalledIssue !== true && scheduleData.kanban !== undefined) { const createIssueResult = DataIssueManager.create( scheduleData.creator, scheduleData.kanban, { title: scheduleData.title, creator: scheduleData.creator, content: scheduleData.content, assigner: [scheduleData.creator], startDate: scheduleData.startDate, dueDate: scheduleData.dueDate, kanban: scheduleData.kanban, milestone: scheduleData.milestone, column: "backlog", } as Omit<TIssueData, "issueId">, true ); if (createIssueResult.code === ResponseCode.ok) { scheduleData = { ...scheduleData, issue: createIssueResult.issue.uuid, }; } } try { getDateArray(startDate, dueDate).forEach((dateElement) => { const calendarCreateData: TScheduleData = { ...scheduleData, scheduleId, }; calendarInfo[dateElement] ? calendarInfo[dateElement].push(calendarCreateData) : (calendarInfo[dateElement] = [calendarCreateData]); }); log.info(`[DataCalendarManager] create : Create schedule`); if (!this.setCalendarInfo(calendarInfo)) { return { code: ResponseCode.internalError, message: "Failed to create schedule data", }; } } catch (err) { log.error(err.stack); return { code: ResponseCode.internalError, message: "Failed to create schedule data", }; } return { code: ResponseCode.ok, uuid: scheduleId }; } static updateSchedule( scheduleData: Partial<TScheduleData>, isCalledIssue: boolean = false ) { if (scheduleData.scheduleId === undefined) { log.error("[DataCalendarManager] update : scheduleId is undefined"); return { code: ResponseCode.missingParameter, message: "Please input suhedule Id", }; } let newCalendarInfo = this.getCalendarInfo(); let scheduleInfo: TScheduleData = this.getScheduleInfo( scheduleData.scheduleId ); if ( scheduleData.startDate !== undefined && scheduleData.dueDate !== undefined ) { getDateArray(scheduleInfo.startDate, scheduleInfo.dueDate).forEach( (dateElement) => (newCalendarInfo = this.deleteScheduleInfo( newCalendarInfo, scheduleInfo.scheduleId, dateElement )) ); scheduleInfo = { ...scheduleInfo, ...scheduleData }; getDateArray(scheduleInfo.startDate, scheduleInfo.dueDate).forEach( (dateElement) => (newCalendarInfo = this.addScheduleInfo( newCalendarInfo, scheduleInfo, dateElement )) ); } else if ( scheduleData.startDate === undefined && scheduleData.dueDate === undefined ) { scheduleInfo = { ...scheduleInfo, ...scheduleData }; getDateArray(scheduleData.startDate, scheduleData.dueDate).forEach( (dateElement) => (newCalendarInfo = this.addScheduleInfo( newCalendarInfo, scheduleInfo, dateElement )) ); } else { } if ( isCalledIssue !== true && scheduleInfo.issue !== undefined && scheduleData.kanban !== undefined ) { const kanbanUUID = DataIssueManager.getKanbanUUID( scheduleInfo.issue ); if ( kanbanUUID === undefined || kanbanUUID !== scheduleData.kanban ) { log.error( `[DataCalendarManager] update : kanbanUUID is undefined` ); } if ( DataIssueManager.update( scheduleInfo.creator, kanbanUUID, { uuid: scheduleInfo.issue, title: scheduleInfo.title, creator: scheduleInfo.creator, content: scheduleInfo.content, milestone: scheduleInfo.milestone, startDate: scheduleInfo.startDate, dueDate: scheduleInfo.dueDate, }, true ).code !== ResponseCode.ok ) { log.error( `[DataCalendarManager] update : Failed to update issue` ); } } if (!this.setCalendarInfo(newCalendarInfo)) { log.error( `[DataCalendarManager] update : Failed to set calendar info` ); return { code: ResponseCode.internalError, message: "Failed to update schedule", }; } log.info(`[DataCalendarManager] update : Update calendar info`); return { code: ResponseCode.ok }; } static deleteSchedule( { scheduleId }: Pick<TScheduleData, "scheduleId">, isCalledIssue: boolean = false ) { let calendarInfo = this.getCalendarInfo(); const scheduleInfo = this.getScheduleInfo(scheduleId); if (scheduleId === undefined || scheduleInfo == undefined) { log.error( `[DataCalendarManager] delete : scheduleId or scheduleInfo is undefined` ); return { code: ResponseCode.missingParameter, message: "Could not find schedule info", }; } if ( isCalledIssue !== true && scheduleInfo.issue !== undefined && scheduleInfo.kanban !== undefined ) { const kanbanUUID = DataIssueManager.getKanbanUUID( scheduleInfo.issue ); if ( kanbanUUID === undefined || kanbanUUID !== scheduleInfo.kanban ) { log.error( `[DataCalendarManager] update : kanbanUUID is undefined` ); } if ( DataIssueManager.delete( scheduleInfo.creator, kanbanUUID, scheduleInfo.issue, true ).code !== ResponseCode.ok ) { log.error( `[DataCalendarManager] delete : Failed to delete issue` ); } } getDateArray(scheduleInfo.startDate, scheduleInfo.dueDate).forEach( (dateElement) => (calendarInfo = this.deleteScheduleInfo( calendarInfo, scheduleId, dateElement )) ); if (!this.setCalendarInfo(calendarInfo)) { log.error(`[DataCalendarManager] delete : update calendar info`); return { code: ResponseCode.internalError, message: "Failed to delete schedule", }; } log.info(`[DataCalendarManager] delete : Delete schedule`); return { code: ResponseCode.ok }; } }
the_stack
* @fileoverview The WordTree data structure and related logic is used to * support Dive's bag-of-words feature. * * Consider an array of multi-word string values (like "the end" and * "hello world"). The goal of the WordTree is to treat each word of each string * individually, and split the strings according to their common words. * * For example, say half the strings contain the word "the", and no word * appeared more frequently than that. Then the word "the" would be the top word * for the whole set of words, and would be used to split out all of those words * into a separate node. * * +---+ * | * |--- others * +---+ * / * +---+ * |the| * +---+ * * The number of strings that a node has is its mass. The goal of the algorithm * is to break up that mass into a tree structure. Currently it dose this by * finding the most common word in a given node and splitting those out to a * child node. * * A better approach would be to choose the word which appears in just about * half of the strings in the node. * * TODO(jimbo): Split nodes by the median word, rather than the top word. */ /** * Maximum level to achieve when building out the word tree. */ const MAX_WORD_TREE_LEVEL = 100; /** * When splitting a string into words, this regex is used. It finds sequences of * word characters, dashes and apostrophes surrounded by word boundaries. * * Currently this regex fails to work for non-latin characters, like the 'é' in * Pokémon. * * TODO(jimbo): Improve word-splitting algorithm to account for non-latin chars. */ const WORD_MATCH_REGEX = /\b[-'\w]+\b/g; /** * A word frequency map keeps track of how many times a string has ocurred. */ export interface WordFrequencyCounts { [word: string]: number; } /** * A ValueHash maps string hash values to the true value and other info about * that value, such as the number of times it occurred (count) and the words * contained within the value. */ export interface ValueHash { /** * The typeAndValue string is a concatenation of the typeof the value and its * string value (see getHashKey). This should be sufficient to uniquely * identify it, as long as the value is primitive, like a string, number, or * something falsey (undefined/null). */ [typeAndValue: string]: { /** * The actual value. Usually this will be a string or number, may also be * undefined or null. */ value: any; /** * The number of times this value occurs. That is, the number of items that * have this value for this field. */ count: number; /** * Hash mapping each word and the number of times it occurs in the value. */ words?: WordFrequencyCounts; }; } /** * Given a value, return the key it can be found by in a ValueHash. */ export function getHashKey(value: any): string { return `${typeof value}\u001F${value}`; } /** * A WordTreeNode contains values specific to this node and links to the parent * and children nodes (if any). */ export interface WordTreeNode { /** * The parent node to this WordTreeNode. For the root, this will be null. */ parent: WordTreeNode|null; /** * List of words common to all children and values. May be empty. */ commonWords: string[]; /** * Lowest value for which this node should be treated as its own bucket * when faceting. */ level: number; /** * Ordering value for sorting nodes when faceting. */ order: number; /** * The total number of items with values that roll up under this node. */ totalCount: number; /** * ValueHash for string values that belong to this node specifically, and * can't be further divided into its child nodes. */ valueHash: ValueHash; /** * The number of items represented in the valueHash, not recursively * under the children. This is the sum of all counts in the valueHash. */ valueCount: number; /** * The number of items represented by this node, but which do not appear in * the valueHash. For the root node, this value will cover non-strings. */ nonValueCount: number; /** * Child nodes which each contain their own value hashes. */ children: WordTreeNode[]; } /** * A tree of WordTreeNodes. */ export interface WordTree { /** * The root of the WordTree. */ root: WordTreeNode; /** * Mapping between the typeAndValue hash and the WordTreeNode which * contains it. */ nodeHash: {[typeAndValue: string]: WordTreeNode}; /** * The highest level of any node in this tree. */ highestLevel: number; /** * Mapping between the level number and the node with that exact level. */ levelHash: {[level: number]: WordTreeNode}; } /** * Given a string, split it into words. */ export function splitIntoWords(str: string): string[] { return str.toLowerCase().match(WORD_MATCH_REGEX) || []; } /** * Given a node, pull out any previously unrecognized common words, then * return the top word for division. * * If the node cannot be meaningfully split, the method returns null. */ export function getTopWord(node: WordTreeNode): string|null { // Short-circuit if this node has one or fewer undivided values. if (node.valueCount < 2) { return null; } // Convenience method for adding a list of words to a set (map). const addWordsToMap = (wordList: string[], wordMap: {[word: string]: boolean}) => { for (let i = 0; i < wordList.length; i++) { wordMap[wordList[i]] = true; } }; // We're going to be looking for a brand new word to split on, so first // we collect a map of ineligible words since we don't want to waste time // considering them. These are the union of all words accounted for at // this node, up through its ancestors, and its first-order children. const ineligibleWords: {[word: string]: boolean} = {}; let ancestor: WordTreeNode|null = node; while (ancestor) { addWordsToMap(ancestor.commonWords, ineligibleWords); ancestor = ancestor.parent; } for (let i = 0; i < node.children.length; i++) { addWordsToMap(node.children[i].commonWords, ineligibleWords); } // Count all words that appear in this node's values, ignoring those that // are already ineligible, and learning common words as they come up. const wordCounts: WordFrequencyCounts = {}; for (const hashKey in node.valueHash) { const {value, count, words} = node.valueHash[hashKey]; for (const word in words!) { if (word in ineligibleWords) { continue; } wordCounts[word] = (wordCounts[word] || 0) + count; if (wordCounts[word] === node.totalCount) { node.commonWords.push(word); ineligibleWords[word] = true; delete wordCounts[word]; } } } // Determine the top word. let topWord: string|null = null; let topWordCount = 0; for (const word in wordCounts) { if (wordCounts[word] > topWordCount) { topWord = word; topWordCount = wordCounts[word]; } } return topWord; } /** * Given a value hash, generate a word tree. */ export function generateWordTree(valueHash: ValueHash) { const root: WordTreeNode = { parent: null, commonWords: [], level: 1, order: 0, totalCount: 0, valueHash: {}, valueCount: 0, nonValueCount: 0, children: [], }; const tree: WordTree = { root, nodeHash: {}, highestLevel: 1, levelHash: { 1: root, } }; // Seed root node from value hash. for (const hashKey in valueHash) { if (!valueHash.hasOwnProperty(hashKey)) { continue; } const {value, count, words} = valueHash[hashKey]; if (typeof value === 'string') { root.valueHash[hashKey] = {value, count, words}; root.valueCount += count; } else { root.nonValueCount += count; } root.totalCount += count; tree.nodeHash[hashKey] = root; } let highestLevel = root.level; // If there are any non-string values, then we'll create a special node // to house them. if (root.nonValueCount) { highestLevel++; const child: WordTreeNode = { parent: root, commonWords: [], level: highestLevel, order: 0, totalCount: root.nonValueCount, valueHash: {}, valueCount: 0, nonValueCount: root.nonValueCount, children: [], }; root.nonValueCount = 0; root.children.push(child); tree.highestLevel = highestLevel; tree.levelHash[highestLevel] = child; for (const hashKey in tree.nodeHash) { if (hashKey in root.valueHash) { continue; } tree.nodeHash[hashKey] = child; } } const divisionCandidates: WordTreeNode[] = [root]; // Convenience method for determining the visible mass of a given candidate. // That is, at the current level, which candidate has the most mass. const undividedMass = (node: WordTreeNode): number => { return node.valueCount + node.nonValueCount; }; while (highestLevel < MAX_WORD_TREE_LEVEL && divisionCandidates.length) { // Pick the division candidate with the most undivided values. let candidateIndex = 0; let maxMass = undividedMass(divisionCandidates[candidateIndex]); for (let i = 1; i < divisionCandidates.length; i++) { const currentMass = undividedMass(divisionCandidates[i]); if (currentMass > maxMass) { candidateIndex = i; maxMass = currentMass; } } const candidate = divisionCandidates[candidateIndex]; // Get the top word for this candidate, while taking note of any common // words. If no top word was found, then this candidate cannot be // meaningfully further subdivided. Remove it and look for another. const topWord = getTopWord(candidate); if (!topWord) { divisionCandidates.splice(candidateIndex, 1); continue; } // Now create a new child node out of the top word. highestLevel++; const child: WordTreeNode = { parent: candidate, commonWords: [topWord], level: highestLevel, order: 0, totalCount: 0, valueHash: {}, valueCount: 0, nonValueCount: 0, children: [], }; candidate.children.push(child); divisionCandidates.push(child); for (const hashKey in candidate.valueHash) { if (!candidate.valueHash.hasOwnProperty(hashKey)) { continue; } const {value, count, words} = candidate.valueHash[hashKey]; if (!words || !(topWord in words)) { continue; } child.valueHash[hashKey] = {value, count, words}; child.valueCount += count; child.totalCount += count; delete candidate.valueHash[hashKey]; candidate.valueCount -= count; tree.nodeHash[hashKey] = child; tree.highestLevel = highestLevel; tree.levelHash[highestLevel] = child; } } // Set all the nodes' order values via depth first search. let order = 0; const updateNodeOrder = (node: WordTreeNode) => { node.order = ++order; for (let i = 0; i < node.children.length; i++) { updateNodeOrder(node.children[i]); } }; updateNodeOrder(tree.root); return tree; }
the_stack
import { Response } from "express"; import OpenApiDocument, { Operation } from "../src/OpenApiDocument"; import OpenApiValidator, { ValidatorConfig } from "../src/OpenApiValidator"; import * as parameters from "../src/parameters"; import ValidationError from "../src/ValidationError"; import openApiDocument from "./open-api-document"; const baseReq: any = { body: {}, query: {}, headers: {}, cookies: {}, params: {}, }; const baseRes = { statusCode: 200, body: {}, headers: {} }; const createTestValidator = ( document: OpenApiDocument, opts?: ValidatorConfig, ): (( method: Operation, path: string, ) => (userReq?: any) => Promise<unknown>) => { const validator = new OpenApiValidator(document, opts); return (method: Operation, path: string) => { const validate = validator.validate(method, path); return (userReq?: any) => new Promise((resolve) => { const req = { ...baseReq, ...userReq }; validate(req, {} as any, resolve); }); }; }; const getValidator = createTestValidator(openApiDocument); describe("OpenApiValidator", () => { test("can be created with valid OpenAPI document", () => { const validator = new OpenApiValidator(openApiDocument); expect(validator).toBeInstanceOf(OpenApiValidator); }); test("creating throws with Swagger 2.0 document", () => { expect(() => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const validator = new OpenApiValidator({ swagger: "2.0", info: { title: "Swagger API", version: "1.0.0" }, paths: {}, } as any); }).toThrowErrorMatchingSnapshot(); }); test("Ajv formats can be passed in", () => { const opts = { ajvOptions: { formats: { password: /[a-zA-Z0-9]{8,}/ } } }; const validator = createTestValidator(openApiDocument, opts); const validate = validator("post", "/format"); return validate({ body: { password: "abc" } }) .then((err) => { expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); return validate({ body: { password: "password123" } }); }) .then((err) => { expect(err).toBeUndefined(); return validate({ body: { d: 123.1 } }); }) .then((err) => { expect(err).toBeUndefined(); }); }); test("getting an operation object fails with invalid arguments", () => { const validator = new OpenApiValidator(openApiDocument); expect(() => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const op = (validator as any)._getOperationObject("POST", "/echo"); }).toThrowErrorMatchingSnapshot(); expect(() => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const op = (validator as any)._getOperationObject("ppost", "/echo"); }).toThrowErrorMatchingSnapshot(); expect(() => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const op = (validator as any)._getOperationObject("post", "/echoo"); }).toThrowErrorMatchingSnapshot(); }); test("trying to validate with a path that doesn't exist throws", async () => { const validator = new OpenApiValidator(openApiDocument); expect(() => { validator.validate("get", "/non-existent"); }).toThrowErrorMatchingSnapshot(); }); test("getting an operation object succeeds", () => { const validator = new OpenApiValidator(openApiDocument); const op = (validator as any)._getOperationObject("post", "/echo"); expect(op).toEqual(openApiDocument.paths["/echo"].post); }); test("validating with a simple echo endpoint", async () => { const validate = getValidator("post", "/echo"); let err = await validate({ body: { input: "hello" } }); expect(err).toBeUndefined(); err = await validate(); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validating response of echo endpoint", async () => { const validator = new OpenApiValidator(openApiDocument); const validate = validator.validateResponse("post", "/echo"); expect(() => { validate(baseRes); }).toThrowErrorMatchingSnapshot(); const err = validate({ ...baseRes, body: { output: "echo" } }); expect(err).toBeUndefined(); }); test("validating with schema as an internal reference", async () => { const validate = getValidator("post", "/internal-ref"); let err = await validate({ body: { value: 123 } }); expect(err).toBeUndefined(); err = await validate({ body: { value: "123" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("creating schema with invalid parameter location throws", () => { expect(() => { const params = [{ name: "invalid", in: "invalid" }]; parameters.buildSchema(params as any); }).toThrowErrorMatchingSnapshot(); }); test("validating query with a parameter schema", async () => { const validate = getValidator("get", "/parameters"); let err = await validate({ query: { param: "123", porom: "abc" } }); expect(err).toBeUndefined(); err = await validate({ query: { porom: "abc" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validating headers with a parameter schema", async () => { const validate = getValidator("get", "/parameters/header"); let err = await validate({ headers: { "x-param": "let-in" } }); expect(err).toBeUndefined(); err = await validate(); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validating headers with a parameter schema where the schema includes uppercase characters", async () => { const validate = getValidator("get", "/parameters/header/caseinsensitive"); let err = await validate({ headers: { "x-param": "let-in" } }); expect(err).toBeUndefined(); err = await validate(); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validating cookies with a parameter schema", async () => { const validate = getValidator("get", "/parameters/cookie"); let err = await validate({ cookies: { session: "abc123" } }); expect(err).toBeUndefined(); err = await validate(); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validating cookies with parameters schema fails with no cookie parser", async () => { const validate = getValidator("get", "/parameters/cookie"); const err = await validate({ cookies: undefined }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validating path parameters with a parameters schema", async () => { const validate = getValidator("get", "/parameters/id/{id}"); let err = await validate({ params: { id: "123" } }); expect(err).toBeUndefined(); err = await validate(); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ params: { id: "abc" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validating path parameters with a parameters schema in paths object", async () => { const validate = getValidator("get", "/parameters/all-operations-id/{pid}"); let err = await validate({ params: { pid: "abc" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ params: { pid: "123" } }); expect(err).toBeUndefined(); }); test("validating path parameters with a parameters schema in both", async () => { const validate = getValidator( "get", "/parameters/both-all-operations-id/{pid}/{id}", ); let err = await validate({ params: { pid: "abc" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ params: { pid: "123" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ params: { id: "abc" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ params: { id: "123" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ params: { id: "123", pid: "123" } }); expect(err).toBeUndefined(); }); test("overridden parameter validations", async () => { const validate = getValidator("get", "/parameters/override/{pid}"); let err = await validate({ params: { pid: "123a" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ params: { pid: "123" } }); expect(err).toBeUndefined(); }); test("parameters with refs", async () => { const validate = getValidator("get", "/parameters/with-refs"); let err = await validate({ headers: { "x-request-id": "bbb" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ headers: { "x-request-id": "123" } }); expect(err).toBeUndefined(); }); test("validating bodies with null fields and nullable property is schema", async () => { const validate = getValidator("post", "/nullable"); let err = await validate({ body: { bar: null } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { baz: null } }); expect(err).toBeUndefined(); }); test("validating query parameters with internal references", async () => { const validate = getValidator("get", "/ref-parameter"); let err = await validate({ query: { hello: "hello" } }); expect(err).toBeUndefined(); err = await validate({ query: { hello: "" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validation with multiple different rules schema", async () => { const validate = getValidator("post", "/different-rules"); let err = await validate({ query: {} }); expect(err).toBeUndefined(); err = await validate({ query: { q1: "abc1def" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ query: { q1: "abcdef" } }); expect(err).toBeUndefined(); err = await validate({ query: { q1: "ab" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ query: { q1: "abcabcabcdef" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { i: 1.2 } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { i: 256.0 } }); expect(err).toBeUndefined(); err = await validate({ body: { i: 111 } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validation with required body", async () => { const validate = getValidator("post", "/required-body"); let err = await validate({ body: undefined }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: {} }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { a: undefined } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { a: "a" } }); expect(err).toBeUndefined(); }); test("validation of numeric OpenAPI formats", async () => { const validate = getValidator("post", "/format"); let err = await validate({ body: { i32: 2147483648 } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { i32: "123" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { i32: 123 } }); expect(err).toBeUndefined(); err = await validate({ body: { i64: "123" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { i64: 123.1 } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { i64: 123 } }); expect(err).toBeUndefined(); err = await validate({ body: { f: 123 } }); expect(err).toBeUndefined(); err = await validate({ body: { f: 123.1 } }); expect(err).toBeUndefined(); err = await validate({ body: { f: 3.4038234663852886e38 } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { d: 3.4038234663852886e38 } }); expect(err).toBeUndefined(); err = await validate({ body: { d: null } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("validation of OpenAPI string formats", async () => { const validate = getValidator("post", "/format"); let err = await validate({ body: { byte: "" } }); expect(err).toBeUndefined(); err = await validate({ body: { byte: "aGVsbG8=" } }); expect(err).toBeUndefined(); err = await validate({ body: { byte: "aGVsbG8" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); const binary = Buffer.from([0x00, 0xff, 0x10, 0x88]).toString("binary"); err = await validate({ body: { binary } }); expect(err).toBeUndefined(); err = await validate({ body: { password: "password" } }); expect(err).toBeUndefined(); err = await validate({ body: { date: "98-01-01" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { date: "05/04/2014" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { date: "2015-08-02" } }); expect(err).toBeUndefined(); }); test("validating signed cookies generated by cookie-parser", async () => { const validate = getValidator("get", "/parameters/cookie"); let err = await validate({ signedCookies: { session: "abc123" } }); expect(err).toBeUndefined(); err = await validate({ signedCookies: {} }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ signedCookies: { session: "" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ cookies: { session: "" }, signedCookies: { session: "abc123" }, }); expect(err).toBeUndefined(); }); test("validating parameters with two required query parameters", async () => { const validate = getValidator("get", "/parameters/required"); let err = await validate({ query: { q1: "a" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ query: { q2: "b" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ query: { q1: "c", q2: "d" } }); expect(err).toBeUndefined(); }); test("response validation with different kinds of response objects", () => { const validator = new OpenApiValidator(openApiDocument); expect(() => { validator.validateResponse("post", "/echooo"); }).toThrowErrorMatchingSnapshot(); const validate = validator.validateResponse("post", "/responses"); expect(() => { validate({}); }).toThrowErrorMatchingSnapshot(); expect(() => { (validate as any)(); }).toThrowErrorMatchingSnapshot(); expect(() => { validate({ stat: 200, body: {}, headers: {} }); }).toThrowErrorMatchingSnapshot(); expect(() => { validate({ status: 200, headers: {} }); }).toThrowErrorMatchingSnapshot(); expect(validate({ status: 200, data: {}, headers: {} })).toBeUndefined(); expect( validate({ statusCode: 500, body: {}, headers: {} }), ).toBeUndefined(); const echoValidate = validator.validateResponse("post", "/echo"); expect( echoValidate({ status: 200, data: { output: "hello" }, headers: {} }), ).toBeUndefined(); expect( echoValidate({ statusCode: 200, body: { output: "hello" }, headers: {} }), ).toBeUndefined(); }); test("response validation with different status codes", () => { const validator = new OpenApiValidator(openApiDocument); let validate = validator.validateResponse("post", "/responses"); expect(validate(baseRes)).toBeUndefined(); expect(() => { validate({ ...baseRes, statusCode: 201 }); }).toThrowErrorMatchingSnapshot(); expect( validate({ ...baseRes, statusCode: 201, body: { hello: "hola" } }), ).toBeUndefined(); expect(validate({ ...baseRes, statusCode: 303 })).toBeUndefined(); validate = validator.validateResponse("get", "/responses/no-default"); expect(() => { validate({ ...baseReq, statusCode: 301 }); }).toThrowErrorMatchingSnapshot(); }); test("validating response headers", () => { const validator = new OpenApiValidator(openApiDocument); const validate = validator.validateResponse("post", "/responses/header"); expect(() => { validate(baseRes); }).toThrowErrorMatchingSnapshot(); expect( validate({ ...baseRes, headers: { "x-header": "heh" } }), ).toBeUndefined(); expect(() => { validate({ ...baseRes, headers: { "x-header": "heh", "x-ref-header": "as" }, }); }).toThrowErrorMatchingSnapshot(); expect( validate({ ...baseRes, headers: { "x-header": "heh", "x-ref-header": "asa" }, }), ).toBeUndefined(); }); test("validating response headers with several required headers", () => { const validator = new OpenApiValidator(openApiDocument); const validate = validator.validateResponse("post", "/responses/header2"); expect(() => { validate(baseRes); }).toThrowErrorMatchingSnapshot(); expect(() => { validate({ ...baseRes, headers: { "x-1": "a" } }); }).toThrowErrorMatchingSnapshot(); expect( validate({ ...baseRes, headers: { "x-1": "a", "x-2": "b" } }), ).toBeUndefined(); }); test("schemas with several references", async () => { const validate = getValidator("post", "/schema-references"); let err = await validate({ body: { value: "1" } }); expect(err).toBeUndefined(); err = await validate({}); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { value: "1", tag: "" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { value: "1", tag: "abc" } }); expect(err).toBeUndefined(); }); test("schemas with request body and headers references", async () => { const validate = getValidator("post", "/more-references"); let err = await validate({ body: { ping: "asd" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { ping: "pong" } }); expect(err).toBeUndefined(); const validator = new OpenApiValidator(openApiDocument); const validateResponse = validator.validateResponse( "post", "/more-references", ); expect(() => { validateResponse({ ...baseRes, headers: { "x-hullo": "a" } }); }).toThrowErrorMatchingSnapshot(); expect( validateResponse({ ...baseRes, headers: { "x-hullo": "aa" } }), ).toBeUndefined(); }); test("match() - finds and calls validate() based on request URL", async () => { const validator = new OpenApiValidator(openApiDocument); const match = validator.match(); const validateHandler = jest.fn(); const validateMock = jest.fn().mockReturnValue(validateHandler); validator.validate = validateMock; const req = { ...baseReq, method: "POST", path: "/match", body: { input: "Hello!" }, }; // eslint-disable-next-line @typescript-eslint/no-empty-function match(req, {} as Response, () => {}); expect(validateMock).toBeCalledWith("post", "/match"); expect(validateHandler).toBeCalled(); }); test("match() - does not call validate() if request does not match and yields error", async () => { const validator = new OpenApiValidator(openApiDocument); const match = validator.match(); const validateMock = jest.fn(); validator.validate = validateMock; const req = { ...baseReq, method: "POST", path: "/no-match", }; const nextMock = jest.fn(); match(req, {} as Response, nextMock); expect(validateMock).not.toHaveBeenCalled(); expect(nextMock).toHaveBeenCalledWith(expect.any(Error)); }); test("match({ allowNoMatch: true }) - does not call validate() if request does not match and does not yield error", async () => { const validator = new OpenApiValidator(openApiDocument); const match = validator.match({ allowNoMatch: true }); const validateMock = jest.fn(); validator.validate = validateMock; const req = { ...baseReq, method: "POST", path: "/no-match", }; const nextMock = jest.fn(); match(req, {} as Response, nextMock); expect(validateMock).not.toHaveBeenCalled(); expect(nextMock).toHaveBeenCalledWith(); }); test("extra OAS fields in schema", async () => { const validate = getValidator("post", "/extra-oas-fields-in-schema"); let err = await validate({ body: "aaa" }); expect(err).toBeUndefined(); err = await validate({ body: 123 }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); test("discriminator", async () => { const validate = getValidator("post", "/discriminator"); let err = await validate({ body: { foo: "x", a: "any" } }); expect(err).toBeUndefined(); err = await validate({ body: { foo: "y", b: "any" } }); expect(err).toBeUndefined(); err = await validate({ body: { foo: "z", b: "any" } }); expect(err).toBeUndefined(); err = await validate({ body: {} }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { foo: 1 } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { foo: "bar" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { foo: "x", b: "b" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); err = await validate({ body: { foo: "y", a: "a" } }); expect(err).toBeInstanceOf(ValidationError); expect(err).toMatchSnapshot(); }); });
the_stack
import SimpleSchema from 'simpl-schema'; import * as _ from 'underscore'; import { addUniversalFields, schemaDefaultValue } from '../../collectionUtils'; import { makeEditable } from '../../editor/make_editable'; import { getDefaultFilterSettings } from '../../filterSettings'; import { forumTypeSetting, hasEventsSetting } from "../../instanceSettings"; import { accessFilterMultiple, addFieldsDict, arrayOfForeignKeysField, denormalizedCountOfReferences, denormalizedField, foreignKeyField, googleLocationToMongoLocation, resolverOnlyField } from '../../utils/schemaUtils'; import { postStatuses } from '../posts/constants'; import Users from "./collection"; import { userOwnsAndInGroup } from "./helpers"; import { userOwns, userIsAdmin } from '../../vulcan-users/permissions'; import GraphQLJSON from 'graphql-type-json'; import { formGroups } from './formGroups'; import { REVIEW_NAME_IN_SITU, REVIEW_YEAR } from '../../reviewUtils'; export const MAX_NOTIFICATION_RADIUS = 300 export const karmaChangeNotifierDefaultSettings = { // One of the string keys in karmaNotificationTimingChocies updateFrequency: "daily", // Time of day at which daily/weekly batched updates are released, a number // of hours [0,24). Always in GMT, regardless of the user's time zone. // Default corresponds to 3am PST. timeOfDayGMT: 11, // A string day-of-the-week name, spelled out and capitalized like "Monday". // Always in GMT, regardless of the user's timezone (timezone matters for day // of the week because time zones could take it across midnight.) dayOfWeekGMT: "Saturday", // A boolean that determines whether we hide or show negative karma updates. // False by default because people tend to drastically overweigh negative feedback showNegativeKarma: false, }; export const defaultNotificationTypeSettings = { channel: "onsite", batchingFrequency: "realtime", timeOfDayGMT: 12, dayOfWeekGMT: "Monday", }; export interface KarmaChangeSettingsType { updateFrequency: "disabled"|"daily"|"weekly"|"realtime" timeOfDayGMT: number dayOfWeekGMT: "Monday"|"Tuesday"|"Wednesday"|"Thursday"|"Friday"|"Saturday"|"Sunday" showNegativeKarma: boolean } const karmaChangeSettingsType = new SimpleSchema({ updateFrequency: { type: String, optional: true, allowedValues: ['disabled', 'daily', 'weekly', 'realtime'] }, timeOfDayGMT: { type: SimpleSchema.Integer, optional: true, min: 0, max: 23 }, dayOfWeekGMT: { type: String, optional: true, allowedValues: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] }, showNegativeKarma: { type: Boolean, optional: true, } }) const notificationTypeSettings = new SimpleSchema({ channel: { type: String, allowedValues: ["none", "onsite", "email", "both"], }, batchingFrequency: { type: String, allowedValues: ['realtime', 'daily', 'weekly'], }, timeOfDayGMT: { type: Number, optional: true, }, dayOfWeekGMT: { type: String, optional: true, }, }) const notificationTypeSettingsField = (overrideSettings?: any) => ({ type: notificationTypeSettings, optional: true, group: formGroups.notifications, control: "NotificationTypeSettings" as keyof ComponentTypes, canRead: [userOwns, 'admins'] as FieldPermissions, canUpdate: [userOwns, 'admins'] as FieldPermissions, canCreate: ['members', 'admins'] as FieldCreatePermissions, ...schemaDefaultValue({ ...defaultNotificationTypeSettings, ...overrideSettings }) }); const partiallyReadSequenceItem = new SimpleSchema({ sequenceId: { type: String, foreignKey: "Sequences", optional: true, }, collectionId: { type: String, foreignKey: "Collections", optional: true, }, lastReadPostId: { type: String, foreignKey: "Posts", }, nextPostId: { type: String, foreignKey: "Posts", }, numRead: { type: SimpleSchema.Integer, }, numTotal: { type: SimpleSchema.Integer, }, lastReadTime: { type: Date, optional: true, }, }); export const CAREER_STAGES = [ {value: 'highSchool', label: "In high school"}, {value: 'associateDegree', label: "Pursuing an associate's degree"}, {value: 'undergradDegree', label: "Pursuing an undergraduate degree"}, {value: 'professionalDegree', label: "Pursuing a professional degree"}, {value: 'graduateDegree', label: "Pursuing a graduate degree (e.g. Master's)"}, {value: 'doctoralDegree', label: "Pursuing a doctoral degree (e.g. PhD)"}, {value: 'otherDegree', label: "Pursuing other degree/diploma"}, {value: 'earlyCareer', label: "Working (0-5 years experience)"}, {value: 'midCareer', label: "Working (6-15 years of experience)"}, {value: 'lateCareer', label: "Working (15+ years of experience)"}, {value: 'seekingWork', label: "Seeking work"}, {value: 'retired', label: "Retired"}, ] export const SOCIAL_MEDIA_PROFILE_FIELDS = { linkedinProfileURL: 'linkedin.com/in/', facebookProfileURL: 'facebook.com/', twitterProfileURL: 'twitter.com/', githubProfileURL: 'github.com/' } addFieldsDict(Users, { // TODO(EA): Allow resending of confirmation email whenConfirmationEmailSent: { type: Date, optional: true, order: 1, group: formGroups.emails, control: 'UsersEmailVerification', canRead: ['members'], // EA Forum does not care about email verification canUpdate: forumTypeSetting.get() === 'EAForum' ? [] : [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], }, // Legacy: Boolean used to indicate that post was imported from old LW database legacy: { type: Boolean, optional: true, defaultValue: false, hidden: true, canRead: [userOwns, 'admins'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], }, commentSorting: { type: String, optional: true, canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], order: 43, group: formGroups.siteCustomizations, control: "select", form: { // TODO - maybe factor out?? options: function () { // options for the select form control let commentViews = [ {value:'postCommentsTop', label: 'magical algorithm'}, {value:'postCommentsNew', label: 'most recent'}, {value:'postCommentsOld', label: 'oldest'}, ]; if (forumTypeSetting.get() === 'AlignmentForum') { return commentViews.concat([ {value:'postLWComments', label: 'magical algorithm (include LW)'} ]) } return commentViews } }, }, sortDrafts: { type: String, optional: true, canRead: [userOwns, 'admins'], canUpdate: [userOwns, 'admins'], label: "Sort Drafts by", order: 43, group: formGroups.siteCustomizations, control: "select", form: { options: function () { // options for the select form control return [ {value:'wordCount', label: 'Wordcount'}, {value:'modifiedAt', label: 'Last Modified'}, ]; } }, }, showHideKarmaOption: { type: Boolean, optional: true, label: "Enable option on posts to hide karma visibility", canRead: [userOwns, 'admins'], canUpdate: [userOwnsAndInGroup('trustLevel1'), 'sunshineRegiment', 'admins'], canCreate: ['members', 'sunshineRegiment', 'admins'], hidden: forumTypeSetting.get() !== 'EAForum', control: 'checkbox', group: formGroups.siteCustomizations, order: 69, }, // Intercom: Will the user display the intercom while logged in? hideIntercom: { order: 70, type: Boolean, optional: true, defaultValue: false, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.siteCustomizations, canCreate: ['members'], control: 'checkbox', label: "Hide Intercom" }, // This field-name is no longer accurate, but is here because we used to have that field // around and then removed `markDownCommentEditor` and merged it into this field. markDownPostEditor: { order: 71, type: Boolean, optional: true, defaultValue: false, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], control: 'checkbox', group: formGroups.siteCustomizations, label: "Activate Markdown Editor" }, hideElicitPredictions: { order: 80, type: Boolean, optional: true, defaultValue: false, canRead: [userOwns], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], control: 'checkbox', group: formGroups.siteCustomizations, label: "Hide other users' Elicit predictions until I have predicted myself", }, hideAFNonMemberInitialWarning: { order: 90, type: Boolean, optional: true, defaultValue: false, canRead: [userOwns], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], control: 'checkbox', group: formGroups.siteCustomizations, hidden: forumTypeSetting.get() !== 'AlignmentForum', label: "Hide explanations of how AIAF submissions work for non-members", //TODO: just hide this in prod }, noSingleLineComments: { order: 91, type: Boolean, optional: true, group: formGroups.siteCustomizations, defaultValue: false, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], control: 'checkbox', label: "Do not collapse comments to Single Line" }, noCollapseCommentsPosts: { order: 92, type: Boolean, optional: true, group: formGroups.siteCustomizations, defaultValue: false, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], control: 'checkbox', label: "Do not truncate comments (in large threads on Post Pages)" }, noCollapseCommentsFrontpage: { order: 93, type: Boolean, optional: true, group: formGroups.siteCustomizations, defaultValue: false, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], control: 'checkbox', label: "Do not truncate comments (on home page)" }, hideNavigationSidebar: { type: Boolean, optional: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', hidden: true, }, currentFrontpageFilter: { type: String, optional: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', hidden: true, }, frontpageFilterSettings: { type: Object, blackbox: true, optional: true, hidden: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', ...schemaDefaultValue(getDefaultFilterSettings), }, allPostsTimeframe: { type: String, optional: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', hidden: true, }, allPostsFilter: { type: String, optional: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', hidden: true, }, allPostsSorting: { type: String, optional: true, hidden: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', }, allPostsShowLowKarma: { type: Boolean, optional: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', hidden: true, }, allPostsIncludeEvents: { type: Boolean, optional: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', hidden: true, }, allPostsOpenSettings: { type: Boolean, optional: true, canRead: userOwns, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: 'guests', hidden: true, }, lastNotificationsCheck: { type: Date, optional: true, canRead: userOwns, canUpdate: userOwns, canCreate: 'guests', hidden: true, logChanges: false, }, // Karma field karma: { type: Number, optional: true, canRead: ['guests'], }, goodHeartTokens: { type: Number, optional: true, canRead: ['guests'], }, moderationStyle: { type: String, optional: true, control: "select", group: formGroups.moderationGroup, label: "Style", canRead: ['guests'], canUpdate: ['members', 'sunshineRegiment', 'admins'], canCreate: ['members', 'sunshineRegiment', 'admins'], blackbox: true, order: 55, form: { options: function () { // options for the select form control return [ {value: "", label: "No Moderation"}, {value: "easy-going", label: "Easy Going - I just delete obvious spam and trolling."}, {value: "norm-enforcing", label: "Norm Enforcing - I try to enforce particular rules (see below)"}, {value: "reign-of-terror", label: "Reign of Terror - I delete anything I judge to be annoying or counterproductive"}, ]; } }, }, moderatorAssistance: { type: Boolean, optional: true, group: formGroups.moderationGroup, label: "I'm happy for site moderators to help enforce my policy", canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members', 'sunshineRegiment', 'admins'], control: 'checkbox', order: 55, }, collapseModerationGuidelines: { type: Boolean, optional: true, group: formGroups.moderationGroup, label: "On my posts, collapse my moderation guidelines by default", canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members', 'sunshineRegiment', 'admins'], control: 'checkbox', order: 56, }, // bannedUserIds: users who are not allowed to comment on this user's posts bannedUserIds: { type: Array, group: formGroups.moderationGroup, canRead: ['guests'], canUpdate: [userOwnsAndInGroup('trustLevel1'), 'sunshineRegiment', 'admins'], canCreate: ['sunshineRegiment', 'admins'], optional: true, label: "Banned Users (All)", control: 'UsersListEditor' }, 'bannedUserIds.$': { type: String, foreignKey: "Users", optional: true }, // bannedPersonalUserIds: users who are not allowed to comment on this user's personal blog posts bannedPersonalUserIds: { type: Array, group: formGroups.moderationGroup, canRead: ['guests'], canUpdate: [userOwnsAndInGroup('canModeratePersonal'), 'sunshineRegiment', 'admins'], canCreate: ['sunshineRegiment', 'admins'], optional: true, label: "Banned Users (Personal)", control: 'UsersListEditor', tooltip: "Users who are banned from commenting on your personal blogposts (will not affect posts promoted to frontpage)" }, "bannedPersonalUserIds.$": { type: String, foreignKey: "Users", optional: true }, bookmarkedPostsMetadata: { canRead: [userOwns, 'sunshineRegiment', 'admins'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], optional: true, hidden: true, onUpdate: ({data, currentUser, oldDocument}) => { if (data?.bookmarkedPostsMetadata) { return _.uniq(data?.bookmarkedPostsMetadata, 'postId') } }, ...arrayOfForeignKeysField({ idFieldName: "bookmarkedPostsMetadata", resolverName: "bookmarkedPosts", collectionName: "Posts", type: "Post", getKey: (obj) => obj.postId }), }, "bookmarkedPostsMetadata.$": { type: Object, optional: true }, "bookmarkedPostsMetadata.$.postId": { type: String, foreignKey: "Posts", optional: true }, // Legacy ID: ID used in the original LessWrong database legacyId: { type: String, hidden: true, optional: true, canRead: ['guests'], canUpdate: ['admins'], canCreate: ['members'], }, // Deleted: Boolean indicating whether user has been deleted (initially used in the LW database transfer ) deleted: { type: Boolean, optional: true, defaultValue: false, canRead: ['guests'], canUpdate: ['admins'], label: 'Delete this user', control: 'checkbox', group: formGroups.adminOptions, }, // voteBanned: All future votes of this user have weight 0 voteBanned: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: ['sunshineRegiment', 'admins'], canCreate: ['admins'], control: 'checkbox', group: formGroups.banUser, label: 'Set all future votes of this user to have zero weight' }, // nullifyVotes: Set all historical votes of this user to 0, and make any future votes have a vote weight of 0 nullifyVotes: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: ['sunshineRegiment', 'admins'], canCreate: ['admins'], control: 'checkbox', group: formGroups.banUser, label: 'Nullify all past votes' }, // deleteContent: Flag all comments and posts from this user as deleted deleteContent: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: ['sunshineRegiment', 'admins'], canCreate: ['admins'], control: 'checkbox', group: formGroups.banUser, label: 'Delete all user content' }, // banned: Whether the user is banned or not. Can be set by moderators and admins. banned: { type: Date, optional: true, canRead: ['guests'], canUpdate: ['sunshineRegiment', 'admins'], canCreate: ['admins'], control: 'datetime', label: 'Ban user until', group: formGroups.banUser, }, // IPs: All Ips that this user has ever logged in with IPs: resolverOnlyField({ type: Array, graphQLtype: '[String]', group: formGroups.banUser, canRead: ['sunshineRegiment', 'admins'], resolver: async (user: DbUser, args: void, context: ResolverContext) => { const { currentUser, LWEvents } = context; const events: Array<DbLWEvent> = await LWEvents.find( {userId: user._id, name: 'login'}, { limit: 10, sort: {createdAt: -1} } ).fetch() const filteredEvents = await accessFilterMultiple(currentUser, LWEvents, events, context); const IPs = filteredEvents.map(event => event.properties?.ip); const uniqueIPs = _.uniq(IPs); return uniqueIPs }, }), 'IPs.$': { type: String, optional: true, }, auto_subscribe_to_my_posts: { label: "Auto-subscribe to comments on my posts", group: formGroups.notifications, type: Boolean, optional: true, control: "checkbox", canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], beforeComponent: "ManageSubscriptionsLink", ...schemaDefaultValue(true), }, auto_subscribe_to_my_comments: { label: "Auto-subscribe to replies to my comments", group: formGroups.notifications, type: Boolean, optional: true, control: "checkbox", canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], ...schemaDefaultValue(true), }, autoSubscribeAsOrganizer: { label: `Auto-subscribe to posts/events in groups I organize`, group: formGroups.notifications, type: Boolean, optional: true, control: "checkbox", canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: !hasEventsSetting.get(), ...schemaDefaultValue(true), }, notificationCommentsOnSubscribedPost: { label: `Comments on posts/events I'm subscribed to`, ...notificationTypeSettingsField(), }, notificationShortformContent: { label: "Shortform by users I'm subscribed to", ...notificationTypeSettingsField(), }, notificationRepliesToMyComments: { label: "Replies to my comments", ...notificationTypeSettingsField(), }, notificationRepliesToSubscribedComments: { label: "Replies to comments I'm subscribed to", ...notificationTypeSettingsField(), }, notificationSubscribedUserPost: { label: "Posts by users I'm subscribed to", ...notificationTypeSettingsField(), }, notificationPostsInGroups: { label: "Posts/events in groups I'm subscribed to", hidden: !hasEventsSetting.get(), ...notificationTypeSettingsField({ channel: "both" }), }, notificationSubscribedTagPost: { label: "Posts added to tags I'm subscribed to", ...notificationTypeSettingsField(), }, notificationPrivateMessage: { label: "Private messages", ...notificationTypeSettingsField({ channel: "both" }), }, notificationSharedWithMe: { label: "Draft shared with me", ...notificationTypeSettingsField({ channel: "both" }), }, notificationAlignmentSubmissionApproved: { label: "Alignment Forum submission approvals", hidden: forumTypeSetting.get() === 'EAForum', ...notificationTypeSettingsField({ channel: "both"}) }, notificationEventInRadius: { label: "New events in my notification radius", hidden: !hasEventsSetting.get(), ...notificationTypeSettingsField({ channel: "both" }), }, notificationRSVPs: { label: "New RSVP responses to my events", hidden: !hasEventsSetting.get(), ...notificationTypeSettingsField({ channel: "both" }), }, notificationGroupAdministration: { label: "Group administration notifications", hidden: !hasEventsSetting.get(), ...notificationTypeSettingsField({ channel: "both" }), }, notificationPostsNominatedReview: { label: `Nominations of my posts for the ${REVIEW_NAME_IN_SITU}`, // Hide this while review is inactive hidden: true, ...notificationTypeSettingsField({ channel: "both" }), }, // Karma-change notifier settings karmaChangeNotifierSettings: { group: formGroups.notifications, type: karmaChangeSettingsType, // See KarmaChangeNotifierSettings.tsx optional: true, control: "KarmaChangeNotifierSettings", canRead: [userOwns, 'admins'], canUpdate: [userOwns, 'admins'], canCreate: ['guests'], ...schemaDefaultValue(karmaChangeNotifierDefaultSettings) }, // Time at which the karma-change notification was last opened (clicked) karmaChangeLastOpened: { hidden: true, type: Date, optional: true, canCreate: ['guests'], canUpdate: [userOwns, 'admins'], canRead: [userOwns, 'admins'], logChanges: false, }, // If, the last time you opened the karma-change notifier, you saw more than // just the most recent batch (because there was a batch you hadn't viewed), // the start of the date range of that batch. karmaChangeBatchStart: { hidden: true, type: Date, optional: true, canCreate: ['guests'], canUpdate: [userOwns, 'admins'], canRead: [userOwns, 'admins'], logChanges: false, }, // Email settings emailSubscribedToCurated: { type: Boolean, optional: true, group: formGroups.emails, control: 'EmailConfirmationRequiredCheckbox', label: "Email me new posts in Curated", canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: ['AlignmentForum', 'EAForum'].includes(forumTypeSetting.get()), canRead: ['members'], }, // Not reusing curated, because we might actually use that as well subscribedToDigest: { type: Boolean, optional: true, group: formGroups.emails, label: "Subscribe to the EA Forum Digest emails", canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: forumTypeSetting.get() !== 'EAForum', canRead: ['members'], ...schemaDefaultValue(false) }, unsubscribeFromAll: { type: Boolean, optional: true, group: formGroups.emails, label: "Do not send me any emails (unsubscribe from all)", canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canRead: [userOwns, 'sunshineRegiment', 'admins'], }, hideSubscribePoke: { type: Boolean, optional: true, hidden: true, canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canRead: [userOwns, 'sunshineRegiment', 'admins'], ...schemaDefaultValue(false), }, hideMeetupsPoke: { type: Boolean, optional: true, hidden: true, canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canRead: [userOwns, 'sunshineRegiment', 'admins'], ...schemaDefaultValue(false), }, // frontpagePostCount: count of how many posts of yours were posted on the frontpage frontpagePostCount: { type: Number, denormalized: true, optional: true, onInsert: (document, currentUser) => 0, ...denormalizedCountOfReferences({ fieldName: "frontpagePostCount", collectionName: "Users", foreignCollectionName: "Posts", foreignTypeName: "post", foreignFieldName: "userId", filterFn: post => !!post.frontpageDate }), canRead: ['guests'], }, // sequenceCount: count of how many non-draft, non-deleted sequences you have sequenceCount: { ...denormalizedCountOfReferences({ fieldName: "sequenceCount", collectionName: "Users", foreignCollectionName: "Sequences", foreignTypeName: "sequence", foreignFieldName: "userId", filterFn: sequence => !sequence.draft && !sequence.isDeleted }), canRead: ['guests'], }, // sequenceDraftCount: count of how many draft, non-deleted sequences you have sequenceDraftCount: { ...denormalizedCountOfReferences({ fieldName: "sequenceDraftCount", collectionName: "Users", foreignCollectionName: "Sequences", foreignTypeName: "sequence", foreignFieldName: "userId", filterFn: sequence => sequence.draft && !sequence.isDeleted }), canRead: ['guests'], }, // Should match googleLocation/location // Determines which events are considered nearby for default sorting on the community page // Determines where the community map is centered/zoomed in on by default // Not shown to other users mongoLocation: { type: Object, canRead: [userOwns, 'sunshineRegiment', 'admins'], blackbox: true, optional: true, ...denormalizedField({ needsUpdate: data => ('googleLocation' in data), getValue: async (user) => { if (user.googleLocation) return googleLocationToMongoLocation(user.googleLocation) return null } }), }, // Is the canonical value for denormalized mongoLocation and location // Edited from the /events page to choose where to show events near googleLocation: { type: Object, form: { stringVersionFieldName: "location", }, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.siteCustomizations, hidden: !hasEventsSetting.get(), label: "Account location (used for location-based recommendations)", control: 'LocationFormComponent', blackbox: true, optional: true, order: 100, }, location: { type: String, canRead: [userOwns, 'sunshineRegiment', 'admins'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], hidden: true, optional: true }, // Used to place a map marker pin on the where-are-other-users map. // Public. mapLocation: { type: Object, canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: forumTypeSetting.get() === "EAForum" ? formGroups.aboutMe : formGroups.siteCustomizations, order: forumTypeSetting.get() === "EAForum" ? 8 : 101, label: "Public map location", control: 'LocationFormComponent', blackbox: true, optional: true, hidden: forumTypeSetting.get() === "EAForum" }, mapLocationSet: { type: Boolean, canRead: ['guests'], ...denormalizedField({ needsUpdate: data => ('mapLocation' in data), getValue: async (user) => { return !!user.mapLocation } }), }, mapMarkerText: { type: String, canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true, label: "Your text on the community map", control: "MuiTextField", optional: true, order: 44 }, htmlMapMarkerText: { type: String, canRead: ['guests'], optional: true, denormalized: true }, nearbyEventsNotifications: { type: Boolean, canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true, optional: true, ...schemaDefaultValue(false), }, // Should probably be merged with the other location field. nearbyEventsNotificationsLocation: { type: Object, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true, control: 'LocationFormComponent', blackbox: true, optional: true, }, nearbyEventsNotificationsMongoLocation: { type: Object, canRead: [userOwns], blackbox: true, optional: true, ...denormalizedField({ needsUpdate: data => ('nearbyEventsNotificationsLocation' in data), getValue: async (user) => { if (user.nearbyEventsNotificationsLocation) return googleLocationToMongoLocation(user.nearbyEventsNotificationsLocation) } }), }, nearbyEventsNotificationsRadius: { type: Number, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true, optional: true, min: 0, max: MAX_NOTIFICATION_RADIUS }, nearbyPeopleNotificationThreshold: { type: Number, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true, optional: true }, hideFrontpageMap: { type: Boolean, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], optional: true, order: 44, group: formGroups.default, hidden: true, label: "Hide the frontpage map" }, hideTaggingProgressBar: { type: Boolean, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], optional: true, hidden: forumTypeSetting.get() === "EAForum", label: "Hide the tagging progress bar", order: 45, group: formGroups.siteCustomizations }, hideFrontpageBookAd: { // this was for the 2018 book, no longer relevant type: Boolean, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], // canUpdate: [userOwns, 'sunshineRegiment', 'admins'], optional: true, order: 46, hidden: forumTypeSetting.get() === "EAForum", group: formGroups.siteCustomizations, label: "Hide the frontpage book ad" }, hideFrontpageBook2019Ad: { type: Boolean, canRead: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], optional: true, order: 47, hidden: forumTypeSetting.get() === "EAForum", group: formGroups.siteCustomizations, label: "Hide the frontpage book ad" }, sunshineNotes: { type: String, canRead: ['admins', 'sunshineRegiment'], canUpdate: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, optional: true, ...schemaDefaultValue(""), }, sunshineFlagged: { type: Boolean, canRead: ['admins', 'sunshineRegiment'], canUpdate: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, optional: true, ...schemaDefaultValue(false), }, needsReview: { type: Boolean, canRead: ['admins', 'sunshineRegiment'], canUpdate: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, optional: true, ...schemaDefaultValue(false), }, sunshineSnoozed: { type: Boolean, canRead: ['admins', 'sunshineRegiment'], canUpdate: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, optional: true, ...schemaDefaultValue(false), }, // Set after a moderator has approved or purged a new user. NB: reviewed does // not imply approval, the user might have been banned reviewedByUserId: { ...foreignKeyField({ idFieldName: "reviewedByUserId", resolverName: "reviewedByUser", collectionName: "Users", type: "User", nullable: true, }), optional: true, canRead: ['sunshineRegiment', 'admins', 'guests'], canUpdate: ['sunshineRegiment', 'admins'], canCreate: ['sunshineRegiment', 'admins'], group: formGroups.adminOptions, }, isReviewed: resolverOnlyField({ type: Boolean, canRead: [userOwns, 'sunshineRegiment', 'admins'], resolver: (user, args, context: ResolverContext) => !!user.reviewedByUserId, }), reviewedAt: { type: Date, canRead: ['admins', 'sunshineRegiment'], canUpdate: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, optional: true }, // A number from 0 to 1, where 0 is almost certainly spam, and 1 is almost // certainly not-spam. This is the same scale as ReCaptcha, except that it // also includes post-signup activity like moderator approval, upvotes, etc. // Scale: // 0 Banned and purged user // 0-0.8: Unreviewed user, based on ReCaptcha rating on signup (times 0.8) // 0.9: Reviewed user // 1.0: Reviewed user with 20+ karma spamRiskScore: resolverOnlyField({ type: Number, graphQLtype: "Float", canRead: ['guests'], resolver: (user: DbUser, args: void, context: ResolverContext) => { const isReviewed = !!user.reviewedByUserId; const { karma, signUpReCaptchaRating } = user; if (user.deleteContent && user.banned) return 0.0; else if (userIsAdmin(user)) return 1.0; else if (isReviewed && karma>=20) return 1.0; else if (isReviewed && karma>=0) return 0.9; else if (isReviewed) return 0.8; else if (signUpReCaptchaRating !== null && signUpReCaptchaRating !== undefined && signUpReCaptchaRating>=0) { // Rescale recaptcha ratings to [0,.8] return signUpReCaptchaRating * 0.8; } else { // No recaptcha rating present; score it .8 return 0.8; } } }), allVotes: resolverOnlyField({ type: Array, graphQLtype: '[Vote]', canRead: ['admins', 'sunshineRegiment'], resolver: async (document, args, context: ResolverContext) => { const { Votes, currentUser } = context; const votes = await Votes.find({ userId: document._id, cancelled: false, }).fetch(); if (!votes.length) return []; return await accessFilterMultiple(currentUser, Votes, votes, context); }, }), 'allVotes.$': { type: Object, optional: true }, afKarma: { type: Number, optional: true, label: "Alignment Base Score", defaultValue: false, canRead: ['guests'], }, voteCount: { type: Number, denormalized: true, optional: true, label: "Small Upvote Count", canRead: ['admins', 'sunshineRegiment'], }, smallUpvoteCount: { type: Number, denormalized: true, optional: true, canRead: ['admins', 'sunshineRegiment'], }, smallDownvoteCount: { type: Number, denormalized: true, optional: true, canRead: ['admins', 'sunshineRegiment'], }, bigUpvoteCount: { type: Number, denormalized: true, optional: true, canRead: ['admins', 'sunshineRegiment'], }, bigDownvoteCount: { type: Number, denormalized: true, optional: true, canRead: ['admins', 'sunshineRegiment'], }, // Full Name field to display full name for alignment forum users fullName: { type: String, optional: true, group: formGroups.default, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment'], hidden: !['LessWrong', 'AlignmentForum'].includes(forumTypeSetting.get()), order: 39, }, shortformFeedId: { ...foreignKeyField({ idFieldName: "shortformFeedId", resolverName: "shortformFeed", collectionName: "Posts", type: "Post", nullable: true, }), optional: true, viewableBy: ['guests'], insertableBy: ['admins', 'sunshineRegiment'], editableBy: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, }, viewUnreviewedComments: { type: Boolean, optional: true, viewableBy: ['guests'], insertableBy: ['admins', 'sunshineRegiment'], editableBy: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, order: 0, }, partiallyReadSequences: { type: Array, canRead: [userOwns], canUpdate: [userOwns], optional: true, hidden: true, }, "partiallyReadSequences.$": { type: partiallyReadSequenceItem, optional: true, }, beta: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], tooltip: "Get early access to new in-development features", group: formGroups.siteCustomizations, label: "Opt into experimental features", order: 70, }, reviewVotesQuadratic: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true }, reviewVotesQuadratic2019: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true }, reviewVoteCount:resolverOnlyField({ type: Number, canRead: ['admins', 'sunshineRegiment'], resolver: async (document, args, context: ResolverContext) => { const { ReviewVotes } = context; const voteCount = await ReviewVotes.find({ userId: document._id, year: REVIEW_YEAR+"" }).count(); return voteCount } }), reviewVotesQuadratic2020: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], hidden: true }, petrovPressedButtonDate: { type: Date, optional: true, control: 'datetime', canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.adminOptions, hidden: true }, petrovLaunchCodeDate: { type: Date, optional: true, control: 'datetime', canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.adminOptions, hidden: true }, defaultToCKEditor: { // this fieldis deprecated type: Boolean, optional: true, canRead: ['guests'], canUpdate: ['admins'], group: formGroups.adminOptions, label: "Activate CKEditor by default" }, // ReCaptcha v3 Integration // From 0 to 1. Lower is spammier, higher is humaner. signUpReCaptchaRating: { type: Number, optional: true, canRead: ['guests'], }, oldSlugs: { type: Array, optional: true, canRead: ['guests'], onUpdate: ({data, oldDocument}) => { if (data.slug && data.slug !== oldDocument.slug) { return [...(oldDocument.oldSlugs || []), oldDocument.slug] } } }, 'oldSlugs.$': { type: String, optional: true, canRead: ['guests'], }, noExpandUnreadCommentsReview: { type: Boolean, optional: true, defaultValue: false, hidden: true, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], canCreate: ['members'], }, postCount: { ...denormalizedCountOfReferences({ fieldName: "postCount", collectionName: "Users", foreignCollectionName: "Posts", foreignTypeName: "post", foreignFieldName: "userId", filterFn: (post) => (!post.draft && post.status===postStatuses.STATUS_APPROVED), }), viewableBy: ['guests'], }, maxPostCount: { ...denormalizedCountOfReferences({ fieldName: "maxPostCount", collectionName: "Users", foreignCollectionName: "Posts", foreignTypeName: "post", foreignFieldName: "userId" }), viewableBy: ['guests'], ...schemaDefaultValue(0) }, // The user's associated posts (GraphQL only) posts: { type: Object, optional: true, viewableBy: ['guests'], resolveAs: { arguments: 'limit: Int = 5', type: '[Post]', resolver: async (user: DbUser, args: { limit: number }, context: ResolverContext): Promise<Array<DbPost>> => { const { limit } = args; const { currentUser, Posts } = context; const posts = await Posts.find({ userId: user._id }, { limit }).fetch(); return await accessFilterMultiple(currentUser, Posts, posts, context); } } }, commentCount: { ...denormalizedCountOfReferences({ fieldName: "commentCount", collectionName: "Users", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "userId", filterFn: comment => !comment.deleted }), canRead: ['guests'], }, maxCommentCount: { ...denormalizedCountOfReferences({ fieldName: "maxCommentCount", collectionName: "Users", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "userId" }), canRead: ['guests'], ...schemaDefaultValue(0) }, tagRevisionCount: { ...denormalizedCountOfReferences({ fieldName: "tagRevisionCount", collectionName: "Users", foreignCollectionName: "Revisions", foreignTypeName: "revision", foreignFieldName: "userId", filterFn: revision => revision.collectionName === "Tags" }), canRead: ['guests'] }, abTestKey: { type: String, optional: true, canRead: [userOwns, 'sunshineRegiment', 'admins'], canUpdate: ['admins'], group: formGroups.adminOptions, }, abTestOverrides: { type: GraphQLJSON, //Record<string,number> optional: true, hidden: true, canRead: [userOwns], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], blackbox: true, }, reenableDraftJs: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], tooltip: "Restore the old Draft-JS based editor", group: formGroups.siteCustomizations, label: "Restore the previous WYSIWYG editor", order: 72, }, walledGardenInvite: { type: Boolean, optional:true, canRead: ['guests'], canUpdate: ['admins'], group: formGroups.adminOptions, }, hideWalledGardenUI: { type: Boolean, optional:true, canRead: ['guests'], // canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.siteCustomizations, hidden: forumTypeSetting.get() === "EAForum", }, walledGardenPortalOnboarded: { type: Boolean, optional:true, canRead: ['guests'], hidden: true, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], }, taggingDashboardCollapsed: { type: Boolean, optional:true, canRead: ['guests'], hidden: true, canUpdate: [userOwns, 'sunshineRegiment', 'admins'], }, usernameUnset: { type: Boolean, optional: true, canRead: ['members'], hidden: true, canUpdate: ['sunshineRegiment', 'admins'], ...schemaDefaultValue(false), }, paymentEmail: { type: String, optional: true, canRead: [userOwns, 'sunshineRegiment', 'admins'], canUpdate: [userOwns, 'admins'], label: "Payment Contact Email", tooltip: "An email you'll definitely check where you can receive information about receiving payments", group: formGroups.paymentInfo, }, paymentInfo: { type: String, optional: true, canRead: [userOwns, 'sunshineRegiment', 'admins'], canUpdate: [userOwns, 'admins'], label: "PayPal Info", tooltip: "Your PayPal account info, for sending small payments", group: formGroups.paymentInfo, }, jobTitle: { type: String, hidden: true, optional: true, canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.aboutMe, order: 1, label: 'Role' }, organization: { type: String, hidden: true, optional: true, canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.aboutMe, order: 2, }, careerStage: { type: Array, hidden: true, optional: true, canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], group: formGroups.aboutMe, order: 3, control: 'FormComponentMultiSelect', placeholder: "Career stage", form: { separator: '\r\n', options: CAREER_STAGES }, }, 'careerStage.$': { type: String, optional: true, }, bio: { type: String, viewableBy: ['guests'], optional: true, hidden: true, }, htmlBio: { type: String, viewableBy: ['guests'], optional: true, hidden: true, }, // These are the groups displayed in the user's profile (i.e. this field is informational only). // This does NOT affect permissions - use the organizerIds field on localgroups for that. organizerOfGroupIds: { ...arrayOfForeignKeysField({ idFieldName: "organizerOfGroupIds", resolverName: "organizerOfGroups", collectionName: "Localgroups", type: "Localgroup" }), hidden: true, optional: true, viewableBy: ['guests'], insertableBy: ['members'], editableBy: ['members'], group: formGroups.aboutMe, order: 7, control: "SelectLocalgroup", label: "Organizer of", tooltip: "If you organize a group that is missing from this list, please contact the EA Forum team.", form: { useDocumentAsUser: true, separator: '\r\n', multiselect: true }, }, 'organizerOfGroupIds.$': { type: String, foreignKey: "Localgroups", optional: true, }, website: { type: String, hidden: true, optional: true, control: 'PrefixedInput', canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], form: { inputPrefix: 'https://' }, group: formGroups.aboutMe, order: 9 }, linkedinProfileURL: { type: String, hidden: true, optional: true, control: 'PrefixedInput', canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], form: { inputPrefix: SOCIAL_MEDIA_PROFILE_FIELDS.linkedinProfileURL }, group: formGroups.socialMedia }, facebookProfileURL: { type: String, hidden: true, optional: true, control: 'PrefixedInput', canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], form: { inputPrefix: SOCIAL_MEDIA_PROFILE_FIELDS.facebookProfileURL }, group: formGroups.socialMedia }, twitterProfileURL: { type: String, hidden: true, optional: true, control: 'PrefixedInput', canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], form: { inputPrefix: SOCIAL_MEDIA_PROFILE_FIELDS.twitterProfileURL }, group: formGroups.socialMedia }, githubProfileURL: { type: String, hidden: true, optional: true, control: 'PrefixedInput', canCreate: ['members'], canRead: ['guests'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], form: { inputPrefix: SOCIAL_MEDIA_PROFILE_FIELDS.githubProfileURL }, group: formGroups.socialMedia }, }); makeEditable({ collection: Users, options: { // Determines whether to use the comment editor configuration (e.g. Toolbars) commentEditor: true, // Determines whether to use the comment editor styles (e.g. Fonts) commentStyles: true, formGroup: formGroups.moderationGroup, order: 50, fieldName: "moderationGuidelines", permissions: { viewableBy: ['guests'], editableBy: [userOwns, 'sunshineRegiment', 'admins'], insertableBy: [userOwns, 'sunshineRegiment', 'admins'] } } }) makeEditable({ collection: Users, options: { commentEditor: true, commentStyles: true, formGroup: formGroups.aboutMe, hidden: true, order: 5, fieldName: 'howOthersCanHelpMe', label: "How others can help me", hintText: "Ex: I am looking for opportunities to do...", permissions: { viewableBy: ['guests'], editableBy: [userOwns, 'sunshineRegiment', 'admins'], insertableBy: [userOwns, 'sunshineRegiment', 'admins'] }, } }) makeEditable({ collection: Users, options: { commentEditor: true, commentStyles: true, formGroup: formGroups.aboutMe, hidden: true, order: 6, fieldName: 'howICanHelpOthers', label: "How I can help others", hintText: "Ex: Reach out to me if you have questions about...", permissions: { viewableBy: ['guests'], editableBy: [userOwns, 'sunshineRegiment', 'admins'], insertableBy: [userOwns, 'sunshineRegiment', 'admins'] }, } }) // biography: Some text the user provides for their profile page and to display // when people hover over their name. // // Replaces the old "bio" and "htmlBio" fields, which were markdown only, and // which now exist as resolver-only fields for back-compatibility. makeEditable({ collection: Users, options: { commentEditor: true, commentStyles: true, hidden: forumTypeSetting.get() === "EAForum", order: forumTypeSetting.get() === "EAForum" ? 4 : 40, formGroup: forumTypeSetting.get() === "EAForum" ? formGroups.aboutMe : formGroups.default, fieldName: "biography", label: "Bio", hintText: "Tell us about yourself", permissions: { viewableBy: ['guests'], editableBy: [userOwns, 'sunshineRegiment', 'admins'], insertableBy: [userOwns, 'sunshineRegiment', 'admins'] }, } }) addUniversalFields({collection: Users})
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * ClassicAdministrators * __NOTE__: An instance of this class is automatically created for an * instance of the AuthorizationManagementClient. */ export interface ClassicAdministrators { /** * Gets service administrator, account administrator, and co-administrators for * the subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ClassicAdministratorListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ClassicAdministratorListResult>>; /** * Gets service administrator, account administrator, and co-administrators for * the subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ClassicAdministratorListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ClassicAdministratorListResult} [result] - The deserialized result object if an error did not occur. * See {@link ClassicAdministratorListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ClassicAdministratorListResult>; list(callback: ServiceCallback<models.ClassicAdministratorListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ClassicAdministratorListResult>): void; /** * Gets service administrator, account administrator, and co-administrators for * the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ClassicAdministratorListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ClassicAdministratorListResult>>; /** * Gets service administrator, account administrator, and co-administrators for * the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ClassicAdministratorListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ClassicAdministratorListResult} [result] - The deserialized result object if an error did not occur. * See {@link ClassicAdministratorListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ClassicAdministratorListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.ClassicAdministratorListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ClassicAdministratorListResult>): void; } /** * @class * ProviderOperationsMetadataOperations * __NOTE__: An instance of this class is automatically created for an * instance of the AuthorizationManagementClient. */ export interface ProviderOperationsMetadataOperations { /** * Gets provider operations metadata for the specified resource provider. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specifies whether to expand the values. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProviderOperationsMetadata>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceProviderNamespace: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProviderOperationsMetadata>>; /** * Gets provider operations metadata for the specified resource provider. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specifies whether to expand the values. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProviderOperationsMetadata} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProviderOperationsMetadata} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationsMetadata} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceProviderNamespace: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ProviderOperationsMetadata>; get(resourceProviderNamespace: string, callback: ServiceCallback<models.ProviderOperationsMetadata>): void; get(resourceProviderNamespace: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProviderOperationsMetadata>): void; /** * Gets provider operations metadata for all resource providers. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specifies whether to expand the values. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProviderOperationsMetadataListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProviderOperationsMetadataListResult>>; /** * Gets provider operations metadata for all resource providers. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specifies whether to expand the values. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProviderOperationsMetadataListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProviderOperationsMetadataListResult} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationsMetadataListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ProviderOperationsMetadataListResult>; list(callback: ServiceCallback<models.ProviderOperationsMetadataListResult>): void; list(options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProviderOperationsMetadataListResult>): void; /** * Gets provider operations metadata for all resource providers. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProviderOperationsMetadataListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProviderOperationsMetadataListResult>>; /** * Gets provider operations metadata for all resource providers. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProviderOperationsMetadataListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProviderOperationsMetadataListResult} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationsMetadataListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProviderOperationsMetadataListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.ProviderOperationsMetadataListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProviderOperationsMetadataListResult>): void; } /** * @class * RoleAssignments * __NOTE__: An instance of this class is automatically created for an * instance of the AuthorizationManagementClient. */ export interface RoleAssignments { /** * Gets role assignments for a resource. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} parentResourcePath The parent resource identity. * * @param {string} resourceType The resource type of the resource. * * @param {string} resourceName The name of the resource to get role * assignments for. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceWithHttpOperationResponse(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets role assignments for a resource. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} parentResourcePath The parent resource identity. * * @param {string} resourceType The resource type of the resource. * * @param {string} resourceName The name of the resource to get role * assignments for. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, callback: ServiceCallback<models.RoleAssignmentListResult>): void; listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; /** * Gets role assignments for a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets role assignments for a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroup(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; listForResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.RoleAssignmentListResult>): void; listForResourceGroup(resourceGroupName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; /** * Deletes a role assignment. * * @param {string} scope The scope of the role assignment to delete. * * @param {string} roleAssignmentName The name of the role assignment to * delete. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(scope: string, roleAssignmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignment>>; /** * Deletes a role assignment. * * @param {string} scope The scope of the role assignment to delete. * * @param {string} roleAssignmentName The name of the role assignment to * delete. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignment} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(scope: string, roleAssignmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignment>; deleteMethod(scope: string, roleAssignmentName: string, callback: ServiceCallback<models.RoleAssignment>): void; deleteMethod(scope: string, roleAssignmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignment>): void; /** * Creates a role assignment. * * @param {string} scope The scope of the role assignment to create. The scope * can be any REST resource instance. For example, use * '/subscriptions/{subscription-id}/' for a subscription, * '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for * a resource group, and * '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' * for a resource. * * @param {string} roleAssignmentName The name of the role assignment to * create. It can be any valid GUID. * * @param {object} parameters Parameters for the role assignment. * * @param {string} parameters.roleDefinitionId The role definition ID used in * the role assignment. * * @param {string} parameters.principalId The principal ID assigned to the * role. This maps to the ID inside the Active Directory. It can point to a * user, service principal, or security group. * * @param {string} [parameters.principalType] The principal type of the * assigned principal ID. Possible values include: 'User', 'Group', * 'ServicePrincipal', 'Unknown', 'DirectoryRoleTemplate', 'ForeignGroup', * 'Application', 'MSI', 'DirectoryObjectOrGroup', 'Everyone' * * @param {boolean} [parameters.canDelegate] The delgation flag used for * creating a role assignment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(scope: string, roleAssignmentName: string, parameters: models.RoleAssignmentCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignment>>; /** * Creates a role assignment. * * @param {string} scope The scope of the role assignment to create. The scope * can be any REST resource instance. For example, use * '/subscriptions/{subscription-id}/' for a subscription, * '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for * a resource group, and * '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' * for a resource. * * @param {string} roleAssignmentName The name of the role assignment to * create. It can be any valid GUID. * * @param {object} parameters Parameters for the role assignment. * * @param {string} parameters.roleDefinitionId The role definition ID used in * the role assignment. * * @param {string} parameters.principalId The principal ID assigned to the * role. This maps to the ID inside the Active Directory. It can point to a * user, service principal, or security group. * * @param {string} [parameters.principalType] The principal type of the * assigned principal ID. Possible values include: 'User', 'Group', * 'ServicePrincipal', 'Unknown', 'DirectoryRoleTemplate', 'ForeignGroup', * 'Application', 'MSI', 'DirectoryObjectOrGroup', 'Everyone' * * @param {boolean} [parameters.canDelegate] The delgation flag used for * creating a role assignment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignment} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(scope: string, roleAssignmentName: string, parameters: models.RoleAssignmentCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignment>; create(scope: string, roleAssignmentName: string, parameters: models.RoleAssignmentCreateParameters, callback: ServiceCallback<models.RoleAssignment>): void; create(scope: string, roleAssignmentName: string, parameters: models.RoleAssignmentCreateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignment>): void; /** * Get the specified role assignment. * * @param {string} scope The scope of the role assignment. * * @param {string} roleAssignmentName The name of the role assignment to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(scope: string, roleAssignmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignment>>; /** * Get the specified role assignment. * * @param {string} scope The scope of the role assignment. * * @param {string} roleAssignmentName The name of the role assignment to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignment} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(scope: string, roleAssignmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignment>; get(scope: string, roleAssignmentName: string, callback: ServiceCallback<models.RoleAssignment>): void; get(scope: string, roleAssignmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignment>): void; /** * Deletes a role assignment. * * @param {string} roleId The ID of the role assignment to delete. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteByIdWithHttpOperationResponse(roleId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignment>>; /** * Deletes a role assignment. * * @param {string} roleId The ID of the role assignment to delete. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignment} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteById(roleId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignment>; deleteById(roleId: string, callback: ServiceCallback<models.RoleAssignment>): void; deleteById(roleId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignment>): void; /** * Creates a role assignment by ID. * * @param {string} roleId The ID of the role assignment to create. * * @param {object} parameters Parameters for the role assignment. * * @param {string} parameters.roleDefinitionId The role definition ID used in * the role assignment. * * @param {string} parameters.principalId The principal ID assigned to the * role. This maps to the ID inside the Active Directory. It can point to a * user, service principal, or security group. * * @param {string} [parameters.principalType] The principal type of the * assigned principal ID. Possible values include: 'User', 'Group', * 'ServicePrincipal', 'Unknown', 'DirectoryRoleTemplate', 'ForeignGroup', * 'Application', 'MSI', 'DirectoryObjectOrGroup', 'Everyone' * * @param {boolean} [parameters.canDelegate] The delgation flag used for * creating a role assignment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createByIdWithHttpOperationResponse(roleId: string, parameters: models.RoleAssignmentCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignment>>; /** * Creates a role assignment by ID. * * @param {string} roleId The ID of the role assignment to create. * * @param {object} parameters Parameters for the role assignment. * * @param {string} parameters.roleDefinitionId The role definition ID used in * the role assignment. * * @param {string} parameters.principalId The principal ID assigned to the * role. This maps to the ID inside the Active Directory. It can point to a * user, service principal, or security group. * * @param {string} [parameters.principalType] The principal type of the * assigned principal ID. Possible values include: 'User', 'Group', * 'ServicePrincipal', 'Unknown', 'DirectoryRoleTemplate', 'ForeignGroup', * 'Application', 'MSI', 'DirectoryObjectOrGroup', 'Everyone' * * @param {boolean} [parameters.canDelegate] The delgation flag used for * creating a role assignment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignment} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createById(roleId: string, parameters: models.RoleAssignmentCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignment>; createById(roleId: string, parameters: models.RoleAssignmentCreateParameters, callback: ServiceCallback<models.RoleAssignment>): void; createById(roleId: string, parameters: models.RoleAssignmentCreateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignment>): void; /** * Gets a role assignment by ID. * * @param {string} roleId The ID of the role assignment to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getByIdWithHttpOperationResponse(roleId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignment>>; /** * Gets a role assignment by ID. * * @param {string} roleId The ID of the role assignment to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignment} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getById(roleId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignment>; getById(roleId: string, callback: ServiceCallback<models.RoleAssignment>): void; getById(roleId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignment>): void; /** * Gets all role assignments for the subscription. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets all role assignments for the subscription. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; list(callback: ServiceCallback<models.RoleAssignmentListResult>): void; list(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; /** * Gets role assignments for a scope. * * @param {string} scope The scope of the role assignments. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForScopeWithHttpOperationResponse(scope: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets role assignments for a scope. * * @param {string} scope The scope of the role assignments. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all role assignments at or above the scope. Use * $filter=principalId eq {id} to return all role assignments at, above or * below the scope for the specified principal. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForScope(scope: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; listForScope(scope: string, callback: ServiceCallback<models.RoleAssignmentListResult>): void; listForScope(scope: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; /** * Gets role assignments for a resource. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets role assignments for a resource. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; listForResourceNext(nextPageLink: string, callback: ServiceCallback<models.RoleAssignmentListResult>): void; listForResourceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; /** * Gets role assignments for a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets role assignments for a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; listForResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.RoleAssignmentListResult>): void; listForResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; /** * Gets all role assignments for the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets all role assignments for the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.RoleAssignmentListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; /** * Gets role assignments for a scope. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForScopeNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleAssignmentListResult>>; /** * Gets role assignments for a scope. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForScopeNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleAssignmentListResult>; listForScopeNext(nextPageLink: string, callback: ServiceCallback<models.RoleAssignmentListResult>): void; listForScopeNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleAssignmentListResult>): void; } /** * @class * Permissions * __NOTE__: An instance of this class is automatically created for an * instance of the AuthorizationManagementClient. */ export interface Permissions { /** * Gets all permissions the caller has for a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PermissionGetResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PermissionGetResult>>; /** * Gets all permissions the caller has for a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PermissionGetResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PermissionGetResult} [result] - The deserialized result object if an error did not occur. * See {@link PermissionGetResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PermissionGetResult>; listForResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.PermissionGetResult>): void; listForResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PermissionGetResult>): void; /** * Gets all permissions the caller has for a resource. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} parentResourcePath The parent resource identity. * * @param {string} resourceType The resource type of the resource. * * @param {string} resourceName The name of the resource to get the permissions * for. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PermissionGetResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceWithHttpOperationResponse(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PermissionGetResult>>; /** * Gets all permissions the caller has for a resource. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} parentResourcePath The parent resource identity. * * @param {string} resourceType The resource type of the resource. * * @param {string} resourceName The name of the resource to get the permissions * for. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PermissionGetResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PermissionGetResult} [result] - The deserialized result object if an error did not occur. * See {@link PermissionGetResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PermissionGetResult>; listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, callback: ServiceCallback<models.PermissionGetResult>): void; listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PermissionGetResult>): void; /** * Gets all permissions the caller has for a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PermissionGetResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PermissionGetResult>>; /** * Gets all permissions the caller has for a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PermissionGetResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PermissionGetResult} [result] - The deserialized result object if an error did not occur. * See {@link PermissionGetResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PermissionGetResult>; listForResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.PermissionGetResult>): void; listForResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PermissionGetResult>): void; /** * Gets all permissions the caller has for a resource. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PermissionGetResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PermissionGetResult>>; /** * Gets all permissions the caller has for a resource. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PermissionGetResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PermissionGetResult} [result] - The deserialized result object if an error did not occur. * See {@link PermissionGetResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PermissionGetResult>; listForResourceNext(nextPageLink: string, callback: ServiceCallback<models.PermissionGetResult>): void; listForResourceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PermissionGetResult>): void; } /** * @class * RoleDefinitions * __NOTE__: An instance of this class is automatically created for an * instance of the AuthorizationManagementClient. */ export interface RoleDefinitions { /** * Deletes a role definition. * * @param {string} scope The scope of the role definition. * * @param {string} roleDefinitionId The ID of the role definition to delete. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleDefinition>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(scope: string, roleDefinitionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleDefinition>>; /** * Deletes a role definition. * * @param {string} scope The scope of the role definition. * * @param {string} roleDefinitionId The ID of the role definition to delete. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleDefinition} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleDefinition} [result] - The deserialized result object if an error did not occur. * See {@link RoleDefinition} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(scope: string, roleDefinitionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleDefinition>; deleteMethod(scope: string, roleDefinitionId: string, callback: ServiceCallback<models.RoleDefinition>): void; deleteMethod(scope: string, roleDefinitionId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleDefinition>): void; /** * Get role definition by name (GUID). * * @param {string} scope The scope of the role definition. * * @param {string} roleDefinitionId The ID of the role definition. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleDefinition>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(scope: string, roleDefinitionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleDefinition>>; /** * Get role definition by name (GUID). * * @param {string} scope The scope of the role definition. * * @param {string} roleDefinitionId The ID of the role definition. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleDefinition} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleDefinition} [result] - The deserialized result object if an error did not occur. * See {@link RoleDefinition} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(scope: string, roleDefinitionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleDefinition>; get(scope: string, roleDefinitionId: string, callback: ServiceCallback<models.RoleDefinition>): void; get(scope: string, roleDefinitionId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleDefinition>): void; /** * Creates or updates a role definition. * * @param {string} scope The scope of the role definition. * * @param {string} roleDefinitionId The ID of the role definition. * * @param {object} roleDefinition The values for the role definition. * * @param {string} [roleDefinition.roleName] The role name. * * @param {string} [roleDefinition.description] The role definition * description. * * @param {string} [roleDefinition.roleType] The role type. * * @param {array} [roleDefinition.permissions] Role definition permissions. * * @param {array} [roleDefinition.assignableScopes] Role definition assignable * scopes. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleDefinition>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(scope: string, roleDefinitionId: string, roleDefinition: models.RoleDefinition, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleDefinition>>; /** * Creates or updates a role definition. * * @param {string} scope The scope of the role definition. * * @param {string} roleDefinitionId The ID of the role definition. * * @param {object} roleDefinition The values for the role definition. * * @param {string} [roleDefinition.roleName] The role name. * * @param {string} [roleDefinition.description] The role definition * description. * * @param {string} [roleDefinition.roleType] The role type. * * @param {array} [roleDefinition.permissions] Role definition permissions. * * @param {array} [roleDefinition.assignableScopes] Role definition assignable * scopes. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleDefinition} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleDefinition} [result] - The deserialized result object if an error did not occur. * See {@link RoleDefinition} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(scope: string, roleDefinitionId: string, roleDefinition: models.RoleDefinition, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleDefinition>; createOrUpdate(scope: string, roleDefinitionId: string, roleDefinition: models.RoleDefinition, callback: ServiceCallback<models.RoleDefinition>): void; createOrUpdate(scope: string, roleDefinitionId: string, roleDefinition: models.RoleDefinition, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleDefinition>): void; /** * Get all role definitions that are applicable at scope and above. * * @param {string} scope The scope of the role definition. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * atScopeAndBelow filter to search below the given scope as well. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleDefinitionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(scope: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleDefinitionListResult>>; /** * Get all role definitions that are applicable at scope and above. * * @param {string} scope The scope of the role definition. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * atScopeAndBelow filter to search below the given scope as well. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleDefinitionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleDefinitionListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleDefinitionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(scope: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleDefinitionListResult>; list(scope: string, callback: ServiceCallback<models.RoleDefinitionListResult>): void; list(scope: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleDefinitionListResult>): void; /** * Gets a role definition by ID. * * @param {string} roleId The fully qualified role definition ID. Use the * format, * /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} * for subscription level role definitions, or * /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for * tenant level role definitions. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleDefinition>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getByIdWithHttpOperationResponse(roleId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleDefinition>>; /** * Gets a role definition by ID. * * @param {string} roleId The fully qualified role definition ID. Use the * format, * /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} * for subscription level role definitions, or * /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for * tenant level role definitions. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleDefinition} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleDefinition} [result] - The deserialized result object if an error did not occur. * See {@link RoleDefinition} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getById(roleId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleDefinition>; getById(roleId: string, callback: ServiceCallback<models.RoleDefinition>): void; getById(roleId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleDefinition>): void; /** * Get all role definitions that are applicable at scope and above. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RoleDefinitionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RoleDefinitionListResult>>; /** * Get all role definitions that are applicable at scope and above. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RoleDefinitionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RoleDefinitionListResult} [result] - The deserialized result object if an error did not occur. * See {@link RoleDefinitionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RoleDefinitionListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.RoleDefinitionListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RoleDefinitionListResult>): void; } /** * @class * DenyAssignments * __NOTE__: An instance of this class is automatically created for an * instance of the AuthorizationManagementClient. */ export interface DenyAssignments { /** * Gets deny assignments for a resource. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} parentResourcePath The parent resource identity. * * @param {string} resourceType The resource type of the resource. * * @param {string} resourceName The name of the resource to get deny * assignments for. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceWithHttpOperationResponse(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets deny assignments for a resource. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} resourceProviderNamespace The namespace of the resource * provider. * * @param {string} parentResourcePath The parent resource identity. * * @param {string} resourceType The resource type of the resource. * * @param {string} resourceName The name of the resource to get deny * assignments for. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, callback: ServiceCallback<models.DenyAssignmentListResult>): void; listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; /** * Gets deny assignments for a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets deny assignments for a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroup(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; listForResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.DenyAssignmentListResult>): void; listForResourceGroup(resourceGroupName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; /** * Gets all deny assignments for the subscription. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets all deny assignments for the subscription. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; list(callback: ServiceCallback<models.DenyAssignmentListResult>): void; list(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; /** * Get the specified deny assignment. * * @param {string} scope The scope of the deny assignment. * * @param {string} denyAssignmentId The ID of the deny assignment to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(scope: string, denyAssignmentId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignment>>; /** * Get the specified deny assignment. * * @param {string} scope The scope of the deny assignment. * * @param {string} denyAssignmentId The ID of the deny assignment to get. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignment} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(scope: string, denyAssignmentId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignment>; get(scope: string, denyAssignmentId: string, callback: ServiceCallback<models.DenyAssignment>): void; get(scope: string, denyAssignmentId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignment>): void; /** * Gets a deny assignment by ID. * * @param {string} denyAssignmentId The fully qualified deny assignment ID. For * example, use the format, * /subscriptions/{guid}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} * for subscription level deny assignments, or * /providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for * tenant level deny assignments. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getByIdWithHttpOperationResponse(denyAssignmentId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignment>>; /** * Gets a deny assignment by ID. * * @param {string} denyAssignmentId The fully qualified deny assignment ID. For * example, use the format, * /subscriptions/{guid}/providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} * for subscription level deny assignments, or * /providers/Microsoft.Authorization/denyAssignments/{denyAssignmentId} for * tenant level deny assignments. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignment} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getById(denyAssignmentId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignment>; getById(denyAssignmentId: string, callback: ServiceCallback<models.DenyAssignment>): void; getById(denyAssignmentId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignment>): void; /** * Gets deny assignments for a scope. * * @param {string} scope The scope of the deny assignments. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForScopeWithHttpOperationResponse(scope: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets deny assignments for a scope. * * @param {string} scope The scope of the deny assignments. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. Use * $filter=atScope() to return all deny assignments at or above the scope. Use * $filter=denyAssignmentName eq '{name}' to search deny assignments by name at * specified scope. Use $filter=principalId eq '{id}' to return all deny * assignments at, above and below the scope for the specified principal. Use * $filter=gdprExportPrincipalId eq '{id}' to return all deny assignments at, * above and below the scope for the specified principal. This filter is * different from the principalId filter as it returns not only those deny * assignments that contain the specified principal is the Principals list but * also those deny assignments that contain the specified principal is the * ExcludePrincipals list. Additionally, when gdprExportPrincipalId filter is * used, only the deny assignment name and description properties are returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForScope(scope: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; listForScope(scope: string, callback: ServiceCallback<models.DenyAssignmentListResult>): void; listForScope(scope: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; /** * Gets deny assignments for a resource. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets deny assignments for a resource. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; listForResourceNext(nextPageLink: string, callback: ServiceCallback<models.DenyAssignmentListResult>): void; listForResourceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; /** * Gets deny assignments for a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets deny assignments for a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; listForResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.DenyAssignmentListResult>): void; listForResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; /** * Gets all deny assignments for the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets all deny assignments for the subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.DenyAssignmentListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; /** * Gets deny assignments for a scope. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DenyAssignmentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForScopeNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DenyAssignmentListResult>>; /** * Gets deny assignments for a scope. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DenyAssignmentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DenyAssignmentListResult} [result] - The deserialized result object if an error did not occur. * See {@link DenyAssignmentListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForScopeNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DenyAssignmentListResult>; listForScopeNext(nextPageLink: string, callback: ServiceCallback<models.DenyAssignmentListResult>): void; listForScopeNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DenyAssignmentListResult>): void; }
the_stack
import { domData, setHtml, triggerEvent, removeNode, virtualElements, options } from '@tko/utils' import { applyBindings, contextFor, dataFor } from '@tko/bind' import { observable, observableArray } from '@tko/observable' import { MultiProvider } from '@tko/provider.multi' import { VirtualProvider } from '@tko/provider.virtual' import { DataBindProvider } from '@tko/provider.databind' import {bindings as templateBindings} from '../dist' import {bindings as ifBindings} from '@tko/binding.if' import {bindings as coreBindings} from '@tko/binding.core' import '@tko/utils/helpers/jasmine-13-helper' // virtualEvents, removeNode describe('Binding: Foreach', function () { beforeEach(jasmine.prepareTestNode) var bindingHandlers beforeEach(function () { var provider = new MultiProvider({ providers: [new DataBindProvider(), new VirtualProvider()] }) options.bindingProviderInstance = provider bindingHandlers = provider.bindingHandlers bindingHandlers.set(coreBindings) bindingHandlers.set(templateBindings) bindingHandlers.set(ifBindings) }) it('Should remove descendant nodes from the document (and not bind them) if the value is falsy', function () { testNode.innerHTML = "<div data-bind='foreach: someItem'><span data-bind='text: someItem.nonExistentChildProp'></span></div>" expect(testNode.childNodes[0].childNodes.length).toEqual(1) applyBindings({ someItem: null }, testNode) expect(testNode.childNodes[0].childNodes.length).toEqual(0) }) it('Should remove descendant nodes from the document (and not bind them) if the value is undefined', function () { testNode.innerHTML = "<div data-bind='foreach: someItem'><span data-bind='text: someItem.nonExistentChildProp'></span></div>" expect(testNode.childNodes[0].childNodes.length).toEqual(1) applyBindings({ someItem: undefined }, testNode) expect(testNode.childNodes[0].childNodes.length).toEqual(0) }) it('Should duplicate descendant nodes for each value in the array value (and bind them in the context of that supplied value)', function () { testNode.innerHTML = "<div data-bind='foreach: someItems'><span data-bind='text: childProp'></span></div>" var someItems = [ { childProp: 'first child' }, { childProp: 'second child' } ] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">first child</span><span data-bind="text: childprop">second child</span>') }) it('Should reject bindings where no template content is specified', function () { testNode.innerHTML = "<div data-bind='foreach: [1, 2, 3]'></div>" expect(function () { applyBindings({}, testNode) }).toThrowContaining('no template content') }) it('Should clean away any data values attached to the original template nodes before use', function () { // Represents issue https://github.com/SteveSanderson/knockout/pull/420 testNode.innerHTML = "<div data-bind='foreach: [1, 2]'><span></span></div>" // Apply some DOM Data to the SPAN var span = testNode.childNodes[0].childNodes[0] expect(span.tagName).toEqual('SPAN') domData.set(span, 'mydata', 123) // See that it vanishes because the SPAN is extracted as a template expect(domData.get(span, 'mydata')).toEqual(123) applyBindings(null, testNode) expect(domData.get(span, 'mydata')).toEqual(undefined) // Also be sure the DOM Data doesn't appear in the output expect(testNode.childNodes[0]).toContainHtml('<span></span><span></span>') expect(domData.get(testNode.childNodes[0].childNodes[0], 'mydata')).toEqual(undefined) expect(domData.get(testNode.childNodes[0].childNodes[1], 'mydata')).toEqual(undefined) }) it('Should be able to use $data to reference each array item being bound', function () { testNode.innerHTML = "<div data-bind='foreach: someItems'><span data-bind='text: $data'></span></div>" var someItems = ['alpha', 'beta'] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: $data">alpha</span><span data-bind="text: $data">beta</span>') }) it('Should add and remove nodes to match changes in the bound array', function () { testNode.innerHTML = "<div data-bind='foreach: someItems'><span data-bind='text: childProp'></span></div>" var someItems = observableArray([ { childProp: 'first child' }, { childProp: 'second child' } ]) applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">first child</span><span data-bind="text: childprop">second child</span>') // Add items at the beginning... someItems.unshift({ childProp: 'zeroth child' }) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">zeroth child</span><span data-bind="text: childprop">first child</span><span data-bind="text: childprop">second child</span>') // ... middle someItems.splice(2, 0, { childProp: 'middle child' }) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">zeroth child</span><span data-bind="text: childprop">first child</span><span data-bind="text: childprop">middle child</span><span data-bind="text: childprop">second child</span>') // ... and end someItems.push({ childProp: 'last child' }) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">zeroth child</span><span data-bind="text: childprop">first child</span><span data-bind="text: childprop">middle child</span><span data-bind="text: childprop">second child</span><span data-bind="text: childprop">last child</span>') // Also remove from beginning... someItems.shift() expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">first child</span><span data-bind="text: childprop">middle child</span><span data-bind="text: childprop">second child</span><span data-bind="text: childprop">last child</span>') // ... and middle someItems.splice(1, 1) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">first child</span><span data-bind="text: childprop">second child</span><span data-bind="text: childprop">last child</span>') // ... and end someItems.pop() expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">first child</span><span data-bind="text: childprop">second child</span>') // Disabling this legacy test re. the `destroyed` observable property. // options.includeDestroyed = false // Also, marking as "destroy" should eliminate the item from display // someItems.destroy(someItems()[0]) // expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">second child</span>') }) it('Should remove all nodes corresponding to a removed array item, even if they were generated via containerless templates', function () { // Represents issue https://github.com/SteveSanderson/knockout/issues/185 testNode.innerHTML = "<div data-bind='foreach: someitems'>a<!-- ko if:true -->b<!-- /ko --></div>" var someitems = observableArray([1, 2]) applyBindings({ someitems: someitems }, testNode) expect(testNode).toContainHtml('<div data-bind="foreach: someitems">a<!-- ko if:true -->b<!-- /ko -->a<!-- ko if:true -->b<!-- /ko --></div>') // Now remove items, and check the corresponding child nodes vanished someitems.splice(1, 1) expect(testNode).toContainHtml('<div data-bind="foreach: someitems">a<!-- ko if:true -->b<!-- /ko --></div>') }) it('Should remove all nodes corresponding to a removed array item, even if they were added via containerless syntax and there are no other nodes', function () { bindingHandlers.test = { init: function (element, valueAccessor) { var value = valueAccessor() virtualElements.prepend(element, document.createTextNode(value)) } } virtualElements.allowedBindings['test'] = true testNode.innerHTML = 'x-<!--ko foreach: someitems--><!--ko test:$data--><!--/ko--><!--/ko-->' var someitems = observableArray(['aaa', 'bbb']) applyBindings({ someitems: someitems }, testNode) expect(testNode).toContainText('x-aaabbb') // Now remove items, and check the corresponding child nodes vanished someitems.splice(1, 1) expect(testNode).toContainText('x-aaa') }) it('Should update all nodes corresponding to a changed array item, even if they were generated via containerless templates', function () { testNode.innerHTML = "<div data-bind='foreach: someitems'><!-- ko if:true --><span data-bind='text: $data'></span><!-- /ko --></div>" var someitems = [ observable('A'), observable('B') ] applyBindings({ someitems: someitems }, testNode) expect(testNode).toContainText('AB') // Now update an item someitems[0]('A2') expect(testNode).toContainText('A2B') }) it('Should be able to supply show "_destroy"ed items via includeDestroyed option', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, includeDestroyed: true }'><span data-bind='text: childProp'></span></div>" var someItems = observableArray([ { childProp: 'first child' }, { childProp: 'second child', _destroy: true } ]) applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: childprop">first child</span><span data-bind="text: childprop">second child</span>') }) it('Should be able to supply afterAdd and beforeRemove callbacks', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, afterAdd: myAfterAdd, beforeRemove: myBeforeRemove }'><span data-bind='text: $data'></span></div>" var someItems = observableArray(['first child']) var afterAddCallbackData = [], beforeRemoveCallbackData = [] applyBindings({ someItems: someItems, myAfterAdd: function (elem, index, value) { afterAddCallbackData.push({ elem: elem, value: value, currentParentClone: elem.parentNode.cloneNode(true) }) }, myBeforeRemove: function (elem, index, value) { beforeRemoveCallbackData.push({ elem: elem, value: value, currentParentClone: elem.parentNode.cloneNode(true) }) } }, testNode) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: $data">first child</span>') // Try adding someItems.push('added child') expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: $data">first child</span><span data-bind="text: $data">added child</span>') expect(afterAddCallbackData.length).toEqual(1) expect(afterAddCallbackData[0].elem).toEqual(testNode.childNodes[0].childNodes[1]) expect(afterAddCallbackData[0].value).toEqual('added child') expect(afterAddCallbackData[0].currentParentClone).toContainHtml('<span data-bind="text: $data">first child</span><span data-bind="text: $data">added child</span>') // Try removing someItems.shift() expect(beforeRemoveCallbackData.length).toEqual(1) expect(beforeRemoveCallbackData[0].elem).toContainText('first child') expect(beforeRemoveCallbackData[0].value).toEqual('first child') // Note that when using "beforeRemove", we *don't* remove the node from the doc - it's up to the beforeRemove callback to do it. So, check it's still there. expect(beforeRemoveCallbackData[0].currentParentClone).toContainHtml('<span data-bind="text: $data">first child</span><span data-bind="text: $data">added child</span>') expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: $data">first child</span><span data-bind="text: $data">added child</span>') // Remove another item beforeRemoveCallbackData = [] someItems.shift() expect(beforeRemoveCallbackData.length).toEqual(1) expect(beforeRemoveCallbackData[0].elem).toContainText('added child') expect(beforeRemoveCallbackData[0].value).toEqual('added child') // Neither item has yet been removed and both are still in their original locations expect(beforeRemoveCallbackData[0].currentParentClone).toContainHtml('<span data-bind="text: $data">first child</span><span data-bind="text: $data">added child</span>') expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: $data">first child</span><span data-bind="text: $data">added child</span>') // Try adding the item back; it should be added and not confused with the removed item testNode.childNodes[0].innerHTML = '' // Actually remove *removed* nodes to check that they are not added back in afterAddCallbackData = [] someItems.push('added child') expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: $data">added child</span>') expect(afterAddCallbackData.length).toEqual(1) expect(afterAddCallbackData[0].elem).toEqual(testNode.childNodes[0].childNodes[0]) expect(afterAddCallbackData[0].value).toEqual('added child') expect(afterAddCallbackData[0].currentParentClone).toContainHtml('<span data-bind="text: $data">added child</span>') }) it('Should call an afterRender callback function and not cause updates if an observable accessed in the callback is changed', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, afterRender: callback }'><span data-bind='text: childprop'></span></div>" var callbackObservable = observable(1), someItems = observableArray([{ childprop: 'first child' }]), callbacks = 0 applyBindings({ someItems: someItems, callback: function () { callbackObservable(); callbacks++ } }, testNode) expect(callbacks).toEqual(1) // Change the array, but don't update the observableArray so that the foreach binding isn't updated someItems().push({ childprop: 'hidden child'}) expect(testNode.childNodes[0]).toContainText('first child') // Update callback observable and check that the binding wasn't updated callbackObservable(2) expect(testNode.childNodes[0]).toContainText('first child') // Update the observableArray and verify that the binding is now updated someItems.valueHasMutated() expect(testNode.childNodes[0]).toContainText('first childhidden child') }) it('Should call an afterRender callback, passing all of the rendered nodes, accounting for node preprocessing and virtual element bindings', function () { // Set up a binding provider that converts text nodes to expressions var originalBindingProvider = options.bindingProviderInstance, preprocessingBindingProvider = function () { } preprocessingBindingProvider.prototype = originalBindingProvider options.bindingProviderInstance = new preprocessingBindingProvider() options.bindingProviderInstance.preprocessNode = function (node) { if (node.nodeType === 3 && node.data.charAt(0) === '$') { var newNodes = [ document.createComment('ko text: ' + node.data), document.createComment('/ko') ] for (var i = 0; i < newNodes.length; i++) { node.parentNode.insertBefore(newNodes[i], node) } node.parentNode.removeChild(node) return newNodes } } // Now perform a foreach binding, and see that afterRender gets the output from the preprocessor and bindings testNode.innerHTML = "<div data-bind='foreach: { data: someItems, afterRender: callback }'><span>[</span>$data<span>]</span></div>" var someItems = observableArray(['Alpha', 'Beta']), callbackReceivedArrayValues = [] applyBindings({ someItems: someItems, callback: function (nodes, arrayValue) { expect(nodes.length).toBe(5) expect(nodes[0]).toContainText('[') // <span>[</span> expect(nodes[1].nodeType).toBe(8) // <!-- ko text: $data --> expect(nodes[2].nodeType).toBe(3) // text node inserted by text binding expect(nodes[3].nodeType).toBe(8) // <!-- /ko --> expect(nodes[4]).toContainText(']') // <span>]</span> callbackReceivedArrayValues.push(arrayValue) } }, testNode) expect(testNode.childNodes[0]).toContainText('[Alpha][Beta]') expect(callbackReceivedArrayValues).toEqual(['Alpha', 'Beta']) options.bindingProviderInstance = originalBindingProvider }) it('Exception in afterAdd callback should not cause extra elements on next update', function () { // See https://github.com/knockout/knockout/issues/1794 testNode.innerHTML = "<div data-bind='foreach: { data: someItems, afterAdd: callback }'><span data-bind='text: $data'></span></div>" var someItems = observableArray([ 'A', 'B', 'C' ]), callback = function (element, index, data) { if (data === 'D') throw 'Exception' } applyBindings({someItems: someItems, callback: callback }, testNode) expect(testNode.childNodes[0]).toContainText('ABC') expect(function () { someItems.push('D') }).toThrow('Exception') expect(testNode.childNodes[0]).toContainText('ABCD') expect(function () { someItems.push('E') }).not.toThrow() expect(testNode.childNodes[0]).toContainText('ABCDE') }) it('Should call an afterAdd callback function and not cause updates if an observable accessed in the callback is changed', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, afterAdd: callback }'><span data-bind='text: childprop'></span></div>" var callbackObservable = observable(1), someItems = observableArray([]), callbacks = 0 applyBindings({ someItems: someItems, callback: function () { callbackObservable(); callbacks++ } }, testNode) someItems.push({ childprop: 'added child'}) expect(callbacks).toEqual(1) // Change the array, but don't update the observableArray so that the foreach binding isn't updated someItems().push({ childprop: 'hidden child'}) expect(testNode.childNodes[0]).toContainText('added child') // Update callback observable and check that the binding wasn't updated callbackObservable(2) expect(testNode.childNodes[0]).toContainText('added child') // Update the observableArray and verify that the binding is now updated someItems.valueHasMutated() expect(testNode.childNodes[0]).toContainText('added childhidden child') }) it('Should call a beforeRemove callback function and not cause updates if an observable accessed in the callback is changed', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, beforeRemove: callback }'><span data-bind='text: childprop'></span></div>" var callbackObservable = observable(1), someItems = observableArray([{ childprop: 'first child' }, { childprop: 'second child' }]), callbacks = 0 applyBindings({ someItems: someItems, callback: function (elem) { callbackObservable(); callbacks++; removeNode(elem) } }, testNode) someItems.pop() expect(callbacks).toEqual(1) // Change the array, but don't update the observableArray so that the foreach binding isn't updated someItems().push({ childprop: 'hidden child'}) expect(testNode.childNodes[0]).toContainText('first child') // Update callback observable and check that the binding wasn't updated callbackObservable(2) expect(testNode.childNodes[0]).toContainText('first child') // Update the observableArray and verify that the binding is now updated someItems.valueHasMutated() expect(testNode.childNodes[0]).toContainText('first childhidden child') }) it('Should call an afterMove callback function and not cause updates if an observable accessed in the callback is changed', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, afterMove: callback }'><span data-bind='text: childprop'></span></div>" var callbackObservable = observable(1), someItems = observableArray([{ childprop: 'first child' }]), callbacks = 0 applyBindings({ someItems: someItems, callback: function () { callbackObservable(); callbacks++ } }, testNode) someItems.splice(0, 0, { childprop: 'added child'}) expect(callbacks).toEqual(1) // Change the array, but don't update the observableArray so that the foreach binding isn't updated someItems().push({ childprop: 'hidden child'}) expect(testNode.childNodes[0]).toContainText('added childfirst child') // Update callback observable and check that the binding wasn't updated callbackObservable(2) expect(testNode.childNodes[0]).toContainText('added childfirst child') // Update the observableArray and verify that the binding is now updated someItems.valueHasMutated() expect(testNode.childNodes[0]).toContainText('added childfirst childhidden child') }) it('Should call a beforeMove callback function and not cause updates if an observable accessed in the callback is changed', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, beforeMove: callback }'><span data-bind='text: childprop'></span></div>" var callbackObservable = observable(1), someItems = observableArray([{ childprop: 'first child' }]), callbacks = 0 applyBindings({ someItems: someItems, callback: function () { callbackObservable(); callbacks++ } }, testNode) someItems.splice(0, 0, { childprop: 'added child'}) expect(callbacks).toEqual(1) // Change the array, but don't update the observableArray so that the foreach binding isn't updated someItems().push({ childprop: 'hidden child'}) expect(testNode.childNodes[0]).toContainText('added childfirst child') // Update callback observable and check that the binding wasn't updated callbackObservable(2) expect(testNode.childNodes[0]).toContainText('added childfirst child') // Update the observableArray and verify that the binding is now updated someItems.valueHasMutated() expect(testNode.childNodes[0]).toContainText('added childfirst childhidden child') }) it('Should not double-unwrap if the internal is iterable', function () { // Previously an observable value was doubly-unwrapped: in the foreach handler and then in the template handler. // This is now fixed so that the value is unwrapped just in the template handler and only peeked at in the foreach handler. // See https://github.com/SteveSanderson/knockout/issues/523 testNode.innerHTML = "<div data-bind='foreach: myArray'><span data-bind='text: $data'></span></div>" var myArrayWrapped = observable(observableArray(['data value'])) applyBindings({ myArray: myArrayWrapped }, testNode) // Because the unwrapped value isn't an array, nothing gets rendered. expect(testNode.childNodes[0]).toContainText('') }) it('Should not triple-unwrap the given value', function () { // Previously an observable value was doubly-unwrapped: in the foreach handler and then in the template handler. // This is now fixed so that the value is unwrapped just in the template handler and only peeked at in the foreach handler. // See https://github.com/SteveSanderson/knockout/issues/523 testNode.innerHTML = "<div data-bind='foreach: myArray'><span data-bind='text: $data'></span></div>" var myArrayWrapped = observable(observable(observableArray(['data value']))) applyBindings({ myArray: myArrayWrapped }, testNode) // Because the unwrapped value isn't an array, nothing gets rendered. expect(testNode.childNodes[0]).toContainText('') }) it('Should be able to nest foreaches and access binding contexts both during and after binding', function () { testNode.innerHTML = "<div data-bind='foreach: items'>" + "<div data-bind='foreach: children'>" + "(Val: <span data-bind='text: $data'></span>, Parents: <span data-bind='text: $parents.length'></span>, Rootval: <span data-bind='text: $root.rootVal'></span>)" + '</div>' + '</div>' var viewModel = { rootVal: 'ROOTVAL', items: observableArray([ { children: observableArray(['A1', 'A2', 'A3']) }, { children: observableArray(['B1', 'B2']) } ]) } applyBindings(viewModel, testNode) // Verify we can access binding contexts during binding expect(testNode.childNodes[0].childNodes[0]).toContainText('(Val: A1, Parents: 2, Rootval: ROOTVAL)(Val: A2, Parents: 2, Rootval: ROOTVAL)(Val: A3, Parents: 2, Rootval: ROOTVAL)') expect(testNode.childNodes[0].childNodes[1]).toContainText('(Val: B1, Parents: 2, Rootval: ROOTVAL)(Val: B2, Parents: 2, Rootval: ROOTVAL)') // Verify we can access them later var firstInnerTextNode = testNode.childNodes[0].childNodes[0].childNodes[1] expect(firstInnerTextNode.nodeType).toEqual(1) // The first span associated with A1 expect(dataFor(firstInnerTextNode)).toEqual('A1') expect(contextFor(firstInnerTextNode).$parent.children()[2]).toEqual('A3') expect(contextFor(firstInnerTextNode).$parents[1].items()[1].children()[1]).toEqual('B2') expect(contextFor(firstInnerTextNode).$root.rootVal).toEqual('ROOTVAL') }) it('Should be able to define a \'foreach\' region using a containerless template', function () { testNode.innerHTML = "hi <!-- ko foreach: someitems --><span data-bind='text: childprop'></span><!-- /ko -->" var someitems = [ { childprop: 'first child' }, { childprop: 'second child' } ] applyBindings({ someitems: someitems }, testNode) expect(testNode).toContainHtml('hi <!-- ko foreach: someitems --><span data-bind="text: childprop">first child</span><span data-bind="text: childprop">second child</span><!-- /ko -->') // Check we can recover the binding contexts expect(dataFor(testNode.childNodes[3]).childprop).toEqual('second child') expect(contextFor(testNode.childNodes[3]).$parent.someitems.length).toEqual(2) }) it('Should be able to nest \'foreach\' regions defined using containerless templates', function () { var innerContents = document.createElement('DIV') testNode.innerHTML = '' testNode.appendChild(document.createComment('ko foreach: items')) testNode.appendChild(document.createComment('ko foreach: children')) innerContents.innerHTML = "(Val: <span data-bind='text: $data'></span>, Parents: <span data-bind='text: $parents.length'></span>, Rootval: <span data-bind='text: $root.rootVal'></span>)" while (innerContents.firstChild) { testNode.appendChild(innerContents.firstChild) } testNode.appendChild(document.createComment('/ko')) testNode.appendChild(document.createComment('/ko')) var viewModel = { rootVal: 'ROOTVAL', items: observableArray([ { children: observableArray(['A1', 'A2', 'A3']) }, { children: observableArray(['B1', 'B2']) } ]) } applyBindings(viewModel, testNode) // Verify we can access binding contexts during binding expect(testNode).toContainText('(Val: A1, Parents: 2, Rootval: ROOTVAL)(Val: A2, Parents: 2, Rootval: ROOTVAL)(Val: A3, Parents: 2, Rootval: ROOTVAL)(Val: B1, Parents: 2, Rootval: ROOTVAL)(Val: B2, Parents: 2, Rootval: ROOTVAL)') // Verify we can access them later var firstInnerSpan = testNode.childNodes[3] expect(firstInnerSpan).toContainText('A1') // It is the first span bound in the context of A1 expect(dataFor(firstInnerSpan)).toEqual('A1') expect(contextFor(firstInnerSpan).$parent.children()[2]).toEqual('A3') expect(contextFor(firstInnerSpan).$parents[1].items()[1].children()[1]).toEqual('B2') expect(contextFor(firstInnerSpan).$root.rootVal).toEqual('ROOTVAL') }) it('Should be able to nest \'if\' inside \'foreach\' defined using containerless templates', function () { testNode.innerHTML = '<ul></ul>' testNode.childNodes[0].appendChild(document.createComment('ko foreach: items')) testNode.childNodes[0].appendChild(document.createElement('li')) testNode.childNodes[0].childNodes[1].innerHTML = "<span data-bind='text: childval.childprop'></span>" testNode.childNodes[0].childNodes[1].insertBefore(document.createComment('ko if: childval'), testNode.childNodes[0].childNodes[1].firstChild) testNode.childNodes[0].childNodes[1].appendChild(document.createComment('/ko')) testNode.childNodes[0].appendChild(document.createComment('/ko')) var viewModel = { items: [ { childval: {childprop: 123 } }, { childval: null }, { childval: {childprop: 456 } } ] } applyBindings(viewModel, testNode) expect(testNode).toContainHtml('<ul>' + '<!--ko foreach: items-->' + '<li>' + '<!--ko if: childval-->' + '<span data-bind="text: childval.childprop">123</span>' + '<!--/ko-->' + '</li>' + '<li>' + '<!--ko if: childval-->' + '<!--/ko-->' + '</li>' + '<li>' + '<!--ko if: childval-->' + '<span data-bind="text: childval.childprop">456</span>' + '<!--/ko-->' + '</li>' + '<!--/ko-->' + '</ul>') }) it('Should be able to use containerless templates directly inside UL elements even when closing LI tags are omitted', function () { // Represents issue https://github.com/SteveSanderson/knockout/issues/155 // Certain closing tags, including </li> are optional (http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission) // Most browsers respect your positioning of closing </li> tags, but IE <= 7 doesn't, and treats your markup // as if it was written as below: // Your actual markup: "<ul><li>Header item</li><!-- ko foreach: someitems --><li data-bind='text: $data'></li><!-- /ko --></ul>"; // How IE <= 8 treats it: testNode.innerHTML = "<ul><li>Header item<!-- ko foreach: someitems --><li data-bind='text: $data'><!-- /ko --></ul>" var viewModel = { someitems: [ 'Alpha', 'Beta' ] } applyBindings(viewModel, testNode) var match = testNode.innerHTML.toLowerCase().match(/<\/li>/g) // Any of the following results are acceptable. if (!match) { // Opera 11.5 doesn't add any closing </li> tags expect(testNode).toContainHtml('<ul><li>header item<!-- ko foreach: someitems --><li data-bind="text: $data">alpha<li data-bind="text: $data">beta<!-- /ko --></ul>') } else if (match.length == 3) { // Modern browsers implicitly re-add the closing </li> tags expect(testNode).toContainHtml('<ul><li>header item</li><!-- ko foreach: someitems --><li data-bind="text: $data">alpha</li><li data-bind="text: $data">beta</li><!-- /ko --></ul>') } else { // ... but IE < 8 doesn't add ones that immediately precede a <li> expect(testNode).toContainHtml('<ul><li>header item</li><!-- ko foreach: someitems --><li data-bind="text: $data">alpha<li data-bind="text: $data">beta</li><!-- /ko --></ul>') } }) it('Should be able to nest containerless templates directly inside UL elements, even on IE < 8 with its bizarre HTML parsing/formatting', function () { // Represents https://github.com/SteveSanderson/knockout/issues/212 // This test starts with the following DOM structure: // <ul> // <!-- ko foreach: ['A', 'B'] --> // <!-- ko if: $data == 'B' --> // <li data-bind='text: $data'> // <!-- /ko --> // <!-- /ko --> // </li> // </ul> // Note that: // 1. The closing comments are inside the <li> to simulate IE<8's weird parsing // 2. We have to build this with manual DOM operations, otherwise IE<8 will deform it in a different weird way // It would be a more authentic test if we could set up the scenario using .innerHTML and then let the browser do whatever parsing it does normally, // but unfortunately IE varies its weirdness according to whether it's really parsing an HTML doc, or whether you're using .innerHTML. testNode.innerHTML = '' testNode.appendChild(document.createElement('ul')) testNode.firstChild.appendChild(document.createComment("ko foreach: ['A', 'B']")) testNode.firstChild.appendChild(document.createComment("ko if: $data == 'B'")) testNode.firstChild.appendChild(document.createElement('li')) testNode.firstChild.lastChild.setAttribute('data-bind', 'text: $data') testNode.firstChild.lastChild.appendChild(document.createComment('/ko')) testNode.firstChild.lastChild.appendChild(document.createComment('/ko')) applyBindings(null, testNode) expect(testNode).toContainText('B') }) it('Should be able to give an alias to $data using \"as\"', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'><span data-bind='text: item'></span></div>" var someItems = ['alpha', 'beta'] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainHtml('<span data-bind="text: item">alpha</span><span data-bind="text: item">beta</span>') }) it('Should be able to give an alias to $data using \"as\", and use it within a nested loop', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'>" + "<span data-bind='foreach: item.sub'>" + "<span data-bind='text: item.name+\":\"+$data'></span>," + '</span>' + '</div>' var someItems = [{ name: 'alpha', sub: ['a', 'b'] }, { name: 'beta', sub: ['c'] }] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainText('alpha:a,alpha:b,beta:c,') }) it('Should be able to set up multiple nested levels of aliases using \"as\"', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'>" + "<span data-bind='foreach: { data: item.sub, as: \"subvalue\" }'>" + "<span data-bind='text: item.name+\":\"+subvalue'></span>," + '</span>' + '</div>' var someItems = [{ name: 'alpha', sub: ['a', 'b'] }, { name: 'beta', sub: ['c', 'd'] }] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainText('alpha:a,alpha:b,beta:c,beta:d,') }) it('Should be able to give an alias to $data using \"as\", and use it within arbitrary descendant binding contexts', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'><span data-bind='if: item.length'><span data-bind='text: item'></span>,</span></div>" var someItems = ['alpha', 'beta'] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainText('alpha,beta,') }) it('Should be able to give an alias to $data using \"as\", and use it within descendant binding contexts defined using containerless syntax', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'>x<!-- ko if: item.length --><span data-bind='text: item'></span>x,<!-- /ko --></div>" var someItems = ['alpha', 'beta'] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainText('xalphax,xbetax,') }) it('Should be able to output HTML5 elements (even on IE<9, as long as you reference either innershiv.js or jQuery1.7+Modernizr)', function () { var isSupported = jasmine.ieVersion >= 9 || window.innerShiv || window.jQuery if (isSupported) { // Represents https://github.com/SteveSanderson/knockout/issues/194 setHtml(testNode, "<div data-bind='foreach:someitems'><section data-bind='text: $data'></section></div>") var viewModel = { someitems: [ 'Alpha', 'Beta' ] } applyBindings(viewModel, testNode) expect(testNode).toContainHtml('<div data-bind="foreach:someitems"><section data-bind="text: $data">alpha</section><section data-bind="text: $data">beta</section></div>') } }) it('Should be able to output HTML5 elements within container-less templates (same as above)', function () { var isSupported = jasmine.ieVersion >= 9 || window.innerShiv || window.jQuery if (isSupported) { // Represents https://github.com/SteveSanderson/knockout/issues/194 setHtml(testNode, "xxx<!-- ko foreach:someitems --><div><section data-bind='text: $data'></section></div><!-- /ko -->") var viewModel = { someitems: [ 'Alpha', 'Beta' ] } applyBindings(viewModel, testNode) expect(testNode).toContainHtml('xxx<!-- ko foreach:someitems --><div><section data-bind="text: $data">alpha</section></div><div><section data-bind="text: $data">beta</section></div><!-- /ko -->') } }) it('Should provide access to observable items through $rawData', function () { testNode.innerHTML = "<div data-bind='foreach: someItems'><input data-bind='value: $rawData'/></div>" var x = observable('first'), y = observable('second'), someItems = observableArray([ x, y ]) applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toHaveValues(['first', 'second']) // Should update observable when input is changed testNode.childNodes[0].childNodes[0].value = 'third' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(x()).toEqual('third') // Should update the input when the observable changes y('fourth') expect(testNode.childNodes[0]).toHaveValues(['third', 'fourth']) // Should update the inputs when the array changes someItems([x]) expect(testNode.childNodes[0]).toHaveValues(['third']) }) it('Should not re-render the nodes when an observable item changes', function () { testNode.innerHTML = "<div data-bind='foreach: someItems'><span data-bind='text: $data'></span></div>" var x = observable('first'), someItems = [ x ] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainText('first') var saveNode = testNode.childNodes[0].childNodes[0] x('second') expect(testNode.childNodes[0]).toContainText('second') expect(testNode.childNodes[0].childNodes[0]).toEqual(saveNode) }) it('Should not clean unrelated nodes when beforeRemove callback removes some nodes before others', function () { // In this scenario, a beforeRemove callback removes non-element nodes (such as text nodes) // immediately, but delays removing element nodes (for a fade effect, for example). See #1903. jasmine.Clock.useMock() testNode.innerHTML = "<div data-bind='foreach: {data: planets, beforeRemove: beforeRemove}'>--<span data-bind='text: name'></span>++</div>" var planets = observableArray([ { name: observable('Mercury') }, { name: observable('Venus') }, { name: observable('Earth') }, { name: observable('Moon') }, { name: observable('Ceres') } ]), beforeRemove = function (elem) { if (elem.nodeType === 1) { setTimeout(function () { removeNode(elem) }, 1) } else { removeNode(elem) } } applyBindings({ planets: planets, beforeRemove: beforeRemove }, testNode) expect(testNode).toContainText('--Mercury++--Venus++--Earth++--Moon++--Ceres++') // Remove an item; the surrounding text nodes are removed immediately, but not the element node var deleted = planets.splice(3, 1) expect(testNode).toContainText('--Mercury++--Venus++--Earth++Moon--Ceres++') // Add some items; this causes the binding to update planets.push({ name: observable('Jupiter') }) planets.push({ name: observable('Saturn') }) expect(testNode).toContainText('--Mercury++--Venus++--Earth++Moon--Ceres++--Jupiter++--Saturn++') // Update the text of the item following the removed item; it should respond to updates normally planets()[3].name('Mars') expect(testNode).toContainText('--Mercury++--Venus++--Earth++Moon--Mars++--Jupiter++--Saturn++') // Update the text of the deleted item; it should not update the node deleted[0].name('Pluto') expect(testNode).toContainText('--Mercury++--Venus++--Earth++Moon--Mars++--Jupiter++--Saturn++') // After the delay, the deleted item's node is removed jasmine.Clock.tick(1) expect(testNode).toContainText('--Mercury++--Venus++--Earth++--Mars++--Jupiter++--Saturn++') }) /* describe('With "noChildContextWithAs" and "as"') There is no option in ko 4 for noChildContextWithAs; the default is that there is no child context when `as` is used, for both the `foreach` binding and the `template { foreach }`. */ it('Should not create a child context when `as` is used', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'><span data-bind='text: item'></span></div>" var someItems = ['alpha', 'beta'] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('alpha') expect(testNode.childNodes[0].childNodes[1]).toContainText('beta') expect(dataFor(testNode.childNodes[0].childNodes[0])).toEqual(dataFor(testNode)) expect(dataFor(testNode.childNodes[0].childNodes[1])).toEqual(dataFor(testNode)) }) it('Should provide access to observable items', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'><input data-bind='value: item'/></div>" var x = observable('first'), y = observable('second'), someItems = observableArray([ x, y ]) applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toHaveValues(['first', 'second']) expect(dataFor(testNode.childNodes[0].childNodes[0])).toEqual(dataFor(testNode)) expect(dataFor(testNode.childNodes[0].childNodes[1])).toEqual(dataFor(testNode)) // Should update observable when input is changed testNode.childNodes[0].childNodes[0].value = 'third' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(x()).toEqual('third') // Should update the input when the observable changes y('fourth') expect(testNode.childNodes[0]).toHaveValues(['third', 'fourth']) // Should update the inputs when the array changes someItems([x]) expect(testNode.childNodes[0]).toHaveValues(['third']) }) it('Should not re-render the nodes when an observable item changes', function () { testNode.innerHTML = "<div data-bind='foreach: { data: someItems, as: \"item\" }'><span data-bind='text: item'></span></div>" var x = observable('first'), someItems = [ x ] applyBindings({ someItems: someItems }, testNode) expect(testNode.childNodes[0]).toContainText('first') var saveNode = testNode.childNodes[0].childNodes[0] x('second') expect(testNode.childNodes[0]).toContainText('second') expect(testNode.childNodes[0].childNodes[0]).toEqual(saveNode) }) it('Can modify the set of top-level nodes in a foreach loop', function () { options.bindingProviderInstance.preprocessNode = function (node) { // Replace <data /> with <span data-bind="text: $data"></span> if (node.tagName && node.tagName.toLowerCase() === 'data') { var newNode = document.createElement('span') newNode.setAttribute('data-bind', 'text: $data') node.parentNode.insertBefore(newNode, node) node.parentNode.removeChild(node) return [newNode] } // Delete any <button> elements if (node.tagName && node.tagName.toLowerCase() === 'button') { node.parentNode.removeChild(node) return [] } } testNode.innerHTML = "<div data-bind='foreach: items'>" + '<button>DeleteMe</button>' + '<data></data>' + '<!-- ko text: $data --><!-- /ko -->' + '<button>DeleteMe</button>' + // Tests that we can remove the last node even when the preceding node is a virtual element rather than a single node '</div>' var items = observableArray(['Alpha', 'Beta']) applyBindings({ items: items }, testNode) expect(testNode).toContainText('AlphaAlphaBetaBeta') // Check that modifying the observable array has the expected effect items.splice(0, 1) expect(testNode).toContainText('BetaBeta') items.push('Gamma') expect(testNode).toContainText('BetaBetaGammaGamma') }) })
the_stack
(function () { try { // 注册设置菜单 API.registerMenu({ key: "common", name: "通用", svg: '<svg viewBox="0 0 24 24"><g><path d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"></path></g></svg>' }); API.registerMenu({ key: "rewrite", name: "重写", svg: `<svg viewBox="0 0 24 24"><g><path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"></path></g></svg>` }); API.registerMenu({ key: "restore", name: "修复", svg: `<svg viewBox="0 0 16 16"><path fill-rule="evenodd" d="M5 3.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm0 2.122a2.25 2.25 0 10-1.5 0v.878A2.25 2.25 0 005.75 8.5h1.5v2.128a2.251 2.251 0 101.5 0V8.5h1.5a2.25 2.25 0 002.25-2.25v-.878a2.25 2.25 0 10-1.5 0v.878a.75.75 0 01-.75.75h-4.5A.75.75 0 015 6.25v-.878zm3.75 7.378a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm3-8.75a.75.75 0 100-1.5.75.75 0 000 1.5z"></path></svg>` }); API.registerMenu({ key: "style", name: "样式", svg: `<svg viewBox="0 0 24 24"><g><path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c2.76 0 5-2.24 5-5 0-4.42-4.03-8-9-8zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9 8 9.67 8 10.5 7.33 12 6.5 12zm3-4C8.67 8 8 7.33 8 6.5S8.67 5 9.5 5s1.5.67 1.5 1.5S10.33 8 9.5 8zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 5 14.5 5s1.5.67 1.5 1.5S15.33 8 14.5 8zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 9 17.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"></path></g></svg>` }); API.registerMenu({ key: "danmaku", name: "弹幕", svg: `<svg viewBox="0 0 22 22"><path d="M16.5 8c1.289 0 2.49.375 3.5 1.022V6a2 2 0 00-2-2H4a2 2 0 00-2 2v10a2 2 0 002 2h7.022A6.5 6.5 0 0116.5 8zM7 13H5a1 1 0 010-2h2a1 1 0 010 2zm2-4H5a1 1 0 010-2h4a1 1 0 010 2z"></path><path d="M20.587 13.696l-.787-.131a3.503 3.503 0 00-.593-1.051l.301-.804a.46.46 0 00-.21-.56l-1.005-.581a.52.52 0 00-.656.113l-.499.607a3.53 3.53 0 00-1.276 0l-.499-.607a.52.52 0 00-.656-.113l-1.005.581a.46.46 0 00-.21.56l.301.804c-.254.31-.456.665-.593 1.051l-.787.131a.48.48 0 00-.413.465v1.209a.48.48 0 00.413.465l.811.135c.144.382.353.733.614 1.038l-.292.78a.46.46 0 00.21.56l1.005.581a.52.52 0 00.656-.113l.515-.626a3.549 3.549 0 001.136 0l.515.626a.52.52 0 00.656.113l1.005-.581a.46.46 0 00.21-.56l-.292-.78c.261-.305.47-.656.614-1.038l.811-.135A.48.48 0 0021 15.37v-1.209a.48.48 0 00-.413-.465zM16.5 16.057a1.29 1.29 0 11.002-2.582 1.29 1.29 0 01-.002 2.582z"></path></svg>` }); API.registerMenu({ key: "player", name: "播放", svg: `<svg viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zM6.379 5.227A.25.25 0 006 5.442v5.117a.25.25 0 00.379.214l4.264-2.559a.25.25 0 000-.428L6.379 5.227z"></path></svg>` }); API.registerMenu({ key: "live", name: "直播", svg: `<svg viewBox="0 0 1024 1024"><path d="M392.448 275.911111a92.416 92.416 0 1 1-184.832 0 92.416 92.416 0 0 1 184.832 0"></path><path d="M826.624 464.583111l-63.744 36.864v-48.64a72.206222 72.206222 0 0 0-71.68-71.936H190.72a72.192 72.192 0 0 0-71.936 71.936V748.231111a71.936 71.936 0 0 0 71.936 71.936H691.2a71.936 71.936 0 0 0 71.936-71.936v-23.808l63.488 37.888a51.2 51.2 0 0 0 76.8-44.544V508.871111a51.2 51.2 0 0 0-76.8-44.288M572.928 369.351111c79.459556 0.142222 143.985778-64.156444 144.128-143.616 0.142222-79.459556-64.156444-143.985778-143.616-144.128-79.260444-0.142222-143.701333 63.857778-144.128 143.104-0.426667 79.459556 63.644444 144.213333 143.104 144.64h0.512"></path><path d="M425.216 512.967111l124.16 71.936a25.6 25.6 0 0 1 0 42.496l-124.16 71.68a25.6 25.6 0 0 1-37.12-21.248V534.471111a25.6 25.6 0 0 1 37.12-21.504"></path></svg>` }); API.registerMenu({ key: "download", name: "下载", svg: `<svg viewBox="0 0 24 24"><g><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"></path></g></svg>` }); // 注册设置项 API.registerSetting({ key: "developer", sort: "common", label: "开发者模式", svg: '<svg viewBox="0 0 24 24"><g><path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"></path></g></svg>', type: "switch", value: false, float: '开发者模式将暴露核心变量 <b>API</b> 到页面顶级对象 window,可以借此在控制台调试部分功能。', sub: '暴露 API 到 window', action: (value) => { value ? (!(<any>window).API && ((<any>window).API = API)) : ((<any>window).API && delete (<any>window).API) } }) config.developer && ((<any>window).API = API); API.registerSetting({ key: "rewriteMethod", sort: "rewrite", label: "重写模式", sub: "兼容性选项", type: "row", value: "同步", list: ["同步", "异步"], float: '同步模式能够更有效阻断原生脚本执行,减少原生脚本对于页面的破坏,<strong>缺点是与其他脚本或拓展兼容性不佳</strong>。</br>异步模式尝试提高兼容性,相对应的阻断效果下降,新版页面一闪而过现象加剧且受网络延时影响更大。' }) API.registerSetting({ key: "av", sort: "rewrite", label: "av/BV", type: "switch", value: true, float: '重写以恢复旧版av视频播放页。' }) API.registerSetting({ key: "upList", sort: "style", label: "UP主列表", sub: "展示视频合作者", type: "switch", value: false }) API.registerSetting({ key: "electric", sort: "player", label: "跳过充电鸣谢", sub: "在视频末尾", type: "switch", value: false }) API.registerSetting({ key: "enlike", sort: "player", label: "添加点赞功能", sub: "自制、简陋", type: "switch", value: false, float: "旧版播放器的时代点赞功能还未存在,本脚本代为设计了个丑丑的点赞功能。" }) API.registerSetting({ key: "medialist", sort: "rewrite", label: "medialist", type: "switch", value: false, float: "用旧版av页重构medialist页面。" }) API.registerSetting({ type: "switch", key: "index", label: "主页", value: true, sort: "rewrite", float: '重写以恢复旧版主页' }) API.registerSetting({ type: "switch", key: "indexLoc", label: "过滤主页广告", sub: "banner+recommand", value: false, sort: "style", float: '当然指的是旧版主页。' }) API.registerSetting({ type: "switch", key: "privateRecommend", label: "禁用主页个性化推荐", sub: "还是习惯全站统一推荐", value: false, sort: "style", float: '禁用旧版主页banner右边的个性化推荐,恢复全站统一推荐。' }) API.registerSetting({ key: "protoDm", sort: "danmaku", label: "启用新版弹幕", sub: "proto弹幕", type: "switch", value: true, float: `添加旧版播放器新版proto弹幕支持。由于旧版xml弹幕已获取不到90分钟后的弹幕,本功能不建议禁用。</br>”` }) API.registerSetting({ key: "liveDm", sort: "danmaku", label: "修复实时弹幕", sub: "及时接收别人新发的弹幕", type: "switch", value: true, float: `修复旧版播放器实时弹幕。` }) API.registerSetting({ key: "commandDm", sort: "danmaku", label: "添加互动弹幕", sub: "投票弹窗等", type: "switch", value: false, float: `可以使用新版的一些弹窗互动组件。目前可用组件:评分弹窗、投屏弹窗、关联视频跳转按钮、带“UP主”标识弹幕。</br>※ <strong>需要同时开启新版proto弹幕。</strong>` }) API.registerSetting({ key: "logReport", sort: "common", label: "日志拦截", svg: '<svg viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1.5 1.75a.75.75 0 00-1.5 0v12.5c0 .414.336.75.75.75h14.5a.75.75 0 000-1.5H1.5V1.75zm14.28 2.53a.75.75 0 00-1.06-1.06L10 7.94 7.53 5.47a.75.75 0 00-1.06 0L3.22 8.72a.75.75 0 001.06 1.06L7 7.06l2.47 2.47a.75.75 0 001.06 0l5.25-5.25z"></path></svg>', sub: "拦截B站日志上报", float: "网页端日志采集太频繁,稍微动下鼠标都要发送数条日志请求,给network调试带来额外的困扰。", type: "switch", value: false }) API.registerSetting({ key: "heartbeat", sort: "restore", label: "修复视频心跳", sub: "出现不记录播放历史症状时的选择", float: "尝试修复可能被广告拦截扩展误伤的视频心跳。", type: "switch", value: false }) API.registerSetting({ key: "noVideo", sort: "player", label: "拦截视频载入", sub: "用于临时不加载视频进入视频页面", float: "拦截播放器载入视频,强行使视频失效。", type: "switch", value: false }) API.registerSetting({ key: "bannerGif", sort: "style", label: "丰富顶栏动图", sub: '搜索框下gif', float: "替换顶栏动图接口,避免单调。", type: "switch", value: true }) API.registerSetting({ key: "danmakuFirst", sort: "style", label: "自动切换到弹幕列表", sub: "默认是展示推荐视频", float: "自动从推荐视频切换到播放弹幕列表。", type: "switch", value: false }) API.registerSetting({ type: "sort", key: "autoDo", label: "自动化操作", sort: "player", sub: "进入播放页面及切P时", list: [{ key: "showBofqi", sort: "style", label: "自动滚动到播放器", type: "switch", value: false }, { key: "screenWide", sort: "style", label: "自动宽屏", type: "switch", value: false }, { key: "noDanmaku", sort: "style", label: "自动关弹幕", type: "switch", value: false }, { key: "autoPlay", sort: "style", label: "自动播放", type: "switch", value: false }] }) API.registerSetting({ key: "segProgress", sort: "player", label: "分段进度条", sub: "仅限看点视频", type: "switch", value: false }) API.registerSetting({ key: "replyList", sort: "style", label: "恢复评论翻页", sub: "可以选择跳转而不必一直下拉", type: "switch", value: true, float: '恢复旧版翻页评论区。</br>重写过的页面除外,那些默认就是翻页评论区。' }) API.registerSetting({ key: "section", sort: "style", label: "统一换回旧版顶栏", sub: "针对未重写的页面", type: "switch", value: true, float: '非重写页面顶栏底栏也替换为旧版。' }) API.registerSetting({ key: "concatDanmaku", sort: "danmaku", label: "合并载入弹幕", sub: "本地弹幕/在线弹幕", type: "switch", value: false, float: '载入本地弹幕文件或者在线弹幕时是否与播放器当前弹幕合并。' }) API.registerSetting({ key: "danmakuHashId", sort: "danmaku", label: "反查弹幕发送者", sub: "结果仅供参考!", type: "switch", value: false, float: '旧版播放器上右键弹幕将显示弹幕发送者。</br>※ 使用哈希逆向算法,存在碰撞可能性,所示信息仅供参考,或者干脆查不出来。' }) API.registerSetting({ type: "switch", key: "errands", label: '恢复对于<a href="//space.bilibili.com/11783021" target="_blank">番剧出差</a>和<a href="//space.bilibili.com/1988098633" target="_blank">DM組</a>的访问', sub: '还好没赶尽杀绝', value: true, sort: "restore", float: '使用备份数据修复对于番剧出差官方空间的访问。' }) API.registerSetting({ type: "switch", key: "album", label: "还原个人空间相簿链接", sub: "相簿比动态页面好看", value: false, sort: "restore", float: '将个人空间的相簿链接从动态重定向回原来的相簿。' }) API.registerSetting({ type: "switch", key: "jointime", label: "显示账号注册时间", sub: "历史不该被隐藏", value: false, sort: "restore", float: '在空间显示对应账号的注册时间。' }) API.registerSetting({ key: "lostVideo", sort: "restore", label: "修复失效视频信息", sub: `有些甚至评论还在!`, type: "switch", value: false, float: '使用第三方数据修复收藏、频道等处的失效视频信息。(以红色删除线标记)</br>访问失效视频链接时将尝试重建av页面。</br>※ 依赖第三方数据库且未必有效,<strong>请谨慎考虑是否开启!</strong>' }) API.registerSetting({ key: "bangumi", sort: "rewrite", label: "bangumi", sub: "ss/ep", type: "switch", value: true, float: '重写以恢复旧版bangumi播放页。' }) API.registerSetting({ key: "limit", sort: "player", label: "解除区域/平台限制", sub: "港澳台?泰版?仅限APP?", float: "同类功能脚本可能会冲突,使用专用脚本切莫开启本功能!", type: "sort", list: [ { key: "videoLimit", sort: "player", label: "解除限制", type: "switch", value: false, sub: "区域+APP" }, { key: "limitAccesskey", sort: "player", label: "账户授权", sub: "泰区除外", type: "action", title: "管理", action: () => { API.showAccesskey() } }, { key: "limitServer", sort: "player", label: "泰区代理", type: "input", value: "https://api.global.bilibili.com", float: "泰区番剧限制需要自备相应的代理服务器(无需末尾的斜杠!)。</br>本功能由于缺乏调试条件维护不善请多担待!", input: { type: "url", placeholder: "URL" }, pattern: /(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/ } ] }) API.registerSetting({ key: "bangumiEplist", sort: "player", label: "保留番剧回目列表", sub: "牺牲特殊背景图", type: "switch", value: false, float: '部分带特殊背景图片的番剧会隐藏播放器下方的番剧回目列表,二者不可得兼,只能选一。' }) API.registerSetting({ key: "episodeData", sort: "style", label: "显示番剧分集数据", sub: "原本是合集数据", type: "switch", value: false, float: '有分集数据时将bangumi播放、弹幕数替换为当集数据。原合集数据将显示在鼠标焦点信息上。' }) API.registerSetting({ type: "switch", key: "watchlater", label: "稍后再看", value: true, sort: "rewrite", float: '重写以恢复旧版稍后再看。' }) API.registerSetting({ type: "switch", key: "history", label: "只显示视频历史", sub: "去除专栏、直播记录", value: false, sort: "style" }) API.registerSetting({ type: "switch", key: "searchHistory", label: "去除历史记录页面搜索框", sub: "其实留着也没什么", value: false, sort: "style" }) API.registerSetting({ type: "switch", key: "liveStream", label: "拦截直播流/轮播流", sub: "那我为什么点开直播?", value: false, sort: "live", float: "将直播间设为未开播状态,不加载直播流或者轮播视频,适用于想打开直播间但不想浪费带宽或流量的情况。</br>※ 脚本注入不够快时可能拦截失败,硬刷新`Ctrl+Shift+R`/`Shift + F5`可解。" }) API.registerSetting({ type: "switch", key: "liveP2p", label: "禁止P2P上传", sub: "小水管禁不起别人白嫖!", value: true, sort: "live", float: "禁止直播间使用WebRTC进行P2P共享上传,以免暴露ip地址,并为小水管节约带宽。" }) API.registerSetting({ type: "switch", key: "sleepCheck", label: "禁止挂机检测", sub: "就喜欢挂后台听个响不行吗!", value: true, sort: "live", float: "禁止直播间5分钟不操作判定挂机并切断直播,可以放心挂后台听个响。" }) API.registerSetting({ type: "switch", key: "anchor", label: "禁用天选时刻", sub: "反正中不了的,哼!", value: false, sort: "live" }) API.registerSetting({ type: "switch", key: "pkvm", label: "禁用大乱斗", sub: "挡着我欣赏主播了", value: false, sort: "live" }) API.registerSetting({ type: "switch", key: "player", label: "嵌入", value: true, sort: "rewrite", float: '重写以恢复旧版嵌入播放器。' }) API.registerSetting({ type: "switch", key: "ranking", label: "排行榜", value: true, sort: "rewrite", float: "重写以恢复旧版全站排行榜。" }) API.registerSetting({ type: "switch", key: "read", label: "专栏", value: true, sort: "rewrite", float: "重写以启用旧版专栏。" }) API.registerSetting({ type: "switch", key: "unloginPopover", label: "移除未登录弹窗", sub: "有些时候就是不喜欢登录", value: false, sort: "style" }) API.registerSetting({ key: "downloadPicture", type: "picture", sort: "download", src: '//s2.hdslb.com/bfs/static/blive/blfe-album-detail/static/img/empty-hint.7b606b9.jpg', hidden: !API.aid, callback: function () { API.aid && API.getAidInfo(API.aid).then(d => { this.innerHTML = `<picture><img src="${d.View.pic.replace("http:", "")}"></picture>` }) } }) API.runWhile(() => API.aid, () => { API.changeSettingMode({ downloadPicture: false }) }) API.registerSetting({ type: "switch", sort: "download", key: "downloadContentmenu", label: "右键菜单", sub: "播放画面上右键添加下载菜单", value: false }) API.registerSetting({ type: "mutlti", sort: "download", key: "downloadList", label: "视频类型", sub: "右键呼出下载时请求的类型", value: ["mp4", "dash"], list: ["mp4", "dash", "flv"], float: '下载功能会自动读取播放器已载入的视频源并呈现在下载面板上,即使未勾选对应的视频类型。</br>勾选了也不一定能获取到该类型的视频源。' }) API.registerSetting({ type: "row", sort: "download", key: "downloadQn", label: "默认画质", sub: "针对flv格式", value: 125, list: ["0", 15, 16, 32, 48, 64, 74, 80, 112, 116, 120, 125], float: '画质qn参数,数值越大画质越高,0表示自动。64(720P)以上需要登录,112(1080P+)以上需要大会员。一般只需设置为最大即可,会自动获取到能获取的最高画质。' }) API.registerSetting({ type: "row", sort: "download", key: "downloadMethod", label: "下载方式", value: "右键保存", list: ["右键保存", "ef2", "aria2", "aira2 RPC"], action: (v) => { switch (v) { case "ef2": API.alertMessage(`<a href="https://github.com/MotooriKashin/ef2/releases" target="_blank">EF2</a>是作者开发的一款从浏览器中拉起IDM进行下载的中间软件,可以非常方便地传递下载数据给IDM,并支持自定义文件名、保存目录等。<strong>您必须安装了ef2和IDM才能使用本方式!</strong>`).then(d => { d ? API.changeSettingMode({ referer: false, useragent: false, filepath: false, IDMLater: false, IDMToast: false, rpcServer: true, rpcPort: true, rpcToken: true, rpcTest: true }) : (config.downloadMethod = "右键保存", API.changeSettingMode({ referer: true, useragent: true, filepath: true, IDMLater: true, IDMToast: true, rpcServer: true, rpcPort: true, rpcToken: true, rpcTest: true })); API.displaySetting("downloadMethod"); }) break; case "aria2": API.alertMessage(`aria2是一款著名的命令行下载工具,使用本方式将在您点击下载面板中的链接时将命令行复制到您的剪切板中,您可以粘贴到cmd等终端中回车进行下载。<strong>您必须先下载aria2工具并添加系统环境变量或者在终端在打开aria2二进制文件所在目录!</strong>`).then(d => { d ? API.changeSettingMode({ referer: false, useragent: false, filepath: false, IDMLater: true, IDMToast: true, rpcServer: true, rpcPort: true, rpcToken: true, rpcTest: true }) : (config.downloadMethod = "右键保存", API.changeSettingMode({ referer: true, useragent: true, filepath: true, IDMLate: true, IDMToast: true, rpcServer: true, rpcPort: true, rpcToken: true, rpcTest: true })); API.displaySetting("downloadMethod"); }) break; case "aira2 RPC": API.alertMessage(`aria2支持RPC方式接收下载数据,您需要在aria2配置开启RPC功能并保持后台运行,并在本脚本设置中配置好aria2主机及端口。</br>点击确定将刷新设置面板并呈现相关设置。`).then(d => { d ? API.changeSettingMode({ referer: false, useragent: false, filepath: false, IDMLater: true, IDMToast: true, rpcServer: false, rpcPort: false, rpcToken: false, rpcTest: false }) : (config.downloadMethod = "右键保存", API.changeSettingMode({ referer: true, useragent: true, filepath: true, IDMLater: true, IDMToast: true, rpcServer: true, rpcPort: true, rpcToken: true, rpcTest: true })); API.displaySetting("downloadMethod"); }) break; default: API.changeSettingMode({ referer: true, useragent: true, filepath: true, IDMLater: true, IDMToast: true, rpcServer: true, rpcPort: true, rpcToken: true, rpcTest: true }); API.displaySetting("downloadMethod"); } } }) API.registerSetting({ type: "input", sort: "download", key: "useragent", label: "User-Agent", value: "Bilibili Freedoooooom/MarkII", input: { type: "text" }, float: `用户代理,此值不可为空,默认使用B站客户端专属UA。`, hidden: config.downloadMethod == "右键保存" }) API.registerSetting({ type: "input", sort: "download", key: "referer", label: "referer", value: location.origin, input: { type: "text" }, float: `一般为B站主域名(http://www.bilibili.com)。</br><strong>APP/TV等下载源此视频源必须为空!</strong>`, hidden: config.downloadMethod == "右键保存" }) API.registerSetting({ type: "input", sort: "download", key: "filepath", label: "保存目录", value: "", input: { type: "text", placeholder: "如:D\\下载" }, float: 'windows端请注意反斜杠!', hidden: config.downloadMethod == "右键保存" }) API.registerSetting({ key: "IDMLater", sort: "download", label: "稍后下载", sub: "添加到IDM列表而不立即下载", type: "switch", value: false, float: "把下载链接添加到下载列表但是不立即开始下载,需要下载时再手动到IDM里开始。<strong>B站下载链接一般都有时效,太久不下载的话链接可能失效!</strong>", hidden: config.downloadMethod != "ef2" }) API.registerSetting({ key: "IDMToast", sort: "download", label: "静默下载", sub: "不用IDM确认框", type: "switch", value: false, float: "禁用IDM下载前的询问弹窗,其中可以选择修改文件名及保存目录等信息。", hidden: config.downloadMethod != "ef2" }) API.registerSetting({ key: "rpcServer", sort: "download", label: "RPC主机", type: "input", input: { type: "url", placeholder: "如:http(s)://localhost" }, value: "http://localhost", hidden: config.downloadMethod != "aira2 RPC" }) API.registerSetting({ key: "rpcPort", sort: "download", label: "RPC端口", type: "input", input: { type: "number", placeholder: "如:6800" }, value: 6800, hidden: config.downloadMethod != "aira2 RPC" }) API.registerSetting({ key: "rpcToken", sort: "download", label: "RPC令牌(可选)", type: "input", input: { type: "password" }, value: "", hidden: config.downloadMethod != "aira2 RPC" }) API.registerSetting({ key: "rpcTest", sort: "download", label: "RPC调试", type: "action", title: "测试", hidden: config.downloadMethod != "aira2 RPC", action: () => { API.aria2.rpcTest() .then(d => toast.success(`RPC设置正常!aria2版本:${d.version}`)) .catch(e => toast.error("RPC链接异常!请检查各项设置以及RPC主机的状况!", e)) } }) API.registerSetting({ key: "dlDmCC", sort: "download", label: "其他下载", sub: "弹幕、CC字幕等", type: "sort", list: [ { key: "ifDlDmCC", sort: "download", label: "弹幕、CC字幕、封面", type: "switch", value: false }, { key: "dlDmType", sort: "download", label: "弹幕格式", type: "row", value: "xml", list: ["xml", "json"], float: `xml是经典的B站弹幕格式,json是旧版播放器直接支持的格式,本脚本载入本地弹幕功能同时支持这两种。</br>如果只是给本脚本专用那就选json,xml对“非法字符”支持不友好,部分高级/代码/BAS弹幕可能出错。` } ] }) // 旧版播放器专属设置 API.registerSetting({ key: "onlineDanmaku", sort: "danmaku", label: "在线弹幕", type: "input", float: '为当前旧版播放器载入其他站内视频弹幕,可以输入URL或者aid等参数。</br>※ 可配合选择是否合并已有弹幕。', input: { type: "url", placeholder: "URL" }, title: "载入", hidden: true, action: (url) => { if (!window.player?.setDanmaku) return toast.warning("内部组件丢失,已停止!"); API.onlineDanmaku(url); } }) API.registerSetting({ key: "allDanmaku", sort: "danmaku", label: "全弹幕装填", type: "sort", float: '获取所有能获取的历史弹幕。</br><strong>※ 该操作耗时较长且可能造成B站临时封接口,请慎用!</strong>', hidden: true, list: [{ key: "allDanmakuDelay", sort: "danmaku", label: "冷却时间:/s", type: "input", value: <any>3, input: { type: "number", min: 1, max: 60, step: 0.5 }, float: '接口冷却时间,时间长可以降低被临时封端口的几率。' }, { key: "allDanmakuAction", sort: "danmaku", label: "开始获取", type: "action", title: "开始", action: function () { if (!window.player?.setDanmaku) return toast.warning("内部组件丢失,已停止!"); API.allDanmaku(); }, disabled: 0 }] }) API.registerSetting({ key: "localMedia", sort: "player", label: "载入本地文件", sub: "视频/弹幕", type: "file", accept: [".mp4", ".xml", ".json"], float: '使用旧版播放器播放本地视频或者弹幕文件。</br>※ 视频只能为mp4格式,且编码格式被浏览器所兼容。</br>※ 若载入弹幕文件,参见弹幕设置是否合并弹幕。', title: "文件", hidden: true, action: (files) => { (!window.player?.setDanmaku) && toast.warning("内部组件丢失,无法载入弹幕文件!"); API.localMedia(files); } }) API.path && API.path.name && API.runWhile(() => API.path.name && (<any>window).player, () => { API.changeSettingMode({ onlineDanmaku: false, allDanmaku: false, localMedia: false }) }) API.registerSetting({ key: "commentLinkDetail", sort: "style", label: "还原评论中的超链接", sub: "av、ss或ep", type: "switch", value: false }) API.registerSetting({ key: "configManage", sort: "common", svg: '<svg viewBox="0 0 24 24"><g><path d="M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z"></path></g></svg>', label: "设置数据", sub: "备份/恢复", type: "action", title: "管理", action: () => API.importModule("manage.js", undefined, true) }) } catch (e) { toast.error("setting.js", e) } })(); /** * 已注册的菜单,通过`registerMenu`新建项请补充这里的可能值 * **本变量仅作为类型声明接口类似的东西存在,不可参与到任何实际运行代码中!** */ declare const settingSort: "common" | "rewrite" | "restore" | "style" | "danmaku" | "player" | "live" | "download" /** * 已注册设置项 */ declare namespace config { /** * 开发者模式 */ let developer: boolean; /** * 重写:av/BV */ let av: boolean; /** * 样式:UP主列表 */ let upList: boolean; /** * 播放:跳过充电鸣谢 */ let electric: boolean; /** * 播放:点赞功能 */ let enlike: boolean; /** * 重写:medialist */ let medialist: boolean; /** * 重写:主页 */ let index: boolean; /** * 样式:过滤主页广告 */ let indexLoc: boolean; /** * 样式:去除个性化推荐 */ let privateRecommend: boolean; /** * 弹幕:互动弹幕 */ let commandDm: boolean; /** * 弹幕:新版弹幕 */ let protoDm: boolean; /** * 弹幕:实时弹幕 */ let liveDm: boolean; /** * 通用:日志拦截 */ let logReport: boolean; /** * 修复:视频心跳 */ let heartbeat: boolean; /** * 播放:拦截视频 */ let noVideo: boolean; /** * 样式:顶栏动图 */ let bannerGif: boolean; /** * 样式:弹幕优先 */ let danmakuFirst: boolean; /** * 样式:自动滚动到播放器 */ let showBofqi: boolean; /** * 样式:自动宽屏 */ let screenWide: boolean; /** * 样式:自动关弹幕 */ let noDanmaku: boolean; /** * 样式:自动播放 */ let autoPlay: boolean; /** * 播放:分段进度条 */ let segProgress: boolean; /** * 样式:翻页评论 */ let replyList: boolean; /** * 样式:顶栏底栏 */ let section: boolean; /** * 播放:弹幕合并 */ let concatDanmaku: boolean; /** * 弹幕:弹幕反查 */ let danmakuHashId: boolean; /** * 弹幕:全弹幕装填冷却时间 */ let allDanmakuDelay: number; /** * 修复:番剧出差 */ let errands: boolean; /** * 修复:相簿链接 */ let album: boolean; /** * 修复:注册时间 */ let jointime: boolean; /** * 修复:失效视频信息 */ let lostVideo: boolean; /** * 重写:bangumi */ let bangumi: boolean; /** * 播放:解除限制 */ let videoLimit: boolean; /** * 播放:泰区代理服务器 */ let limitServer: string; /** * 播放:番剧回目列表 */ let bangumiEplist: boolean; /** * 样式:番剧分集数据 */ let episodeData: boolean; /** * 重写:稍后再看 */ let watchlater: boolean; /** * 样式:只显示视频历史 */ let history: boolean; /** * 样式:去除历史记录页面搜索框 */ let searchHistory: boolean; /** * 直播:拦截直播流 */ let liveStream: boolean; /** * 直播:P2P上传 */ let liveP2p: boolean; /** * 直播:禁止挂机检测 */ let sleepCheck: boolean; /** * 直播:禁用天选时刻 */ let anchor: boolean; /** * 直播:禁用大乱斗 */ let pkvm: boolean; /** * 重写:嵌入播放器 */ let player: boolean; /** * 重写:排行榜 */ let ranking: boolean; /** * 重写:专栏 */ let read: boolean; /** * 重写:重写模式 */ let rewriteMethod: string; /** * 样式:登录弹窗 */ let unloginPopover: boolean; /** * 下载:右键菜单 */ let downloadContentmenu: boolean; /** * 下载:视频类型 */ let downloadList: ("mp4" | "dash" | "flv")[]; /** * 下载:画质参数 */ let downloadQn: number; /** * 下载:下载方式 */ let downloadMethod: string; /** * 下载:UserAgent */ let useragent: string; /** * 下载:保存目录 */ let filepath: string; /** * 下载:稍后下载 */ let IDMLater: boolean; /** * 下载:静默下载 */ let IDMToast: boolean; /** * 下载:RPC主机 */ let rpcServer: string; /** * 下载:RPC端口 */ let rpcPort: number; /** * 下载:referer */ let referer: string; /** * 下载:RPC令牌 */ let rpcToken: string; /** * 下载:其他下载 */ let ifDlDmCC: boolean; /** * 下载:弹幕类型 */ let dlDmType: string; /** * 样式:评论超链接 */ let commentLinkDetail: boolean; } /** * 工具栏按钮 */ interface ToolIcon { /** * 设置唯一主键,非必需 * **注意不能与已有设置项重复** */ key?: string; /** * 类型标志,用于识别这是工具栏按钮设置项 */ type: "icon"; /** * 按钮 svg 图标字符串 */ svg: string; /** * 鼠标焦点按钮时提示的文字 */ title: string; /** * 鼠标单击时的回调 */ action: (node: HTMLDivElement) => void; /** * 隐藏该设置项,比如不满足某些前置条件 * 对于有key的设置可以通过changeSettingMode方法改变其显示状态 */ hidden?: boolean; } /** * 菜单项 */ interface Menuitem { /** * 菜单主键(唯一),可以取已有的,也可以自定义 */ key: string; /** * 主键名字,简短的菜单分类名字,与 key 一一对应 */ name: string; /** * 菜单图标 svg 字符串 */ svg?: string; } /** * 图片类菜单项,可以作为banner或者下一项设置的图解说明等 */ interface ItemPic { /** * 设置唯一主键,非必需 * **注意不能与已有设置项重复** */ key?: string; /** * 类型标志,用于识别这是图片类设置项 */ type: "picture"; /** * 菜单归属分类菜单,也可以新建 */ sort: typeof settingSort; /** * 图片 URL */ src: string; /** * 设置呈现时执行的回调函数,this为设置项节点,可以据此修改设置项呈现 * **其子节点一般都使用shadowDOM封装,外部js无权访问,但可以自己生成节点进行覆盖(如使用innerHTML属性)** */ callback?: (this: HTMLDivElement) => void; /** * 隐藏该设置项,比如不满足某些前置条件 * 对于有key的设置可以通过changeSettingMode方法改变其显示状态 */ hidden?: boolean; } interface ItemCommon { /** * 设置唯一主键,将作为全局变量`config`的属性名。 * **注意不能与已有设置项重复** */ key: string; /** * 菜单归属分类菜单 * 可以使用已有的,参见接口`settingSort` * 若要新建,请使用`API.registerMenu`添加,并补充`settingSort`声明的可能值 */ sort: typeof settingSort; /** * 设置 svg 图片 */ svg?: string; /** * 设置内容 */ label: string; /** * 内容附加简短介绍 */ sub?: string; /** * 鼠标移动到设置项时浮动信息,可以详细介绍设置的信息 * 该内容可以包含\<i\>、\<strong\>等HTML便签用于格式化信息 * ※ 理论上支持所有能以\<div\>为父节点的标签 */ float?: string; /** * 设置呈现时执行的回调函数,this为设置项节点,可以据此修改设置项呈现 * **其子节点一般都使用shadowDOM封装,外部js无权访问,但可以自己生成节点进行覆盖(如使用innerHTML属性)** */ callback?: (this: HTMLDivElement) => void; /** * 隐藏该设置项,比如不满足某些前置条件 * 对于有key的设置可以通过changeSettingMode方法改变其显示状态 */ hidden?: boolean; } /** * 开关类菜单项,用以给用户判断是否开启某些功能等 * 可以在`action`属性添加回调函数以立即响应用户的开关操作 * 否则可能需要刷新页面才会生效 */ interface ItemSwh extends ItemCommon { /** * 类型标志,用于识别这是开关类设置项 */ type: "switch"; /** * 设置的值,添加设置项时将作为默认值 * 实际时将以用户本地配置`config[key]`为准 */ value: boolean; /** * 点击该设置时的回调函数 * 将调整后的`value`作为参数传递 * 设置节点本身将作为`this`传递 */ action?: (value: Boolean) => void; } /** * 下拉框类菜单项,用于给用户从多个数值选一个等 * 可以在`action`属性添加回调函数以立即响应用户的开关操作 * 否则可能需要刷新页面才会生效 */ interface ItemRow extends ItemCommon { /** * 类型标志,用于识别这是下拉框类设置项 */ type: "row"; /** * 默认取值 * 实际时将以用户本地配置`config[key]`为准 */ value: string | number; /** * 下拉框可选值列表 */ list: (string | number)[]; /** * 改变选值后的回调函数 * 将调整后的`value`作为参数传递 * 设置节点本身将作为`this`传递 */ action?: (value: string) => void } /** * 按钮设置,用以用户点击按钮执行操作 * 必须在`action`属性添加回调函数 */ interface ItemPus extends ItemCommon { /** * 类型标志,用于识别这是按钮设置项 */ type: "action"; /** * 按钮上的文字 */ title: string; /** * 点击按钮执行的回调函数 * 设置节点本身将作为this传入 */ action: () => void, /** * 点击按钮后临时禁用按钮多长时间,单位:/s,默认为 3 * 0 表示一直禁用直到刷新面板 */ disabled?: number; } /** * 输入框设置项,用以提供一个输入框与用户交互等 * 需要自行将HTML的`input`标签配置以对象形式写入`input`属性 */ interface ItemIpt extends ItemCommon { /** * 类型标志,用于识别这是输入框设置项 */ type: "input"; /** * 用于给`input`标签添加的属性 * 请自行通过合适的属性来指定`input`类型及其他要求 */ input: input; /** * 回调函数,用于接受用户输入内容以执行操作 * 将输入值作为参数传递 * 设置节点本身将作为`this`传递 */ action?: (value: string) => void; /** * 输入框后按钮上的文字 */ title?: string; /** * 默认值,输入框内的默认值 * 这意味着本设置将保存到本地 config */ value?: string | number; /** * 用于判断输入的正则表达式 */ pattern?: RegExp; /** * 点击按钮后临时禁用按钮多长时间,单位:/s,默认为 3 * 0 表示一直禁用直到刷新面板 */ disabled?: number; } /** * 文件选择设置项,用于提取本地文件读取等 */ interface ItemFie extends ItemCommon { /** * 类型标志,用于识别这是文件选择设置项 */ type: "file"; /** * 按钮上的文字 */ title: string; /** * 文件拓展名列表:如 `.txt` */ accept?: string[]; /** * 是否允许文件多选 */ multiple?: boolean; /** * 点击按钮执行的回调函数 * 设置节点本身将作为this传递 * 将文件列表`input.files`作为参数传递 */ action: (files: FileList) => void } /** * 多选类菜单项,用以提供一组数据供用户不定多选等 * 可以在`action`属性添加回调函数以立即响应用户的开关操作 * 如果值只有一个等于另一种形式的开关菜单只是回调还是数组 * 注意:任意选项改变都会触发回调 */ interface ItemMut extends ItemCommon { /** * 类型标志,用于识别这是输入框设置项 */ type: "mutlti"; /** * 默认取值列表 * 实际时将以用户本地配置`config[key]`为准 */ value: string[]; /** * 所有选项列表 */ list: string[]; /** * 改变选值后的回调函数 * 将调整后的`value`作为参数传递 * 设置节点本身将作为`this`传递 */ action?: (value: string[]) => void } /** * input标签的可选属性 */ interface input { /** * 选择提交的文件类型,仅限type="file" * `audio/*` `video/*` `image/*` `MIME_type` */ accept?: string; /** * 图像输入的替代文本,仅限type="image" */ alt?: string; /** * 自动完成输入 */ autocomplete?: "on" | "off"; /** * 页面加载时自动焦点 */ autofocus?: "autofocus"; /** * 页面加载时自动选中,仅限ype="checkbox"或type="radio" */ checked?: "checked"; /** * 禁用输入框 */ disabled?: "disabled"; /** * 所属的表单,复数时以逗号间隔 */ form?: string; /** * 提交表单时的URL,仅限type="submit"或type="image" */ formaction?: string; /** * 表单数据使用的编码,仅限type="submit"或type="image" */ formenctypeNew?: string; /** * 表单提交使用的HTTP方法,仅限type="submit"或type="image" */ formmethod?: "GET" | "POST"; /** * 覆盖表单标签的`novalidate`属性 */ formnovalidate?: "formnovalidate"; /** * 由谁处理表单相应,取值内置关键词或对应的`framename` */ formtarget?: "_blank" | "_self" | "_parent" | "_top" | string; /** * 元素高度:/px,仅限type="image" */ height?: number; /** * 绑定的<datalist>元素的id */ list?: string; /** * 接受输入的最大值 */ max?: number | string; /** * 输入框最大字符数 */ maxlength?: number; /** * 接受输入的最小值 */ min?: number | string; /** * 允许多个输入,仅限type="file"或type="email" */ multiple?: "multiple"; /** * 元素名称 */ name?: string; /** * 输入提示信息 */ placeholder?: string; /** * 只读元素 */ readonly?: "readonly"; /** * 禁止空提交 */ required?: "required"; /** * 元素可见宽度 */ size?: number; /** * 提交按钮的图片URL */ src?: string; /** * 输入的合法间隔 */ step?: number; /** * 输入框类型 */ type?: "button" | "checkbox" | "color" | "date" | "datetime" | "datetime-local" | "email" | "file" | "hidden" | "image" | "month" | "number" | "password" | "radio" | "range" | "reset" | "search" | "submit" | "tel" | "text" | "time" | "url" | "week" /** * 元素的宽度:/px,仅限type="image" */ width?: number; } /** * 归档一组设置,这组设置将在点击本条设置后展开 * 用于分组一些关联性很强或者同类的设置 * 可以看作是在菜单中再分类 */ interface ItemSor extends ItemCommon { /** * 类型标志,用于识别这是分组集合设置项 */ type: "sort"; /** * 类别名称 */ label: string; /** * 设置组,包含该类下属设置项 */ list: (ItemPic | ItemSwh | ItemSor | ItemRow | ItemPus | ItemIpt | ItemFie | ItemMut | ToolIcon | ItemCus)[] ; } /** * 自定义设置项,本设置项支持使用HTML语法自定义设置项值的部分 * 如果预定义的设置类型满足不了需求,那么此种类型可能满足需求 */ interface ItemCus extends ItemCommon { /** * 类型标志,用于识别这是自定义设置 */ type: "custom"; /** * 设置主键(唯一),用于唯一确定设置项 */ key: string; /** * 要自定义显示的设置内容,可以使用所有支持在\<div\>标签下的HTML标签 * 内容完全封装在独立的shadowDOM中,这意味这可以使用独立的<style>标签而不用担心样式指示器影响到页面其他部分 */ custom: string; /** * 一个回调函数,设置项绘制后将执行该回调并将本设置数据以参数形式传递 * 您可以设置这个回调函数以接受参数信息,并在需要时对其进行更新,更新结果会及时同步在设置界面中。 */ flesh?: (obj: ItemCus) => void; } declare namespace API { /** * 注册设置项 * 脚本内置多种设置模型,用于往脚本设置界面添加设置 * @param obj 设置对象 */ function registerSetting(obj: ItemPic | ItemSwh | ItemSor | ItemRow | ItemPus | ItemIpt | ItemFie | ItemMut | ToolIcon | ItemCus): void; /** * 注册设置项所属菜单信息 * @param obj 用于将设置分类,设置项中sort值即可这里注册的key值 */ function registerMenu(obj: Menuitem): void; /** * 修改设置项的显示状态,只能改变有key的设置项 * 可配合displaySetting([key])立即刷新当前设置面板显示 * @param mode key:是否隐藏 构成的对象,注意真值表示隐藏 */ function changeSettingMode(mode: Record<string, boolean>): void; }
the_stack
import { expect } from './expect' import { Logger, InvalidParameterError, UUID, ReadModelRequestEnvelope, GraphQLOperation, NotFoundError, NotAuthorizedError, SubscriptionEnvelope, FilterFor, BoosterConfig, } from '@boostercloud/framework-types' import { restore, fake, match, spy, replace } from 'sinon' import { BoosterReadModelsReader } from '../src/booster-read-models-reader' import { random, internet } from 'faker' import { BoosterAuth } from '../src/booster-auth' import { Booster } from '../src/booster' const logger: Logger = { debug() {}, info() {}, error() {}, } describe('BoosterReadModelReader', () => { const config = new BoosterConfig('test') config.provider = { readModels: { search: fake(), subscribe: fake(), deleteSubscription: fake(), deleteAllSubscriptions: fake(), }, } as any afterEach(() => { restore() }) class TestReadModel { public id: UUID = '∂' } class SequencedReadModel { public id: UUID = 'π' } class UserRole {} // Why sorting by salmon? Salmons are fun! https://youtu.be/dDj7DuHVV9E config.readModelSequenceKeys[SequencedReadModel.name] = 'salmon' const readModelReader = new BoosterReadModelsReader(config, logger) const noopGraphQLOperation: GraphQLOperation = { query: '', } context('requests by Id', () => { beforeEach(() => { config.readModels[TestReadModel.name] = { class: TestReadModel, authorizedRoles: [UserRole], properties: [], before: [], } config.readModels[SequencedReadModel.name] = { class: SequencedReadModel, authorizedRoles: [UserRole], properties: [], before: [], } }) afterEach(() => { delete config.readModels[TestReadModel.name] delete config.readModels[SequencedReadModel.name] }) describe('the `validateByIdRequest', () => { const validateByIdRequest = (readModelReader as any).validateByIdRequest.bind(readModelReader) it('throws an invalid parameter error when the version is not present in a request', () => { expect(() => { validateByIdRequest({}) }).to.throw('"version" was not present') }) it("throws a not found error when it can't find the read model metadata", () => { expect(() => { validateByIdRequest({ version: 1, class: { name: 'NonexistentReadModel' } }) }).to.throw(/Could not find read model/) }) it('throws a non authorized error when the current user is not allowed to perform the request', () => { expect(() => { validateByIdRequest({ version: 1, class: TestReadModel }) }).to.throw(/Access denied/) }) it('throws an invalid parameter error when the request receives a sequence key but it cannot be found in the Booster metadata', () => { replace(BoosterAuth, 'isUserAuthorized', fake.returns(true)) expect(() => { validateByIdRequest({ version: 1, class: TestReadModel, currentUser: { id: '666', username: 'root', role: 'root' }, key: { id: 'π', sequenceKey: { name: 'salmon', value: 'sammy' }, }, }) }).to.throw(/Could not find a sort key/) }) it('does not throw an error when there is no sequence key and everything else is ok', () => { replace(BoosterAuth, 'isUserAuthorized', fake.returns(true)) expect(() => { validateByIdRequest({ version: 1, class: TestReadModel, currentUser: { id: '666', username: 'root', role: 'root' }, }) }).not.to.throw() }) it('does not throw an error when there is a valid sequence key and everything else is ok', () => { replace(BoosterAuth, 'isUserAuthorized', fake.returns(true)) expect(() => { validateByIdRequest({ version: 1, class: SequencedReadModel, currentUser: { id: '666', username: 'root', role: 'root' }, key: { id: '§', sequenceKey: { name: 'salmon', value: 'sammy' }, }, }) }).not.to.throw() }) }) describe('the `findById` method', () => { beforeEach(() => { config.readModels['SomeReadModel'] = { before: [], } as any }) afterEach(() => { delete config.readModels['SomeReadModel'] }) it('validates and uses the searcher to find a read model by id', async () => { const fakeValidateByIdRequest = fake() replace(readModelReader as any, 'validateByIdRequest', fakeValidateByIdRequest) const fakeSearcher = { findById: fake() } replace(Booster, 'readModel', fake.returns(fakeSearcher)) const currentUser = { id: 'a user', } as any const sequenceKey = { name: 'salmon', value: 'sammy', } const readModelRequestEnvelope = { key: { id: '42', sequenceKey, }, class: { name: 'SomeReadModel' }, className: 'SomeReadModel', currentUser, version: 1, requestID: 'my request!', } as any await readModelReader.findById(readModelRequestEnvelope) expect(fakeValidateByIdRequest).to.have.been.calledOnceWith(readModelRequestEnvelope) expect(fakeSearcher.findById).to.have.been.calledOnceWith('42') }) }) }) describe('the validation for methods `search` and `subscribe`', () => { beforeEach(() => { config.readModels[TestReadModel.name] = { class: TestReadModel, authorizedRoles: [UserRole], properties: [], before: [], } }) afterEach(() => { delete config.readModels[TestReadModel.name] }) it('throws the right error when request is missing "version"', async () => { const envelope = { class: { name: 'anyReadModel' }, requestID: random.uuid(), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any // To avoid the compilation failure of "missing version field" await expect(readModelReader.search(envelope)).to.eventually.be.rejectedWith(InvalidParameterError) await expect( readModelReader.subscribe(envelope.requestID, envelope, noopGraphQLOperation) ).to.eventually.be.rejectedWith(InvalidParameterError) }) it('throws the right error when the read model does not exist', async () => { const envelope: ReadModelRequestEnvelope<any> = { class: { name: 'nonExistentReadModel' }, filters: {}, requestID: random.uuid(), version: 1, } as any await expect(readModelReader.search(envelope)).to.eventually.be.rejectedWith(NotFoundError) await expect( readModelReader.subscribe(envelope.requestID.toString(), envelope, noopGraphQLOperation) ).to.eventually.be.rejectedWith(NotFoundError) }) it('throws the right error when the user is not authorized', async () => { const envelope: ReadModelRequestEnvelope<TestReadModel> = { class: TestReadModel, className: TestReadModel.name, requestID: random.uuid(), filters: {}, version: 1, currentUser: { username: internet.email(), role: '', claims: {}, }, } await expect(readModelReader.search(envelope)).to.eventually.be.rejectedWith(NotAuthorizedError) await expect( readModelReader.subscribe(envelope.requestID.toString(), envelope, noopGraphQLOperation) ).to.eventually.be.rejectedWith(NotAuthorizedError) }) }) context("The logic of 'search' and 'subscribe' methods", () => { const filters = { id: { operation: 'eq', values: [random.alphaNumeric(5)], }, field: { operation: 'lt', values: [random.number(10)], }, } const currentUser = { username: internet.email(), role: UserRole.name, claims: {}, } const envelope: ReadModelRequestEnvelope<TestReadModel> = { class: TestReadModel, className: TestReadModel.name, requestID: random.uuid(), version: 1, filters, currentUser, } as any const beforeFn = (request: ReadModelRequestEnvelope<any>): ReadModelRequestEnvelope<any> => { return { ...request, filters: { id: { eq: request.filters.id } } } } const beforeFnV2 = (request: ReadModelRequestEnvelope<any>): ReadModelRequestEnvelope<any> => { return { ...request, filters: { id: { eq: request.currentUser?.username } } } } describe('the "search" method', () => { beforeEach(() => { config.readModels[TestReadModel.name] = { class: TestReadModel, authorizedRoles: [UserRole], properties: [], before: [], } }) afterEach(() => { delete config.readModels[TestReadModel.name] }) it('calls the provider search function and returns its results', async () => { const expectedReadModels = [new TestReadModel(), new TestReadModel()] const providerSearcherFunctionFake = fake.returns(expectedReadModels) replace(config.provider.readModels, 'search', providerSearcherFunctionFake) replace(Booster, 'config', config) // Needed because the function `Booster.readModel` references `this.config` from `searchFunction` const result = await readModelReader.search(envelope) expect(providerSearcherFunctionFake).to.have.been.calledOnceWithExactly( match.any, match.any, TestReadModel.name, filters, undefined, undefined, false ) expect(result).to.be.deep.equal(expectedReadModels) }) context('when there is only one before hook function', () => { const beforeFnSpy = spy(beforeFn) beforeEach(() => { const providerSearcherFunctionFake = fake.returns([]) config.readModels[TestReadModel.name] = { class: TestReadModel, authorizedRoles: [UserRole], properties: [], before: [beforeFnSpy], } replace(Booster, 'config', config) // Needed because the function `Booster.readModel` references `this.config` from `searchFunction` replace(config.provider.readModels, 'search', providerSearcherFunctionFake) }) afterEach(() => { delete config.readModels[TestReadModel.name] }) it('calls the before hook function', async () => { await readModelReader.search(envelope) expect(beforeFnSpy).to.have.been.calledOnceWithExactly(envelope) expect(beforeFnSpy).to.have.returned({ ...envelope, filters: { id: { eq: envelope.filters.id } } }) }) }) context('when there are more than one before hook functions', () => { const beforeFnSpy = spy(beforeFn) const beforeFnV2Spy = spy(beforeFnV2) beforeEach(() => { const providerSearcherFunctionFake = fake.returns([]) config.readModels[TestReadModel.name] = { class: TestReadModel, authorizedRoles: [UserRole], properties: [], before: [beforeFnSpy, beforeFnV2Spy], } replace(Booster, 'config', config) // Needed because the function `Booster.readModel` references `this.config` from `searchFunction` replace(config.provider.readModels, 'search', providerSearcherFunctionFake) }) afterEach(() => { delete config.readModels[TestReadModel.name] }) it('chains the before hook functions when there is more than one', async () => { await readModelReader.search(envelope) expect(beforeFnSpy).to.have.been.calledOnceWithExactly(envelope) expect(beforeFnSpy).to.have.returned({ ...envelope, filters: { id: { eq: envelope.filters.id } } }) const returnedEnvelope = beforeFnSpy.returnValues[0] expect(beforeFnV2Spy).to.have.been.calledAfter(beforeFnSpy) expect(beforeFnV2Spy).to.have.been.calledOnceWithExactly(returnedEnvelope) expect(beforeFnV2Spy).to.have.returned({ ...returnedEnvelope, filters: { id: { eq: returnedEnvelope.currentUser?.username } }, }) }) }) }) describe('the "subscribe" method', () => { context('with no before hooks defined', () => { const providerSubscribeFunctionFake = fake() beforeEach(() => { config.readModels[TestReadModel.name] = { class: TestReadModel, authorizedRoles: [UserRole], properties: [], before: [], } replace(config.provider.readModels, 'subscribe', providerSubscribeFunctionFake) }) it('calls the provider subscribe function and returns its results', async () => { const connectionID = random.uuid() const expectedSubscriptionEnvelope: SubscriptionEnvelope = { ...envelope, connectionID, operation: noopGraphQLOperation, expirationTime: 1, } await readModelReader.subscribe(connectionID, envelope, noopGraphQLOperation) expect(providerSubscribeFunctionFake).to.have.been.calledOnce const gotSubscriptionEnvelope = providerSubscribeFunctionFake.getCall(0).lastArg expect(gotSubscriptionEnvelope).to.include.keys('expirationTime') gotSubscriptionEnvelope.expirationTime = expectedSubscriptionEnvelope.expirationTime // We don't care now about the value expect(gotSubscriptionEnvelope).to.be.deep.equal(expectedSubscriptionEnvelope) }) }) context('with before hooks', () => { const providerSubscribeFunctionFake = fake() beforeEach(() => { config.readModels[TestReadModel.name] = { class: TestReadModel, authorizedRoles: [UserRole], properties: [], before: [beforeFn, beforeFnV2], } replace(config.provider.readModels, 'subscribe', providerSubscribeFunctionFake) }) it('calls the provider subscribe function when setting before hooks and returns the new filter in the result', async () => { const connectionID = random.uuid() envelope.filters = { id: { eq: currentUser?.username } } as Record<string, FilterFor<unknown>> const expectedSubscriptionEnvelope: SubscriptionEnvelope = { ...envelope, connectionID, operation: noopGraphQLOperation, expirationTime: 1, } await readModelReader.subscribe(connectionID, envelope, noopGraphQLOperation) expect(providerSubscribeFunctionFake).to.have.been.calledOnce const gotSubscriptionEnvelope = providerSubscribeFunctionFake.getCall(0).lastArg expect(gotSubscriptionEnvelope).to.include.keys('expirationTime') gotSubscriptionEnvelope.expirationTime = expectedSubscriptionEnvelope.expirationTime // We don't care now about the value expect(gotSubscriptionEnvelope).to.be.deep.equal(expectedSubscriptionEnvelope) }) }) }) }) describe("The 'unsubscribe' method", () => { it('calls the provider "deleteSubscription" method with the right data', async () => { const deleteSubscriptionFake = fake() replace(config.provider.readModels, 'deleteSubscription', deleteSubscriptionFake) const connectionID = random.uuid() const subscriptionID = random.uuid() await readModelReader.unsubscribe(connectionID, subscriptionID) expect(deleteSubscriptionFake).to.have.been.calledOnceWithExactly( match.any, match.any, connectionID, subscriptionID ) }) }) describe("The 'unsubscribeAll' method", () => { it('calls the provider "deleteAllSubscription" method with the right data', async () => { const deleteAllSubscriptionsFake = fake() replace(config.provider.readModels, 'deleteAllSubscriptions', deleteAllSubscriptionsFake) const connectionID = random.uuid() await readModelReader.unsubscribeAll(connectionID) expect(deleteAllSubscriptionsFake).to.have.been.calledOnceWithExactly(match.any, match.any, connectionID) }) }) })
the_stack
import childProcess from 'child_process'; import fs from 'fs'; import path from 'path'; import { promisify } from 'util'; import {type Readable} from "stream"; const execFile = promisify(childProcess.execFile); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); const cliFilePath = path.join(__dirname, '../dist/cli.js'); const fixturesPath = path.join(__dirname, './fixtures'); const yarnLockFilePath = path.join(fixturesPath, 'yarn.lock'); const testWithFlags = async (flags:string[]) => { const { stdout, stderr } = await execFile(process.execPath, [ cliFilePath, '--print', ...flags, '--', yarnLockFilePath, ]); expect(stderr).toBe(''); return stdout; }; const streamToString = (stream:Readable) => { const chunks:Uint8Array[] = []; return new Promise((resolve, reject) => { stream.on('data', (chunk:Uint8Array[]) => chunks.push(Buffer.from(chunk))); stream.on('error', (err) => reject(err)); stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); }); }; describe('Basic output', () => { test('prints duplicates', async () => { const { stdout, stderr } = await execFile(process.execPath, [ cliFilePath, '--list', yarnLockFilePath, ]); expect(stdout).toContain( 'Package "@scope/lib" wants >=1.0.0 and could get 4.17.15, but got 1.3.1' ); expect(stdout).toContain( 'Package "@another-scope/lib" wants >=1.0.0 and could get 4.17.15, but got 1.3.1' ); expect(stdout).toContain( 'Package "lodash" wants >=1.0.0 and could get 4.17.15, but got 1.3.1' ); expect(stderr).toBe(''); }); test('prints fixed yarn.lock', async () => { const { stdout, stderr } = await execFile(process.execPath, [ cliFilePath, '--print', yarnLockFilePath, ]); expect(stdout).not.toContain('"@scope/lib@>=1.0.0":'); expect(stdout).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(stdout).not.toContain('lodash@>=1.0.0:'); expect(stdout).toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(stderr).toBe(''); }); }); describe('Edit in place', () => { test('edits yarn.lock and replaces its content with the fixed version', async () => { const oldFileContent = await readFile(yarnLockFilePath, 'utf8'); try { const { stdout, stderr } = await execFile(process.execPath, [ cliFilePath, yarnLockFilePath, ]); const newFileContent = await readFile(yarnLockFilePath, 'utf8'); expect(oldFileContent).not.toBe(newFileContent); expect(oldFileContent).toContain('"@scope/lib@>=1.0.0":'); expect(oldFileContent).not.toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(oldFileContent).toContain('lodash@>=1.0.0:'); expect(oldFileContent).not.toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(newFileContent).not.toContain('"@scope/lib@>=1.0.0":'); expect(newFileContent).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(newFileContent).not.toContain('lodash@>=1.0.0:'); expect(newFileContent).toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(stdout).toBe(''); expect(stderr).toBe(''); } finally { await writeFile(yarnLockFilePath, oldFileContent, 'utf8'); } }); test('edits yarn.lock and replaces its content with the fixed version without specifying yarn.lock path', async () => { const oldFileContent = await readFile(yarnLockFilePath, 'utf8'); try { const { stdout, stderr } = await execFile(process.execPath, [cliFilePath], { cwd: fixturesPath, }); const newFileContent = await readFile(yarnLockFilePath, 'utf8'); expect(oldFileContent).not.toBe(newFileContent); expect(oldFileContent).toContain('"@scope/lib@>=1.0.0":'); expect(oldFileContent).not.toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(oldFileContent).toContain('lodash@>=1.0.0:'); expect(oldFileContent).not.toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(newFileContent).not.toContain('"@scope/lib@>=1.0.0":'); expect(newFileContent).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(newFileContent).not.toContain('lodash@>=1.0.0:'); expect(newFileContent).toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(stdout).toBe(''); expect(stderr).toBe(''); } finally { await writeFile(yarnLockFilePath, oldFileContent, 'utf8'); } }); }); describe('Error control', () => { test('fails if given the fail option', async () => { const listProc = await childProcess.spawn(process.execPath, [ cliFilePath, '--list', '--fail', yarnLockFilePath, ]); listProc.on('close', (code) => { expect(code).toBe(1); }); const listOut = await streamToString(listProc.stderr); expect(listOut).toContain( 'Found duplicated entries. Run yarn-deduplicate to deduplicate them.' ); const execProc = await childProcess.spawn(process.execPath, [ cliFilePath, '--print', '--fail', yarnLockFilePath, ]); execProc.on('close', (code) => { expect(code).toBe(1); }); const execOut = await streamToString(execProc.stderr); expect(execOut).toContain( 'Found duplicated entries. Run yarn-deduplicate to deduplicate them.' ); }); test('does not fail without the fail option', async () => { const listProc = await childProcess.spawn(process.execPath, [ cliFilePath, '--list', yarnLockFilePath, ]); listProc.on('close', (code) => { expect(code).toBe(0); }); const execProc = await childProcess.spawn(process.execPath, [ cliFilePath, '--print', yarnLockFilePath, ]); execProc.on('close', (code) => { expect(code).toBe(0); }); }); }); describe('Supports individal packages', () => { test('it accepts a single package', async () => { const stdout = await testWithFlags(['--packages', 'lodash']); expect(stdout).not.toContain('lodash@>=1.0.0:'); expect(stdout).toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); }); test('it accepts a multiple packages in one flag', async () => { const stdout = await testWithFlags(['--packages', 'lodash', '@scope/lib']); expect(stdout).not.toContain('lodash@>=1.0.0:'); expect(stdout).not.toContain('@scope/lib@>=1.0.0:'); expect(stdout).toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(stdout).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); }); test('it accepts a multiple flags', async () => { const stdout = await testWithFlags(['--packages', 'lodash', '--packages', '@scope/lib']); expect(stdout).not.toContain('lodash@>=1.0.0:'); expect(stdout).not.toContain('@scope/lib@>=1.0.0:'); expect(stdout).toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(stdout).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); }); // eslint-disable-next-line jest/expect-expect test('does not break if package is missing', () => testWithFlags(['--packages', 'foo'])); }); describe('Supports scopes', () => { test('it accepts a single scope', async () => { const stdout = await testWithFlags(['--scopes', '@scope']); expect(stdout).not.toContain('"@scope/lib@>=1.0.0":'); expect(stdout).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); }); test('it accepts a multiple scopes in one flag', async () => { const stdout = await testWithFlags(['--scopes', '@scope', '@another-scope']); expect(stdout).not.toContain('"@scope/lib@>=1.0.0":'); expect(stdout).not.toContain('"@another-scope/lib@>=1.0.0":'); expect(stdout).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(stdout).toContain('"@another-scope/lib@>=1.0.0", "@another-scope/lib@>=2.0.0":'); }); test('it accepts a multiple flags', async () => { const stdout = await testWithFlags(['--scopes', '@scope', '--scopes', '@another-scope']); expect(stdout).not.toContain('"@scope/lib@>=1.0.0":'); expect(stdout).not.toContain('"@another-scope/lib@>=1.0.0":'); expect(stdout).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(stdout).toContain('"@another-scope/lib@>=1.0.0", "@another-scope/lib@>=2.0.0":'); }); // eslint-disable-next-line jest/expect-expect test('does not break if scope is missing', () => testWithFlags(['--scopes', '@foo'])); }); describe('Supports excluding packages', () => { test('it accepts a single package', async () => { const stdout = await testWithFlags(['--exclude', 'lodash']); expect(stdout).toContain('lodash@>=1.0.0:'); expect(stdout).toContain('lodash@>=2.0.0:'); expect(stdout).toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(stdout).not.toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); }); test('it accepts a multiple package in one flag', async () => { const stdout = await testWithFlags(['--exclude', 'lodash', '@scope/lib']); expect(stdout).toContain('lodash@>=1.0.0:'); expect(stdout).toContain('lodash@>=2.0.0:'); expect(stdout).toContain('"@scope/lib@>=1.0.0":'); expect(stdout).toContain('"@scope/lib@>=2.0.0":'); expect(stdout).not.toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(stdout).not.toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); }); test('it accepts a multiple flags', async () => { const stdout = await testWithFlags(['--exclude', 'lodash', '--exclude', '@scope/lib']); expect(stdout).toContain('lodash@>=1.0.0:'); expect(stdout).toContain('lodash@>=2.0.0:'); expect(stdout).toContain('"@scope/lib@>=1.0.0":'); expect(stdout).toContain('"@scope/lib@>=2.0.0":'); expect(stdout).not.toContain('lodash@>=1.0.0, lodash@>=2.0.0:'); expect(stdout).not.toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); }); // eslint-disable-next-line jest/expect-expect test('does not break if scope is missing', () => testWithFlags(['--exclude', '@foo'])); }); describe('Supports excluding scopes', () => { test('it accepts a single scope', async () => { const stdout = await testWithFlags(['--exclude-scopes', '@scope']); expect(stdout).toContain('"@scope/lib@>=1.0.0":'); expect(stdout).not.toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); }); test('it accepts a multiple scopes in one flag', async () => { const stdout = await testWithFlags(['--exclude-scopes', '@scope', '@another-scope']); expect(stdout).toContain('"@scope/lib@>=1.0.0":'); expect(stdout).toContain('"@another-scope/lib@>=1.0.0":'); expect(stdout).not.toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(stdout).not.toContain('"@another-scope/lib@>=1.0.0", "@another-scope/lib@>=2.0.0":'); }); test('it accepts a multiple flags', async () => { const stdout = await testWithFlags([ '--exclude-scopes', '@scope', '--exclude-scopes', '@another-scope', ]); expect(stdout).toContain('"@scope/lib@>=1.0.0":'); expect(stdout).toContain('"@another-scope/lib@>=1.0.0":'); expect(stdout).not.toContain('"@scope/lib@>=1.0.0", "@scope/lib@>=2.0.0":'); expect(stdout).not.toContain('"@another-scope/lib@>=1.0.0", "@another-scope/lib@>=2.0.0":'); }); // eslint-disable-next-line jest/expect-expect test('does not break if scope is missing', () => testWithFlags(['--scopes', '@foo'])); }); test('line endings are retained', async () => { const oldFileContent = await readFile(yarnLockFilePath, 'utf8'); try { const { stdout, stderr } = await execFile(process.execPath, [ cliFilePath, yarnLockFilePath, ]); const newFileContent = await readFile(yarnLockFilePath, 'utf8'); const oldEol = (oldFileContent.match(/(\r?\n)/) as RegExpMatchArray) [0]; const newEol = (newFileContent.match(/(\r?\n)/) as RegExpMatchArray) [0]; expect(newEol).toBe(oldEol); } finally { await writeFile(yarnLockFilePath, oldFileContent, 'utf8'); } }); test('uses fewer strategy', async () => { const { stdout, stderr } = await execFile(process.execPath, [ cliFilePath, '--print', '-s', 'fewer', yarnLockFilePath, ]); expect(stdout).not.toContain('library@>=1.0.0:'); expect(stdout).toContain('library@>=1.0.0, library@>=1.1.0, library@^2.0.0:'); expect(stdout).toContain('resolved "https://example.net/library@^2.1.0"'); expect(stderr).toBe(''); }); test('uses includePrerelease option', async () => { const { stdout, stderr } = await execFile(process.execPath, [ cliFilePath, '--print', '--includePrerelease', yarnLockFilePath, ]); expect(stdout).not.toContain('typescript@^4.0.3:'); expect(stdout).toContain('typescript@^4.0.3, typescript@^4.1.0-beta:'); expect(stdout).toContain( 'resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.1.0-beta.tgz#e4d054035d253b7a37bdc077dd71706508573e69"' ); expect(stderr).toBe(''); });
the_stack
const fs = require('fs'); class logger { /** * @property * @private * @readonly * @description folder path */ private readonly path = "./logs/"; private readonly filetimestamp : Logger.FileTimestamp; /** * @property * @private * @readonly * @description path of log file for current bot process. */ private readonly full_path : string; /** * @property * @private * @static * @description the only instance of logger class */ private static instance : logger; private bot_settings : {settings: Map<string, boolean | number>, notification_time: Logger.LoggingTimestamp}; private wallet_config : {configuration: Map<string, string>, notification_time: Logger.LoggingTimestamp}; private target_address : {target_address: string, notification_time: Logger.LoggingTimestamp}; private target_time : {target_time: number, notification_time: Logger.LoggingTimestamp}; /** * @method * @private * @readonly * @name update() * @param {{error: Error, caught: boolean, timestamp: Logger.LoggingTimestamp}} error error to log - if any * @param {boolean} exiting true if program is exiting, false otherwise. * @description updates and handles log file. */ private readonly update = (function () { var isBotSettingsDisplayed : boolean = false; var isWalletConfigDisplayed : boolean = false; var isTargetAddressDisplayed : boolean = false; var isTargetTimeDisplayed : boolean = false; /** * @description flagged to true in case of uncaught rejections/exceptions, sigint and process.exit([not 0]) */ var fatalError : boolean = false; return function (error? : {error: Error, caught: boolean, timestamp: Logger.LoggingTimestamp}, exiting? : boolean) { fs.appendFileSync(this.full_path, "\n"); if (exiting) { if (fatalError) { fs.appendFileSync(this.full_path, "\n\nEnd of Log (Terminated with fatal error)."); this.clearSensibleData(); } else { if (process.env.npm_package_debug) { fs.appendFileSync(this.full_path, "\n\nEnd of Log (Terminated with NO fatal error - log generated because of debug mode on)."); this.clearSensibleData(); } else { try { fs.unlinkSync(this.full_path); } catch (error : any) { console.error(error); }; } } return; } if (error) { if (error.caught) { fs.appendFileSync(this.full_path, error.timestamp + "\t" + "===CAUGHT error==="); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, error.error.name); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, error.error.message); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, error.error.stack ? error.error.stack : "stack not available."); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, "===================END OF ERROR==="); } else { fs.appendFileSync(this.full_path, error.timestamp + "\t" + "===UNCAUGHT error==="); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, error.error.name); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, error.error.message); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, error.error.stack ? error.error.stack : "stack not available."); fs.appendFileSync(this.full_path, "\n"); fs.appendFileSync(this.full_path, "===================END OF ERROR====="); fatalError = true; logger.getInstance().update(null, true); } return; } if (!isBotSettingsDisplayed) { if (this.bot_settings) { fs.appendFileSync(this.full_path, this.bot_settings.notification_time + "\t" + "Bot started with following setting: \n"); fs.appendFileSync(this.full_path, "Mode: " + (this.bot_settings.settings.get('fairlaunch') ? 'fairlaunch' : 'presale') + "\n"); fs.appendFileSync(this.full_path, "Delay: " + (this.bot_settings.settings.get('delay') ? 'on (' + this.bot_settings.settings.get('delay') + ' '+ 'blocks' + ')' : 'off') + "\n"); fs.appendFileSync(this.full_path, "Mode: " + (this.bot_settings.settings.get('testnet') ? 'testnet' : 'mainnet') + "\n"); isBotSettingsDisplayed = true; } else throw new Error("No bot settings data (and further) available."); } else if (!isWalletConfigDisplayed) { if (this.wallet_config) { fs.appendFileSync(this.full_path, this.wallet_config.notification_time + "\t" + "Wallet configuration is the following: \n"); fs.appendFileSync(this.full_path, "Private key: " + "[CENSORED]\n"); fs.appendFileSync(this.full_path, "Gas amount: " + this.wallet_config.configuration.get('gas_amount') + "\n"); fs.appendFileSync(this.full_path, "Gas price: " + this.wallet_config.configuration.get('gas_price') + "\n"); fs.appendFileSync(this.full_path, "Amount: " + this.wallet_config.configuration.get('amount') + "\n"); isWalletConfigDisplayed = true; } else throw new Error("No wallet settings data (and further) available."); } else if (!isTargetAddressDisplayed) { if (this.target_address) { fs.appendFileSync(this.full_path, this.target_address.notification_time + "\t" + "Target address: " + this.target_address.target_address); isTargetAddressDisplayed = true; } else throw new Error("No target address (and further) available."); } else if (!isTargetTimeDisplayed){ if (this.target_time) { fs.appendFileSync(this.full_path, this.target_time.notification_time + "\t" + "Target time: " + this.target_time.target_time); isTargetTimeDisplayed = true } else throw new Error("No target address (and further) available."); } } })(); /** * @method clearSensibleData() removes sensible data that may have been logged. * @private */ private clearSensibleData() { if (this.wallet_config && this.wallet_config.configuration.has('private_key')) { let private_key_regex : RegExp = new RegExp(`${this.bot_settings.settings.get('private_key')}`, 'g'); let log : string = fs.readFileSync(this.full_path, 'utf8'); fs.writeFileSync(this.full_path, log.replace(private_key_regex, "[PRIVATE KEY CENSORED]")); } } /** * Returns Logger instance and subscribes to exit/stop events to finalize logging before app closes * @constructor * @private */ private constructor() { this.filetimestamp = Logger.FileTimestamp.getTimestamp(); this.full_path = this.path + this.filetimestamp.toString() + ".txt"; fs.appendFileSync(this.full_path, `===LOG FILE CREATED AT TIMESTAMP ${this.filetimestamp}===\n\n`); /** * @function exitHandler() * @param {number} exitCode exit code. * @description handles calls of process.exit(). */ function exitHandler(exitCode: number) { //code -10: used internally to flag process.exit() called by others event handlers. if (exitCode == -10) process.exit(); //code 10: flags process.exit() called by bot itself during execution. else if (exitCode == 10) { this.update({ error: new Error("exit(10) has been called. Program forcibly closed by itself."), caught: false, timestamp: Logger.LoggingTimestamp.getTimestamp() }, false); } //no errors else if (exitCode == 0){ this.update(null, true); } //other codes (external entities called process.exit()) else { this.update({ error: new Error(`exit(${exitCode}) has been called. Program forcibly closed by external entity.`), caught: false, timestamp: Logger.LoggingTimestamp.getTimestamp() }, false); } process.exit(); } /** * @function sigHandler() * @param {any} sig type of SIG that has been invoked (e.g. SIGINT). * @description handles SIG events. */ function sigHandler(sig : any) { this.update({ error: new Error(`Sig (${sig.toString()}) has been called. Program forcibly closed by external entity.`), caught: false, timestamp: Logger.LoggingTimestamp.getTimestamp() }, false); process.exit(-10); } /** * @function uncaughtHandler() * @param {Error} error unhandled error * @description handles events "uncaughtException" and "unCaightRejection" */ function uncaughtHandler(error : Error) { this.update({ error: error, caught: false, timestamp: Logger.LoggingTimestamp.getTimestamp() }, false); console.error(error); process.exit(-10); } process.on('exit', exitHandler.bind(this)) .on('beforeExit', exitHandler.bind(this)) .on('SIGINT', sigHandler.bind(this)) .on('SIGUSR1', sigHandler.bind(this)) .on('SIGUSR2', sigHandler.bind(this)) .on('uncaughtException', uncaughtHandler.bind(this)) .on('unhandledRejection', uncaughtHandler.bind(this)); } /** * @method getInstance() returns the only instance of Logger (singleton) * @returns {Logger} returns Logger.instance */ public static getInstance() : logger { if (logger.instance) return logger.instance; logger.instance = new logger(); return logger.instance; } /** * @method updateBotConfig() * @public */ public updateBotConfig(bot_settings : Map<string, boolean | number>) { this.bot_settings = { settings: bot_settings, notification_time: Logger.LoggingTimestamp.getTimestamp() }; this.update(null, false); } /** * @method updateWalletConfig() * @public */ public updateWalletConfig(wallet_config : Map<string, string>) { wallet_config.set('private_key', "CENSORED"); this.wallet_config = { configuration: wallet_config, notification_time: Logger.LoggingTimestamp.getTimestamp() }; this.update(null, false); } /** * @method updateAddress() * @public */ public updateAddress(address: string) { this.target_address = { target_address: address, notification_time: Logger.LoggingTimestamp.getTimestamp() } this.update(null, false); } /** * @method updateTime() * @public */ public updateTime(time: number) { this.target_time = { target_time: time, notification_time: Logger.LoggingTimestamp.getTimestamp() } this.update(null, false); } /** * @method notifyHandledException() * @public * @description notifies the logger for handled exceptions. * @param {Error} error error to notify. */ public notifyHandledException(error : Error) { this.update({ error: error, caught: true, timestamp: Logger.LoggingTimestamp.getTimestamp() }, false); } } namespace Logger { /** * @exports * @class * @name LoggingTimestamp * @extends Object * @description This class is used to define formatting of logs' timestamps. */ export class LoggingTimestamp extends Object { /** * @private * @readonly * @property * @description will be a string of the format [hh:mm:ss:millis] */ private readonly timestamp : string; /** * Private constructor of LoggingTimestamp class. * @constructor * @private * @param {string} timestamp the timestamp string returned by LoggingTimestamp.getTimestamp() */ private constructor(timestamp : string) { super(); this.timestamp = timestamp; } /** * @method getTimestamp() * @returns {LoggingTimestamp} correct instance of LoggingTimestamp to use for logging. */ public static getTimestamp() : LoggingTimestamp { let now : Date = new Date(); //Leading zeroes have to be manually inserted. return new LoggingTimestamp(`[${now.getHours() < 10 ? "0" + now.getHours().toString() : now.getHours()}:`+ `${now.getMinutes() < 10 ? "0" + now.getMinutes().toString() : now.getMinutes()}:`+ `${now.getSeconds() < 10 ? "0" + now.getSeconds().toString() : now.getSeconds()}:`+ `${now.getMilliseconds() < 10 ? "000" + now.getMilliseconds().toString() : now.getMilliseconds() < 100 ? "00" + now.getMilliseconds().toString() : "0" + now.getMilliseconds().toString()}]`); } /** * @method toString() * @override * @returns {string} returns correct string representation of LoggingTimestamp instance (the timestamp property) - if correctly set. */ override toString() : string { if (this.timestamp) return this.timestamp; return "TIMESTAMP NOT SET: you should create the instance only via the static method Logger.LoggingTimestamp.getTimestamp()"; } }; /** * @exports * @class * @name FileTimestamp * @extends Object * @description This class is used to define formatting of log file's timestamp. */ export class FileTimestamp extends Object { /** * @private * @readonly * @property * @description will be a string of the format ddmmyyyy-hhmmss */ private readonly timestamp : string; /** * Private constructor of FileTimestamp class. * @constructor * @private * @param {string} timestamp the timestamp string returned by FileTimestamp.getTimestamp() */ private constructor(timestamp : string) { super(); this.timestamp = timestamp; } /** * @method getTimestamp() * @returns {FileTimestamp} correct instance of FileTimestamp to use for log file's name. */ public static getTimestamp() : FileTimestamp { let now : Date = new Date(); //leading zeroes have to be manually inserted return new FileTimestamp(`${now.getDay() < 10 ? "0" + now.getDay().toString() : now.getDay().toString()}`+ `${now.getMonth() < 10 ? "0" + now.getMonth().toString() : now.getMonth().toString()}`+ `${now.getFullYear()}-`+ `${now.getHours() < 10 ? "0" + now.getHours().toString() : now.getHours().toString()}`+ `${now.getMinutes() < 10 ? "0" + now.getMinutes().toString() : now.getMinutes().toString()}`+ `${now.getSeconds() < 10 ? "0" + now.getSeconds().toString() : now.getSeconds().toString()}`); } /** * @method toString() * @override * @returns {sttring} returns correct string representation of FileTimestamp instance (the timestamp property) - if correctly set. */ override toString() : string { if (this.timestamp) return this.timestamp; return "TIMESTAMP NOT SET: you should create the instance only via the static method Logger.FileTimestamp.getTimestamp()"; } }; } export {Logger, logger}
the_stack
import { forumTypeSetting, siteUrlSetting } from '../../instanceSettings'; import { getOutgoingUrl, getSiteUrl } from '../../vulcan-lib/utils'; import { mongoFindOne } from '../../mongoQueries'; import { userOwns, userCanDo } from '../../vulcan-users/permissions'; import { userGetDisplayName } from '../users/helpers'; import { postStatuses, postStatusLabels } from './constants'; import { cloudinaryCloudNameSetting } from '../../publicSettings'; import Localgroups from '../localgroups/collection'; import moment from '../../moment-timezone'; // EXAMPLE-FORUM Helpers ////////////////// // Link Helpers // ////////////////// // Return a post's link if it has one, else return its post page URL export const postGetLink = function (post: PostsBase|DbPost, isAbsolute=false, isRedirected=true): string { const url = isRedirected ? getOutgoingUrl(post.url) : post.url; return !!post.url ? url : postGetPageUrl(post, isAbsolute); }; // Whether a post's link should open in a new tab or not export const postGetLinkTarget = function (post: PostsBase|DbPost): string { return !!post.url ? '_blank' : ''; }; /////////////////// // Other Helpers // /////////////////// // Get a post author's name export const postGetAuthorName = async function (post: DbPost) { var user = await mongoFindOne("Users", post.userId); if (user) { return userGetDisplayName(user); } else { return post.author; } }; // Get default status for new posts. export const postGetDefaultStatus = function (user: DbUser): number { return postStatuses.STATUS_APPROVED; }; const findWhere = (array: any, criteria: any) => array.find((item: any) => Object.keys(criteria).every((key: any) => item[key] === criteria[key])); // Get status name export const postGetStatusName = function (post: DbPost): string { return findWhere(postStatusLabels, {value: post.status}).label; }; // Check if a post is approved export const postIsApproved = function (post: DbPost): boolean { return post.status === postStatuses.STATUS_APPROVED; }; // Check if a post is pending export const postIsPending = function (post: DbPost): boolean { return post.status === postStatuses.STATUS_PENDING; }; // Get URL for sharing on Twitter. export const postGetTwitterShareUrl = (post: DbPost): string => { return `https://twitter.com/intent/tweet?text=${ encodeURIComponent(post.title) }%20${ encodeURIComponent(postGetLink(post, true)) }`; }; // Get URL for sharing on Facebook. export const postGetFacebookShareUrl = (post: DbPost): string => { return `https://www.facebook.com/sharer/sharer.php?u=${ encodeURIComponent(postGetLink(post, true)) }`; }; // Get URL for sharing by Email. export const postGetEmailShareUrl = (post: DbPost): string => { const subject = `Interesting link: ${post.title}`; const body = `I thought you might find this interesting: ${post.title} ${postGetLink(post, true, false)} (found via ${siteUrlSetting.get()}) `; return `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`; }; // Select the social preview image for the post, using the manually-set // cloudinary image if available, or the auto-set from the post contents. If // neither of those are available, it will return null. export const getSocialPreviewImage = (post: DbPost): string => { const manualId = post.socialPreviewImageId if (manualId) return `https://res.cloudinary.com/${cloudinaryCloudNameSetting.get()}/image/upload/c_fill,ar_1.91,g_auto/${manualId}` const autoUrl = post.socialPreviewImageAutoUrl return autoUrl || '' } // The set of fields required for calling postGetPageUrl. Could be supplied by // either a fragment or a DbPost. export interface PostsMinimumForGetPageUrl { _id: string slug: string isEvent?: boolean groupId?: string|undefined } // Get URL of a post page. export const postGetPageUrl = function(post: PostsMinimumForGetPageUrl, isAbsolute=false, sequenceId:string|null=null): string { const prefix = isAbsolute ? getSiteUrl().slice(0,-1) : ''; // LESSWRONG – included event and group post urls if (sequenceId) { return `${prefix}/s/${sequenceId}/p/${post._id}`; } else if (post.isEvent) { return `${prefix}/events/${post._id}/${post.slug}`; } else if (post.groupId) { return `${prefix}/g/${post.groupId}/p/${post._id}/`; } return `${prefix}/posts/${post._id}/${post.slug}`; }; export const postGetCommentCount = (post: PostsBase|DbPost): number => { if (forumTypeSetting.get() === 'AlignmentForum') { return post.afCommentCount || 0; } else { return post.commentCount || 0; } } export const postGetCommentCountStr = (post: PostsBase|DbPost, commentCount?: number|undefined): string => { // can be passed in a manual comment count, or retrieve the post's cached comment count const count = commentCount != undefined ? commentCount : postGetCommentCount(post) if (!count) { return "No comments" } else if (count == 1) { return "1 comment" } else { return count + " comments" } } export const postGetLastCommentedAt = (post: PostsBase|DbPost): Date => { if (forumTypeSetting.get() === 'AlignmentForum') { return post.afLastCommentedAt; } else { return post.lastCommentedAt; } } export const postGetLastCommentPromotedAt = (post: PostsBase|DbPost):Date|null => { if (forumTypeSetting.get() === 'AlignmentForum') return null // TODO: add an afLastCommentPromotedAt return post.lastCommentPromotedAt; } /** * Whether or not the given user is an organizer for the post's group * @param user * @param post * @returns {Promise} Promise object resolves to true if the post has a group and the user is an organizer for that group */ export const userIsPostGroupOrganizer = async (user: UsersMinimumInfo|DbUser|null, post: PostsBase|DbPost): Promise<boolean> => { const groupId = ('group' in post) ? post.group?._id : post.groupId; if (!user || !groupId) return false const group = await Localgroups.findOne({_id: groupId}); return !!group && group.organizerIds.some(id => id === user._id); } export const postCanEdit = (currentUser: UsersCurrent|null, post: PostsBase): boolean => { const organizerIds = post.group?.organizerIds; const isPostGroupOrganizer = organizerIds ? organizerIds.some(id => id === currentUser?._id) : false; return userOwns(currentUser, post) || userCanDo(currentUser, 'posts.edit.all') || isPostGroupOrganizer; } export const postCanDelete = (currentUser: UsersCurrent|null, post: PostsBase): boolean => { if (userCanDo(currentUser, "posts.remove.all")) { return true } const organizerIds = post.group?.organizerIds; const isPostGroupOrganizer = organizerIds ? organizerIds.some(id => id === currentUser?._id) : false; return (userOwns(currentUser, post) || isPostGroupOrganizer) && post.draft } export const postGetKarma = (post: PostsBase|DbPost): number => { const baseScore = forumTypeSetting.get() === 'AlignmentForum' ? post.afBaseScore : post.baseScore return baseScore || 0 } // User can add/edit the hideCommentKarma setting if: // 1) The user is logged in and has the requisite setting enabled // And // 2) The post does not exist yet // Or if the post does exist // 3) The post doesn't have any comments yet export const postCanEditHideCommentKarma = (user: UsersCurrent|DbUser|null, post?: PostsBase|DbPost|null): boolean => { return !!(user?.showHideKarmaOption && (!post || !postGetCommentCount(post))) } /** * Returns the event datetimes in a user-friendly format, * ex: Mon, Jan 3 at 4:30 - 5:30 PM * * @param {(PostsBase|DbPost)} post - The event to be checked. * @param {string} [timezone] - (Optional) Convert datetimes to this timezone. * @param {string} [dense] - (Optional) Exclude the day of the week. * @returns {string} The formatted event datetimes. */ export const prettyEventDateTimes = (post: PostsBase|DbPost, timezone?: string, dense?: boolean): string => { // when no start time, just show "TBD" if (!post.startTime) return 'TBD' let start = moment(post.startTime) let end = post.endTime && moment(post.endTime) // if we have event times in the local timezone, use those instead const useLocalTimes = post.localStartTime && (!post.endTime || post.localEndTime) // prefer to use the provided timezone let tz = ` ${start.format('[UTC]ZZ')}` if (timezone) { start = start.tz(timezone) end = end && end.tz(timezone) tz = ` ${start.format('z')}` } else if (useLocalTimes) { // see postResolvers.ts for more on how local times work start = moment(post.localStartTime).utc() end = post.localEndTime && moment(post.localEndTime).utc() tz = '' } // hide the year if it's reasonable to assume it const now = moment() const sixMonthsFromNow = moment().add(6, 'months') const startYear = (now.isSame(start, 'year') || start.isBefore(sixMonthsFromNow)) ? '' : `, ${start.format('YYYY')}` const startDate = dense ? start.format('MMM D') : start.format('ddd, MMM D') const startTime = start.format('h:mm').replace(':00', '') let startAmPm = ` ${start.format('A')}` if (!end) { // just a start time // ex: Starts on Mon, Jan 3 at 4:30 PM // ex: Starts on Mon, Jan 3, 2023 at 4:30 PM EST return `${dense ? '' : 'Starts on '}${startDate}${startYear} at ${startTime}${startAmPm}${tz}` } const endTime = end.format('h:mm A').replace(':00', '') // start and end time on the same day // ex: Mon, Jan 3 at 4:30 - 5:30 PM // ex: Mon, Jan 3, 2023 at 4:30 - 5:30 PM EST if (start.isSame(end, 'day')) { // hide the start time am/pm if it's the same as the end time's startAmPm = start.format('A') === end.format('A') ? '' : startAmPm return `${startDate}${startYear} at ${startTime}${startAmPm} - ${endTime}${tz}` } // start and end time on different days // ex: Mon, Jan 3 at 4:30 PM - Tues, Jan 4 at 5:30 PM // ex: Mon, Jan 3, 2023 at 4:30 PM - Tues, Jan 4, 2023 at 5:30 PM EST const endDate = dense ? end.format('MMM D') : end.format('ddd, MMM D') const endYear = (now.isSame(end, 'year') || end.isBefore(sixMonthsFromNow)) ? '' : `, ${end.format('YYYY')}` return `${startDate}${startYear} at ${startTime}${startAmPm} - ${endDate}${endYear} at ${endTime}${tz}` }
the_stack
interface Window { Office: any; } declare var $: any; module VORLON { export class OfficeClient extends ClientPlugin { private objectPrototype = Object.getPrototypeOf({}); constructor() { super("office"); // Name this._ready = true; // No need to wait console.log('Started'); } //Return unique id for your plugin public getID(): string { return "OFFICE"; } public refresh(): void { //override this method with cleanup work that needs to happen //as the user switches between clients on the dashboard //sometimes refresh is called before document was loaded if (!document.body) { setTimeout(() => { this.refresh(); }, 200); return; } var office = window["Office"]; } private STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; private ARGUMENT_NAMES = /([^\s,]+)/g; private getFunctionArgumentNames(func) { var result = []; try { var fnStr = func.toString().replace(this.STRIP_COMMENTS, ''); result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(this.ARGUMENT_NAMES); if (result === null) result = []; } catch (exception) { console.error(exception); } return result; } private inspectOfficeObject(path: Array<string>, obj: any, rootObject: any): Object { var res = { proto: null, fullpath: path.join('.'), name: path[path.length - 1], functions: [], properties: [], contentFetched: true, type: typeof obj, value: undefined }; // Check if can inspect something if (res.type === "function") { return res; } if (obj === null) { res.type = "null"; res.value = null; return res; } if (res.type !== "object") { res.value = obj.toString(); return res; } // get all properties var objProperties = Object.getOwnPropertyNames(obj); // Gets prototype var proto = Object.getPrototypeOf(obj); // Get the prototype. if (proto && proto != this.objectPrototype) res.proto = this.inspectOfficeObject(path, proto, rootObject); // Recurse the properties for (var i = 0, l = objProperties.length; i < l; i++) { var p = objProperties[i]; var propertyType = ""; // if it's a vorlon property, we pass if (p === '__vorlon') continue; // a office internal prop if (p.substr(0, 1) == '$') continue; // Strange to stringify then parse. // whatever... var propPath = JSON.parse(JSON.stringify(path)); propPath.push(p); try { // get the property value var objValue = rootObject[p]; // get the type of this propertyType propertyType = typeof objValue; if (propertyType === 'function') { res.functions.push({ name: p, fullpath: propPath.join('.'), args: this.getFunctionArgumentNames(objValue) }); } else if (propertyType === 'undefined') { res.properties.push({ name: p, type: propertyType, fullpath: propPath.join('.'), value: undefined }); } else if (propertyType === 'null') { res.properties.push({ name: p, type: propertyType, fullpath: propPath.join('.'), value: null }); } else if (propertyType === 'object') { if (objValue === null) { var desc = { name: p, type: "null", fullpath: propPath.join('.'), contentFetched: true }; res.properties.push(desc); } else { if (propPath.indexOf(p.toString()) == -1 || propPath.indexOf(p.toString()) == (propPath.length - 1)) { var r = <any>this.inspectOfficeObject(propPath, objValue, objValue); if (r.properties.length > 0) res.properties.push(r); } } } else { if (objValue !== undefined && objValue !== null) { res.properties.push({ name: p, fullpath: propPath.join('.'), type: propertyType, value: objValue.toString() }); } } } catch (exception) { this.trace('error reading property ' + p + ' of type ' + propertyType); this.trace(exception); res.properties.push({ name: p, type: propertyType, fullpath: propPath.join('.'), val: "oups, Vorlon has an error reading this " + propertyType + " property..." }); } } return res; } // This code will run on the client ////////////////////// // Start the clientside code public startClientSide(): void { //don't actually need to do anything at startup } public query(name: string) { var tokens = ["window", name]; if (window[name] === null || window[name] === undefined) { return this.sendToDashboard( { type: 'empty', name: name, value: undefined }); } var packagedObject = this.inspectOfficeObject(tokens, window[name], window[name]); if (!window.Office || window.Office === undefined || window.Office === null) { return this.sendToDashboard( { type: 'error', name: name, value: "Office not defined" }); } return this.sendToDashboard( { type: 'object', name: name, value: packagedObject }); } public stringify(o: any): any { var cache = []; return JSON.stringify(o, function(key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // Circular reference found, discard key return; } // Store value in our collection cache.push(value); } return value; }); } public getAsyncResult(deferred: any): Object { return (asyncResult) => { if (asyncResult.status == window.Office.AsyncResultStatus.Failed) { return deferred.reject(asyncResult.error); } else { return deferred.resolve(asyncResult.value); } } } public executeFunction(receivedObject: any): any { var deferred = $.Deferred(); try { var result = this.getFunctionOrProperty(receivedObject.name); if (result === null || result === undefined || result.fn === null || result.fn === undefined) { deferred.reject("this function is not allowed in this mode."); } var args = receivedObject.args; if (args === undefined || args === null) args = []; if (typeof args === 'string') args = [args]; var parsedArgs = []; for (var i = 0; i < args.length; i++) { var arg = args[i]; if (typeof arg === 'string') { parsedArgs.push(arg); } else if ($.isPlainObject(arg) && arg.type) { switch (arg.type) { case "Datetime": parsedArgs.push(new Date(Date.parse(arg.value))); break; case "Json": parsedArgs.push(JSON.parse(arg.value)); break; default: parsedArgs.push(arg.value); } } else if ($.isPlainObject(arg)) { parsedArgs.push(arg); } } if (receivedObject.hasAsyncResult) { parsedArgs.push(this.getAsyncResult(deferred)); result.fn.apply(result.obj, parsedArgs); } else { var response = result.fn.apply(result.obj, parsedArgs); deferred.resolve(response); } } catch (error) { deferred.reject(error); } return deferred.promise(); } public getOfficeType(): any { if (!window.Office || !window.Office.context) { return undefined; } if (window.Office.context.mailbox) { return { officeType: "Outlook" }; } if (window.Office.context.requirements && window.Office.context.requirements._setMap && window.Office.context.requirements._setMap._sets) { return { officeType: window.Office.context.requirements._setMap._sets } } return { officeType: "Office" }; } public getFunctionOrProperty(clsClass: string): any { if (clsClass === undefined || clsClass === null || clsClass.trim() === "") return undefined; var clsClassT = clsClass.split("."); if (clsClassT.length === 0) return undefined; if (clsClassT[0] == "window") { clsClassT = clsClassT.slice(1, clsClassT.length); } var finalResult = { obj: undefined, fn: undefined } var obj = window; while (clsClassT.length > 0) { var currentProperty = clsClassT[0]; if (clsClassT.length == 2) { finalResult.obj = obj[currentProperty]; } clsClassT = clsClassT.slice(1, clsClassT.length); obj = obj[currentProperty]; } finalResult.fn = obj; return finalResult; } // Handle messages from the dashboard, on the client public onRealtimeMessageReceivedFromDashboardSide(receivedObject: any): void { switch (receivedObject.type) { case "query": this.query(receivedObject.name); break; case "officetype": var t = this.getOfficeType(); this.sendToDashboard( { type: 'officetype', value: t }); break; case "property": var property = this.getFunctionOrProperty(receivedObject.name); this.sendToDashboard( { type: 'property', name: receivedObject.name, value: property }); break; case "function": this.executeFunction(receivedObject) .then((content) => { var c = this.stringify(content); this.sendToDashboard( { type: 'function', name: receivedObject.name, value: c }); }).fail(error => { var c = this.stringify(error); this.sendToDashboard( { type: 'error', name: receivedObject.name, value: c }); }); break; default: break; } } } //Register the plugin with vorlon core Core.RegisterClientPlugin(new OfficeClient()); }
the_stack
import { accentColor, bodyFontFamily, labelColor, backgroundColor, buttonBackgroundColor } from './styles'; import { ContentElement } from './content'; import { ACCInputEvent } from '../events/input-event'; import { AbstractInputElement } from './abstract-input'; import { PoseInputElement } from './pose-input'; import { html } from '@polymer/lit-element'; import { AbstractModalElement } from './abstract-modal'; import { property } from './decorators'; import './range'; interface StyleMap { [index: string]: string; } const computeStyleResults = (parent: Element | ShadowRoot, map: StyleMap): StyleMap => { const result: StyleMap = {}; //compute our accent color by applying it to a temp element const _tmpEl = document.createElement('div'); _tmpEl.style.display = 'none'; Object.assign(_tmpEl.style, map); parent.appendChild(_tmpEl); const computedStyle = window.getComputedStyle(_tmpEl); for (let key in map) { result[key] = (computedStyle as any)[key]; } _tmpEl.parentElement && _tmpEl.parentElement.removeChild(_tmpEl); return result; }; const options = (parts:string[], selectedPart:string)=> parts.map((part, i)=> html`<acc-item value="${part}" selected?=${part === selectedPart} label=${part}></option>` ) const hasHost = (v: any):v is { host: HTMLElement } => v && typeof v.host !== 'undefined'; class PoseInputCalibrationElement extends AbstractModalElement { @property({ type: Number }) public amplification:number = 1; @property({ type: Number }) public smoothing:number = 0; @property({ type: String }) public part:string; @property({ type: Array }) public parts:string[] = []; @property({ type: Number }) public imageScaleFactor:number = 0.5; @property({ type: String }) public inputSelector: string = 'acc-pose-input'; private __content: ContentElement; private __ctx: CanvasRenderingContext2D; //we will retrieve this using window.getComputedStyle(element) private __accentColor: string = 'white'; private __centerColor: string = 'white'; public inputElement: AbstractInputElement; constructor() { super(); this._onTick = this._onTick.bind(this); } focusHeader() { const header = this.shadowRoot.querySelector('#header') as HTMLElement; if (header) { header.focus(); } } _onTick(event: ACCInputEvent) { if (!this.__ctx || !this.__content) { return; } const { __ctx } = this; const input = (event.target as PoseInputElement); __ctx.canvas.width = this.__content.clientWidth; __ctx.canvas.height = this.__content.clientHeight; //__ctx.clearRect(0, 0, __ctx.canvas.width, __ctx.canvas.height); __ctx.lineWidth = 1; input.renderInputData(__ctx); input.renderCenter(__ctx, this.__centerColor); input.renderCursor(__ctx, this.__accentColor); } _propertiesChanged(props: any, changed: any, prev: any) { if(changed && typeof changed.open === 'boolean') { // let inputElement: PoseInputElement; // if (hasHost(this.parentNode)) { // inputElement = this.parentNode.host as PoseInputElement; // } if (changed.open && this.inputElement) { // the pose input element this.inputElement.addEventListener('tick', this._onTick); } else if(this.inputElement) { this.inputElement.removeEventListener('tick', this._onTick); } } return super._propertiesChanged(props, changed, prev); } _firstRendered() { setTimeout(() => { //compute our accent color by applying it to a temp element const { backgroundColor, color } = computeStyleResults(this.shadowRoot, { backgroundColor: accentColor, color: labelColor }); this.__accentColor = backgroundColor; this.__centerColor = color; this.inputElement = document.querySelector(this.inputSelector); if(this.inputElement && this.open){ this.inputElement.addEventListener('tick', this._onTick); } }, 16); super._firstRendered(); } _didRender(props: any, changed: any, prev: any) { const content = this.shadowRoot!.querySelector('acc-content') as ContentElement; if (content && hasHost(this.parentNode)) { this.__content = content; content.inputElement = this.parentNode.host as PoseInputElement; } const canvas = this.shadowRoot!.querySelector('#input-visualization')! as HTMLCanvasElement; if(changed && changed.amplification) { const range = this.shadowRoot.querySelector('acc-range') as HTMLElement; if(range) { range.focus(); } } if(!canvas) { return; } this.__ctx = canvas.getContext('2d'); return super._didRender(props, changed, prev); } _renderModalBody(props:any){ const self:PoseInputCalibrationElement = this; const dispatch = (eventType: string= 'change', composed: boolean = false) =>{ self.dispatchEvent(new CustomEvent(eventType, { detail: { target: self, part: self.part, amplification: self.amplification, imageScaleFactor: self.imageScaleFactor, smoothing: self.smoothing }, composed, bubbles: composed } )); } function onSelectInput(e:CustomEvent){ //const selectedPart = self.parts[this.selectedIndex]; const selectedPart = e.detail.value; //'this' scope is the select box if(this.id === 'part'){ self.part = selectedPart; } console.log('self.part: ' + self.part); dispatch(); //dispatch('center'); } function onScaleInput(e:Event){ self.imageScaleFactor = Number(this.value); dispatch(); } function onSmoothing(e:Event) { self.smoothing = Number(this.value); dispatch(); } function onAmplification(e:Event) { self.amplification = parseFloat(this.value); dispatch(); const ampEl = self.shadowRoot.querySelector('.amp-value') as HTMLElement; if(ampEl) { ampEl.innerHTML = `${self.amplification.toFixed(1)}x`; } } return html` <style> @media ( max-height: 640px ) { acc-content { width: 320px; height: 240px; } } @media ( min-height: 641px ) and ( max-height: 760px ) { acc-content { width: 480px; height: 360px; } #modal-body { } } @media( min-height: 760px ) { acc-content { width: 640px; height: 480px; } } :host { font-family: ${bodyFontFamily}; } .container { background-color: ${backgroundColor}; text-align: center; } acc-content { background-color: white; margin: 20px auto; } h2 { font-family: ${bodyFontFamily}; color: ${labelColor}; display: inline-block; } h4 { display: inline-block; } :host() * { } :host([debug]) .controls-row, :host([debug]) .controls-row-item, *[debug] .controls-row, *[debug] .controls-row-item { border: 1px solid red; } .inner-container { position: relative; top: 50%; width: auto; transform: translate(0, -50%); } .controls-row { display: flex; flex-direction: row; flex-wrap: wrap; max-width: 960px; margin: 0 auto; padding: 8px; } .box { box-sizing: border-box; border: 1px solid black; } .controls-row-item { align-self: baseline; display: inline-flex; order: 1; flex-basis: auto; flex-grow: 1; flex-shrink: 1; text-align: center; } a.reset-centerpoint { font-family: ${bodyFontFamily}; color: ${accentColor}; text-decoration: none; font-weight: 700; } .amp-value { color: ${labelColor}; padding-left: 8px; min-width: 24px; } .done { --background-color: ${accentColor}: --accent-color: ${backgroundColor}; width: 100px; } *[inline] .centerpoint-buttons { display: flex; flex-direction: row; flex-shrink: 1; flex-basis: auto; } .centerpoint-button { padding: 0 8px; display: inline-block; width: auto; --button-label-color: ${accentColor}; --button-border-width: 0; font-weight: bold; font-size: 14px; } label { font-weight: bold; } .help-container { cursor: pointer; position: absolute; top: 16px; right: 16px; font-size: 18px; color: ${accentColor}; font-weight: bold; width: 80px; text-align: right; background: transparent; border: 0; } .help-container svg { position: absolute; top: 0; left: 0; } .help-container span { position: relative; top: 50%; transform: translate(0, -50%); } #help-question-mark { fill: ${accentColor}; } .control-pairing { display: inline-flex; flex-direction: row; align-items: baseline; margin: auto; } .control-pairing label { flex-direction: row; flex-basis: auto; } .centerpoint-buttons { flex-direction: row; flex-basis: auto; } .centerpoint-divider { align-items: baseline; } #part { margin: auto; } .close { margin: 40px auto; --button-background-color: ${accentColor}; --button-label-color: ${backgroundColor}; --button-border-color: ${accentColor}; text-align: right; width: 150px; } </style> <div class="inner-container"> <h2 id="header" tabindex="0">Body Tracking Settings</h2> <acc-content id="content-container" grayscale webcamopacity="0.5" disabled?=${!props.open}> <canvas id="input-visualization" width="640" height="480"> Visualization of body tracking data. </canvas> </acc-content> <div class="controls-row"> <div class="controls-row-item"> <acc-select label="Body Part:" id="part" on-change=${onSelectInput} inline> ${options(this.parts, this.part)} </acc-select> </div> <div class="controls-row-item"> <div class="control-pairing"> <acc-range min="1" max="6" step="0.1" label="Amplification:" value="${this.amplification}" on-input="${onAmplification}" inline></acc-range> <span class="amp-value">${this.amplification.toFixed(1)}x</span> </div> </div> <div class="controls-row-item"> <div class="control-pairing"> <label style="font-size: 18px;">Centerpoint:</label> <span class="centerpoint-buttons"> <acc-button class="centerpoint-button" label="Use current position" on-click=${()=> dispatch('center', true)}></acc-button> <span class="centerpoint-divider"> | </span> <acc-button class="centerpoint-button" label="Reset" on-click=${()=> dispatch('resetcenter', true)}></acc-button> </span> </div> </div> </div> <acc-button class="close" label="Done" on-click=${()=>this._handleCloseClick()}></acc-button> </div> <button class="help-container" role="button" on-click=${()=> dispatch('help')}> <svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <path id="help-question-mark" d="M12,2 C6.48,2 2,6.48 2,12 C2,17.52 6.48,22 12,22 C17.52,22 22,17.52 22,12 C22,6.48 17.52,2 12,2 L12,2 Z M13,19 L11,19 L11,17 L13,17 L13,19 L13,19 Z M15.07,11.25 L14.17,12.17 C13.45,12.9 13,13.5 13,15 L11,15 L11,14.5 C11,13.4 11.45,12.4 12.17,11.67 L13.41,10.41 C13.78,10.05 14,9.55 14,9 C14,7.9 13.1,7 12,7 C10.9,7 10,7.9 10,9 L8,9 C8,6.79 9.79,5 12,5 C14.21,5 16,6.79 16,9 C16,9.88 15.64,10.68 15.07,11.25 L15.07,11.25 Z" id="Shape" fill="#000000"></path> </svg> Help </button> `; } _shouldRender(props: any, changed: any, prev: any) { if(!changed){ return super._shouldRender(props, changed, prev); } const keys = Object.keys(changed); const justAmp = (keys.length === 1 && changed.amplification); if(justAmp || (keys.length < 3 && changed.part && changed.amplification)) { return false; } return super._shouldRender(props, changed, prev); } } // <a // class="set-centerpoint" // href="javascript:;" // on-click=${()=> { dispatch('center'); return false; }}>Use current position</a> | // <a // class="reset-centerpoint" // href="javascript:;" // on-click=${()=>{ dispatch('center'); return false;}}>Reset centerpoint</a> customElements.define('acc-pose-input-calibration', PoseInputCalibrationElement);
the_stack
import { TypeConstant, ActionCreatorBuilder, ActionBuilder, } from './type-helpers'; import { createAction } from './create-action'; export function throwInvalidAsyncActionArgument(argPosition: number): never { throw new Error( `Argument ${argPosition} is invalid, it should be an action type of "string | symbol" or a tuple of "[string | symbol, Function, Function?]"` ); } type AsyncActionHandler< TType extends TypeConstant, TArgs extends any[], TPayloadMeta > = [TArgs] extends [never] ? ActionCreatorBuilder< TType, unknown extends TPayloadMeta ? any : [TPayloadMeta] extends [[infer T, any]] ? T : TPayloadMeta, unknown extends TPayloadMeta ? undefined : [TPayloadMeta] extends [[any, infer T]] ? T : undefined > : ( ...args: TArgs ) => ActionBuilder< TType, [TPayloadMeta] extends [[infer T, any]] ? T : TPayloadMeta, [TPayloadMeta] extends [[any, infer T]] ? T : undefined >; interface AsyncAction< TType1 extends TypeConstant, TPayload1 extends any, TMeta1 extends any, TArgs1 extends any[], TType2 extends TypeConstant, TPayload2 extends any, TMeta2 extends any, TArgs2 extends any[], TType3 extends TypeConstant, TPayload3 extends any, TMeta3 extends any, TArgs3 extends any[], TType4 extends TypeConstant, TPayload4 extends any, TMeta4 extends any, TArgs4 extends any[] > { // tslint:disable-next-line: callable-types < TPayloadMeta1 extends | TPayload1 | [TPayload1, TMeta1] = TMeta1 extends undefined ? TPayload1 : [TPayload1, TMeta1], TPayloadMeta2 extends | TPayload2 | [TPayload2, TMeta2] = TMeta2 extends undefined ? TPayload2 : [TPayload2, TMeta2], TPayloadMeta3 extends | TPayload3 | [TPayload3, TMeta3] = TMeta3 extends undefined ? TPayload3 : [TPayload3, TMeta3], TPayloadMeta4 extends | TPayload4 | [TPayload4, TMeta4] = TMeta3 extends undefined ? TPayload4 : [TPayload4, TMeta4] >(): [TType4] extends [never] ? { request: AsyncActionHandler<TType1, TArgs1, TPayloadMeta1>; success: AsyncActionHandler<TType2, TArgs2, TPayloadMeta2>; failure: AsyncActionHandler<TType3, TArgs3, TPayloadMeta3>; } : { request: AsyncActionHandler<TType1, TArgs1, TPayloadMeta1>; success: AsyncActionHandler<TType2, TArgs2, TPayloadMeta2>; failure: AsyncActionHandler<TType3, TArgs3, TPayloadMeta3>; cancel: AsyncActionHandler<TType4, TArgs4, TPayloadMeta4>; }; } export function createAsyncAction< TType1 extends TypeConstant, TType2 extends TypeConstant, TType3 extends TypeConstant, TType4 extends TypeConstant = never >( requestArg: TType1, successArg: TType2, failureArg: TType3, cancelArg?: TType4 ): AsyncAction< TType1, unknown, unknown, never, TType2, unknown, unknown, never, TType3, unknown, unknown, never, TType4, unknown, unknown, never >; export function createAsyncAction< TType1 extends TypeConstant, TType2 extends TypeConstant, TType3 extends TypeConstant, TType4 extends TypeConstant = never, TPayloadCreator1 extends | ((...args: TArgs1) => TPayload1) | undefined = undefined, TPayloadCreator2 extends | ((...args: TArgs2) => TPayload2) | undefined = undefined, TPayloadCreator3 extends | ((...args: TArgs3) => TPayload3) | undefined = undefined, TPayloadCreator4 extends | ((...args: TArgs4) => TPayload4) | undefined = undefined, TMetaCreator1 extends ((...args: TArgs1) => TMeta1) | undefined = undefined, TMetaCreator2 extends ((...args: TArgs2) => TMeta2) | undefined = undefined, TMetaCreator3 extends ((...args: TArgs3) => TMeta3) | undefined = undefined, TMetaCreator4 extends ((...args: TArgs4) => TMeta4) | undefined = undefined, TPayload1 extends any = TPayloadCreator1 extends ((...args: any[]) => infer T) ? T : undefined, TMeta1 extends any = TMetaCreator1 extends ((...args: any[]) => infer T) ? T : undefined, TPayload2 extends any = TPayloadCreator2 extends ((...args: any[]) => infer T) ? T : undefined, TMeta2 extends any = TMetaCreator2 extends ((...args: any[]) => infer T) ? T : undefined, TPayload3 extends any = TPayloadCreator3 extends ((...args: any[]) => infer T) ? T : undefined, TMeta3 extends any = TMetaCreator3 extends ((...args: any[]) => infer T) ? T : undefined, TPayload4 extends any = TPayloadCreator4 extends ((...args: any[]) => infer T) ? T : undefined, TMeta4 extends any = TMetaCreator4 extends ((...args: any[]) => infer T) ? T : undefined, TArgs1 extends any[] = TPayloadCreator1 extends ((...args: infer T) => any) ? T : TMetaCreator1 extends ((...args: infer T) => any) ? T : never, TArgs2 extends any[] = TPayloadCreator2 extends ((...args: infer T) => any) ? T : TMetaCreator2 extends ((...args: infer T) => any) ? T : never, TArgs3 extends any[] = TPayloadCreator3 extends ((...args: infer T) => any) ? T : TMetaCreator3 extends ((...args: infer T) => any) ? T : never, TArgs4 extends any[] = TPayloadCreator4 extends ((...args: infer T) => any) ? T : TMetaCreator4 extends ((...args: infer T) => any) ? T : never >( requestArg: | TType1 | [TType1, TPayloadCreator1] | [TType1, TPayloadCreator1, TMetaCreator1], successArg: | TType2 | [TType2, TPayloadCreator2] | [TType2, TPayloadCreator2, TMetaCreator2], failureArg: | TType3 | [TType3, TPayloadCreator3] | [TType3, TPayloadCreator3, TMetaCreator3], cancelArg?: | TType4 | [TType4, TPayloadCreator4] | [TType4, TPayloadCreator4, TMetaCreator4] ): AsyncAction< TType1, TPayload1, TMeta1, TArgs1, TType2, TPayload2, TMeta2, TArgs2, TType3, TPayload3, TMeta3, TArgs3, TType4, TPayload4, TMeta4, TArgs4 >; /** * @description create an async action-creator object that contains `request`, `success` and `failure` actions as props */ export function createAsyncAction< TType1 extends TypeConstant, TType2 extends TypeConstant, TType3 extends TypeConstant, TType4 extends TypeConstant = never, TPayloadCreator1 extends | ((...args: TArgs1) => TPayload1) | undefined = undefined, TPayloadCreator2 extends | ((...args: TArgs2) => TPayload2) | undefined = undefined, TPayloadCreator3 extends | ((...args: TArgs3) => TPayload3) | undefined = undefined, TPayloadCreator4 extends | ((...args: TArgs4) => TPayload4) | undefined = undefined, TMetaCreator1 extends ((...args: TArgs1) => TMeta1) | undefined = undefined, TMetaCreator2 extends ((...args: TArgs2) => TMeta2) | undefined = undefined, TMetaCreator3 extends ((...args: TArgs3) => TMeta3) | undefined = undefined, TMetaCreator4 extends ((...args: TArgs4) => TMeta4) | undefined = undefined, TPayload1 extends any = TPayloadCreator1 extends ((...args: any[]) => infer T) ? T : undefined, TMeta1 extends any = TMetaCreator1 extends ((...args: any[]) => infer T) ? T : undefined, TPayload2 extends any = TPayloadCreator2 extends ((...args: any[]) => infer T) ? T : undefined, TMeta2 extends any = TMetaCreator2 extends ((...args: any[]) => infer T) ? T : undefined, TPayload3 extends any = TPayloadCreator3 extends ((...args: any[]) => infer T) ? T : undefined, TMeta3 extends any = TMetaCreator3 extends ((...args: any[]) => infer T) ? T : undefined, TPayload4 extends any = TPayloadCreator4 extends ((...args: any[]) => infer T) ? T : undefined, TMeta4 extends any = TMetaCreator4 extends ((...args: any[]) => infer T) ? T : undefined, TArgs1 extends any[] = TPayloadCreator1 extends ((...args: infer T) => any) ? T : TMetaCreator1 extends ((...args: infer T) => any) ? T : never, TArgs2 extends any[] = TPayloadCreator2 extends ((...args: infer T) => any) ? T : TMetaCreator2 extends ((...args: infer T) => any) ? T : never, TArgs3 extends any[] = TPayloadCreator3 extends ((...args: infer T) => any) ? T : TMetaCreator3 extends ((...args: infer T) => any) ? T : never, TArgs4 extends any[] = TPayloadCreator4 extends ((...args: infer T) => any) ? T : TMetaCreator4 extends ((...args: infer T) => any) ? T : never >( requestArg: | TType1 | [TType1, TPayloadCreator1] | [TType1, TPayloadCreator1, TMetaCreator1], successArg: | TType2 | [TType2, TPayloadCreator2] | [TType2, TPayloadCreator2, TMetaCreator2], failureArg: | TType3 | [TType3, TPayloadCreator3] | [TType3, TPayloadCreator3, TMetaCreator3], cancelArg?: | TType4 | [TType4, TPayloadCreator4] | [TType4, TPayloadCreator4, TMetaCreator4] ): AsyncAction< TType1, TPayload1, TMeta1, TArgs1, TType2, TPayload2, TMeta2, TArgs2, TType3, TPayload3, TMeta3, TArgs3, TType4, TPayload4, TMeta4, TArgs4 > { const constructor = (< TP1 = undefined, TM1 = undefined, TP2 = undefined, TM2 = undefined, TP3 = undefined, TM3 = undefined, TP4 = undefined, TM4 = undefined >() => { const results = [requestArg, successArg, failureArg, cancelArg].map( (arg, index) => { if (Array.isArray(arg)) { return createAction(arg[0], arg[1] as any, arg[2] as any)(); } else if (typeof arg === 'string' || typeof arg === 'symbol') { return createAction(arg as string)(); } else if (index < 3) { throwInvalidAsyncActionArgument(index); } } ); const [request, success, failure, cancel] = results; return { request, success, failure, cancel, }; }) as AsyncAction< TType1, TPayload1, TMeta1, TArgs1, TType2, TPayload2, TMeta2, TArgs2, TType3, TPayload3, TMeta3, TArgs3, TType4, TPayload4, TMeta4, TArgs4 >; return constructor; }
the_stack
import RamlWrapper1= require("../parser/artifacts/raml10parserapi") import RamlWrapper1Impl= require("../parser/artifacts/raml10parser") import RamlWrapper08= require("../parser/artifacts/raml08parserapi") import path=require("path") import jsonTypings = require("../typings-new-format/raml"); import Opt = require('../Opt') import jsyaml=require("../parser/jsyaml/jsyaml2lowLevel") import hl=require("../parser/highLevelAST") import hlimpl=require("../parser/highLevelImpl") import ll=require("../parser/lowLevelAST") import llimpl=require("../parser/jsyaml/jsyaml2lowLevel") import expanderLL=require("../parser/ast.core/expanderLL") import util=require("../util/index") import universeDef=require("../parser/tools/universe") import parserCore=require('../parser/wrapped-ast/parserCore') import parserCoreApi=require('../parser/wrapped-ast/parserCoreApi') import ramlServices = require("../parser/definition-system/ramlServices") import jsonSerializerHL = require("../util/jsonSerializerHL") import universeHelpers = require("./tools/universeHelpers"); import search = require("./../search/search-interface"); import linter=require("./ast.core/linter") import resolversApi = require("./jsyaml/resolversApi"); let messageRegistry = require("../../resources/errorMessages"); export type IHighLevelNode=hl.IHighLevelNode; export type IParseResult=hl.IParseResult; import universeProvider=require("../parser/definition-system/universeProvider") export function load(ramlPathOrContent:string,options?:parserCoreApi.LoadOptions):Promise<jsonTypings.RAMLParseResult>{ let serializeOptions = toNewFormatSerializeOptions(options); return parse(ramlPathOrContent,options).then(expanded=>{ return jsonSerializerHL.dump(expanded,serializeOptions); }); } export function loadSync(ramlPathOrContent:string,options?:parserCoreApi.LoadOptions):jsonTypings.RAMLParseResult{ let serializeOptions = toNewFormatSerializeOptions(options); let expanded = parseSync(ramlPathOrContent,options); return jsonSerializerHL.dump(expanded,serializeOptions); } export function parse(ramlPathOrContent:string,options?:parserCoreApi.LoadOptions):Promise<hl.IHighLevelNode>{ options = options || {}; let filePath = ramlPathOrContent; if(consideredAsRamlContent(ramlPathOrContent)){ options = loadOptionsForContent(ramlPathOrContent,options,options.filePath); filePath = virtualFilePath(options); } let loadRAMLOptions = toOldStyleOptions(options); return loadRAMLAsyncHL(filePath,loadRAMLOptions).then(hlNode=>{ var expanded:hl.IHighLevelNode; if(!options.hasOwnProperty("expandLibraries") || options.expandLibraries) { expanded = expanderLL.expandLibrariesHL(hlNode); } else{ expanded = expanderLL.expandTraitsAndResourceTypesHL(hlNode); } return expanded; }); } export function parseSync(ramlPathOrContent:string,options?:parserCoreApi.LoadOptions):hl.IHighLevelNode{ options = options || {}; let filePath = ramlPathOrContent; if(consideredAsRamlContent(ramlPathOrContent)){ options = loadOptionsForContent(ramlPathOrContent,options,options.filePath); filePath = virtualFilePath(options); } let loadRAMLOptions = toOldStyleOptions(options); let hlNode = loadRAMLInternalHL(filePath,loadRAMLOptions); let expanded:hl.IHighLevelNode; if (!options.hasOwnProperty("expandLibraries") || options.expandLibraries) { if(universeHelpers.isLibraryType(hlNode.definition())){ expanded = expanderLL.expandLibraryHL(hlNode) || hlNode; } else { expanded = expanderLL.expandLibrariesHL(hlNode) || hlNode; } } else { expanded = expanderLL.expandTraitsAndResourceTypesHL(hlNode)||hlNode; } return expanded; } /*** * Load API synchronously. Detects RAML version and uses corresponding parser. * @param apiPath Path to API: local file system path or Web URL * @param options Load options * @return Opt&lt;Api&gt;, where Api belongs to RAML 1.0 or RAML 0.8 model. ***/ export function loadApi(apiPath:string,arg1?:string[]|parserCoreApi.Options,arg2?:string[]|parserCoreApi.Options):Opt<RamlWrapper1.Api|RamlWrapper08.Api>{ var hlNode = loadRAMLInternalHL(apiPath,arg1,arg2); if(!hlNode) { return Opt.empty< RamlWrapper1.Api | RamlWrapper08.Api >(); } var api = <any>hlNode.wrapperNode(); var options = <parserCoreApi.Options>(Array.isArray(arg1) ? arg2 : arg1); setAttributeDefaults(api,options); return new Opt<RamlWrapper1.Api|RamlWrapper08.Api>(api); } /*** * Load RAML synchronously. Detects RAML version and uses corresponding parser. * @param ramlPath Path to RAML: local file system path or Web URL * @param options Load options * @return Opt&lt;RAMLLanguageElement&gt;, where RAMLLanguageElement belongs to RAML 1.0 or RAML 0.8 model. ***/ export function loadRAML(ramlPath:string,arg1?:string[]|parserCoreApi.Options,arg2?:string[]|parserCoreApi.Options) : Opt<hl.BasicNode> { var hlNode = loadRAMLInternalHL(ramlPath, arg1, arg2); if(!hlNode){ return Opt.empty<hl.BasicNode>(); } var api = hlNode.wrapperNode(); var options = <parserCoreApi.Options>(Array.isArray(arg1) ? arg2 : arg1); setAttributeDefaults(api,options); return new Opt<hl.BasicNode>(api); } /*** * Load RAML synchronously. Detects RAML version and uses corresponding parser. * @param ramlPath Path to RAML: local file system path or Web URL * @param options Load options * @return Opt&lt;hl.IHighLevelNode&gt; ***/ export function loadRAMLHL(ramlPath:string,arg1?:string[]|parserCoreApi.Options,arg2?:string[]|parserCoreApi.Options) : Opt<hl.IHighLevelNode> { var hlNode = loadRAMLInternalHL(ramlPath, arg1, arg2); if(!hlNode){ return Opt.empty<hl.IHighLevelNode>(); } return new Opt<hl.IHighLevelNode>(hlNode); } function loadRAMLInternalHL(apiPath:string,arg1?:string[]|parserCoreApi.Options,arg2?:string[]|parserCoreApi.Options) : hl.IHighLevelNode { var gotArray = Array.isArray(arg1); var extensionsAndOverlays = <string[]>(gotArray ? arg1: null); var options = <parserCoreApi.Options>(gotArray ? arg2 : arg1); options = options || {}; var project = getProject(apiPath,options); var pr=apiPath.indexOf("://"); var unitName=(pr!=-1&&pr<6)?apiPath:path.basename(apiPath); var unit = project.unit(unitName); if (arg2 && !extensionsAndOverlays) { extensionsAndOverlays=null; } var api:hl.IHighLevelNode; if(unit){ if (extensionsAndOverlays && extensionsAndOverlays.length > 0) { var extensionUnits = []; extensionsAndOverlays.forEach(currentPath =>{ if (!currentPath || currentPath.trim().length == 0) { throw new Error(messageRegistry.EXTENSIONS_AND_OVERLAYS_LEGAL_FILE_PATHS.message); } }) extensionsAndOverlays.forEach(unitPath=>{ extensionUnits.push(project.unit(unitPath, path.isAbsolute(unitPath))) }) //calling to perform the checks, we do not actually need the api itself extensionUnits.forEach(extensionUnit=>toApi(extensionUnit, options)) api = toApi(expanderLL.mergeAPIs(unit, extensionUnits, hlimpl.OverlayMergeMode.MERGE), options); } else { api = toApi(unit, options); (<hlimpl.ASTNodeImpl>api).setMergeMode(hlimpl.OverlayMergeMode.MERGE); } } if (!unit){ throw new Error(linter.applyTemplate(messageRegistry.CAN_NOT_RESOLVE,{path:apiPath})); } if(options.rejectOnErrors && api && api.errors().filter(x=>!x.isWarning).length){ throw toError(api); } return api; } /*** * Load API asynchronously. Detects RAML version and uses corresponding parser. * @param apiPath Path to API: local file system path or Web URL * @param options Load options * @return Promise&lt;Api&gt;, where Api belongs to RAML 1.0 or RAML 0.8 model. ***/ export function loadApiAsync(apiPath:string,arg1?:string[]|parserCoreApi.Options,arg2?:string[]|parserCoreApi.Options):Promise<RamlWrapper1.Api|RamlWrapper08.Api>{ var ramlPromise = loadRAMLAsync(apiPath,arg1,arg2); return ramlPromise.then(loadedRaml=>{ // if (false) { // //TODO check that loaded RAML is API // return Promise.reject("Specified RAML is not API"); // } else { return <RamlWrapper1.Api|RamlWrapper08.Api>loadedRaml; // } }) } /*** * Load API asynchronously. Detects RAML version and uses corresponding parser. * @param ramlPath Path to RAML: local file system path or Web URL * @param options Load options * @return Promise&lt;RAMLLanguageElement&gt;, where RAMLLanguageElement belongs to RAML 1.0 or RAML 0.8 model. ***/ export function loadRAMLAsync(ramlPath:string,arg1?:string[]|parserCoreApi.Options,arg2?:string[]|parserCoreApi.Options):Promise<hl.BasicNode>{ return loadRAMLAsyncHL(ramlPath,arg1,arg2).then(x=>{ if(!x){ return null; } var gotArray = Array.isArray(arg1); var options = <parserCoreApi.Options>(gotArray ? arg2 : arg1); var node = x; while (node != null) { var wn = node.wrapperNode(); setAttributeDefaults(wn,options); var master = node.getMaster(); node = master && master !== node ? master.asElement() : null; } return x.wrapperNode(); }); } export function loadRAMLAsyncHL(ramlPath:string,arg1?:string[]|parserCoreApi.Options,arg2?:string[]|parserCoreApi.Options):Promise<hl.IHighLevelNode>{ var gotArray = Array.isArray(arg1); var extensionsAndOverlays = <string[]>(gotArray ? arg1: null); var options = <parserCoreApi.Options>(gotArray ? arg2 : arg1); options = options || {}; var project = getProject(ramlPath,options); var pr=ramlPath.indexOf("://"); var unitName=(pr!=-1&&pr<6)?ramlPath:path.basename(ramlPath); if (arg2 && !extensionsAndOverlays) { extensionsAndOverlays=null; } if (!extensionsAndOverlays || extensionsAndOverlays.length == 0) { return fetchAndLoadApiAsyncHL(project, unitName, options).then(masterApi=>{ (<hlimpl.ASTNodeImpl>masterApi).setMergeMode(hlimpl.OverlayMergeMode.MERGE); return masterApi; }) } else { extensionsAndOverlays.forEach(currentPath =>{ if (!currentPath || currentPath.trim().length == 0) { throw new Error(messageRegistry.EXTENSIONS_AND_OVERLAYS_LEGAL_FILE_PATHS.message); } }) return fetchAndLoadApiAsyncHL(project, unitName, options).then(masterApi=>{ var apiPromises = [] extensionsAndOverlays.forEach(extensionUnitPath=>{ apiPromises.push(fetchAndLoadApiAsyncHL(project, extensionUnitPath, options)) }); return Promise.all(apiPromises).then(apis=>{ var overlayUnits = [] apis.forEach(currentApi=>overlayUnits.push(currentApi.lowLevel().unit())) var result = expanderLL.mergeAPIs(masterApi.lowLevel().unit(), overlayUnits, hlimpl.OverlayMergeMode.MERGE); return result; }).then(mergedHighLevel=>{ return toApi(mergedHighLevel, options); }) }); } } /** * Gets AST node by runtime type, if runtime type matches any. * @param runtimeType */ export function getLanguageElementByRuntimeType(runtimeType : hl.ITypeDefinition) : parserCore.BasicNode { if (runtimeType == null) { return null; } var highLevelNode = runtimeType.getAdapter(ramlServices.RAMLService).getDeclaringNode(); if (highLevelNode == null) { return null; } return highLevelNode.wrapperNode(); } function fetchAndLoadApiAsync(project: jsyaml.Project, unitName : string, options: parserCoreApi.Options):Promise<hl.BasicNode> { return fetchAndLoadApiAsyncHL(project,unitName,options).then(x=>x.wrapperNode()); } function fetchAndLoadApiAsyncHL(project: jsyaml.Project, unitName : string, options: parserCoreApi.Options):Promise<hl.IHighLevelNode>{ var _unitName = unitName.replace(/\\/g,"/") return llimpl.fetchIncludesAndMasterAsync(project,_unitName).then(x=>{ try { var api = toApi(x, options); if (options.rejectOnErrors && api && api.errors().filter(x=>!x.isWarning).length) { return Promise.reject<hl.IHighLevelNode>(toError(api)); } return api; } catch(err){ return Promise.reject<hl.IHighLevelNode>(err); } }); } function getProject(apiPath:string,options?:parserCoreApi.Options):jsyaml.Project { options = options || {}; var includeResolver = options.fsResolver; var httpResolver = options.httpResolver; var reusedNode = options.reusedNode; var project:jsyaml.Project; if(reusedNode){ let reusedUnit = reusedNode.lowLevel().unit(); project = <jsyaml.Project>reusedUnit.project(); project.namespaceResolver().deleteUnitModel(reusedUnit.absolutePath()); project.deleteUnit(path.basename(apiPath)); if(includeResolver) { project.setFSResolver(includeResolver); } if(httpResolver){ project.setHTTPResolver(httpResolver); } } else { var projectRoot = path.dirname(apiPath); project = new jsyaml.Project(projectRoot, includeResolver, httpResolver); } return project; }; function toApi(unitOrHighlevel:ll.ICompilationUnit|hl.IHighLevelNode, options:parserCoreApi.Options,checkApisOverlays=false):hl.IHighLevelNode { options = options||{}; if(!unitOrHighlevel){ return null; } var unit : ll.ICompilationUnit = null; var highLevel : hl.IHighLevelNode = null; if ((<any>unitOrHighlevel).isRAMLUnit) { unit = <ll.ICompilationUnit>unitOrHighlevel; } else { highLevel = <hlimpl.ASTNodeImpl>unitOrHighlevel; unit = highLevel.lowLevel().unit(); } var contents = unit.contents(); var ramlFirstLine = hlimpl.ramlFirstLine(contents); if(!ramlFirstLine){ throw new Error(messageRegistry.INVALID_FIRST_LINE.message); } var verStr = ramlFirstLine[1]; var ramlFileType = ramlFirstLine[2]; var typeName; var apiImpl; var ramlVersion; if (verStr == '0.8') { ramlVersion='RAML08'; } else if (verStr == '1.0') { ramlVersion='RAML10'; } if (!ramlVersion) { throw new Error(messageRegistry.UNKNOWN_RAML_VERSION.message); } if(ramlVersion=='RAML08'&&checkApisOverlays){ throw new Error(messageRegistry.EXTENSIONS_AND_OVERLAYS_NOT_SUPPORTED_0_8.message); } //if (!ramlFileType || ramlFileType.trim() === "") { // if (verStr=='0.8') { // typeName = universeDef.Universe08.Api.name; // apiImpl = RamlWrapper08.ApiImpl; // } else if(verStr=='1.0'){ // typeName = universeDef.Universe10.Api.name; // apiImpl = RamlWrapper1.ApiImpl; // } //} else if (ramlFileType === "Overlay") { // apiImpl = RamlWrapper1.OverlayImpl; // typeName = universeDef.Universe10.Overlay.name; //} else if (ramlFileType === "Extension") { // apiImpl = RamlWrapper1.ExtensionImpl; // typeName = universeDef.Universe10.Extension.name; //} var universe = universeProvider(ramlVersion); var apiType = universe.type(typeName); if (!highLevel) { highLevel = <hl.IHighLevelNode>hlimpl.fromUnit(unit); if(options.reusedNode) { if(options.reusedNode.lowLevel().unit().absolutePath()==unit.absolutePath()) { if(checkReusability(<hlimpl.ASTNodeImpl>highLevel, <hlimpl.ASTNodeImpl>options.reusedNode)) { (<hlimpl.ASTNodeImpl>highLevel).setReusedNode(options.reusedNode); } } } //highLevel = // new hlimpl.ASTNodeImpl(unit.ast(), null, <any>apiType, null) } //api = new apiImpl(highLevel); return highLevel; }; export function toError(api:hl.IHighLevelNode):hl.ApiLoadingError{ var error:any = new Error(messageRegistry.API_CONTAINS_ERROR.message); error.parserErrors = hlimpl.toParserErrors(api.errors(),api); return error; } export function loadApis1(projectRoot:string,cacheChildren:boolean = false,expandTraitsAndResourceTypes:boolean=true){ var universe = universeProvider("RAML10"); var apiType=universe.type(universeDef.Universe10.Api.name); var p=new jsyaml.Project(projectRoot); var result:RamlWrapper1.Api[] = []; p.units().forEach( x=> { var lowLevel = x.ast(); if(cacheChildren){ lowLevel = llimpl.toChildCachingNode (lowLevel); } var api:RamlWrapper1.Api = new RamlWrapper1Impl.ApiImpl(new hlimpl.ASTNodeImpl(lowLevel, null, <any>apiType, null)); if(expandTraitsAndResourceTypes){ api = expanderLL.expandTraitsAndResourceTypes(api); } result.push(api); }); return result; } function checkReusability(hnode:hlimpl.ASTNodeImpl,rNode:hlimpl.ASTNodeImpl){ if(!rNode) { return false; } var s1 = hnode.lowLevel().unit().contents(); var s2 = rNode.lowLevel().unit().contents(); var l = Math.min(s1.length,s2.length); var pos = -1; for(var i = 0 ; i < l ; i++){ if(s1.charAt(i)!=s2.charAt(i)){ pos = i; break; } } while(pos>0&&s1.charAt(pos).replace(/\s/,'')==''){ pos--; } if(pos<0&&s1.length!=s2.length){ pos = l; } var editedNode = search.deepFindNode(rNode,pos,pos+1); if(!editedNode){ return true; } if(editedNode.lowLevel().unit().absolutePath() != hnode.lowLevel().unit().absolutePath()){ return true; } var editedElement = editedNode.isElement() ? editedNode.asElement() : editedNode.parent(); if(!editedElement){ return true; } var pProp = editedElement.property(); if(!pProp){ return true; } if(universeHelpers.isAnnotationsProperty(pProp)){ editedElement = editedElement.parent(); } if(!editedElement){ return true; } var p = editedElement; while(p){ var pDef = p.definition(); if(universeHelpers.isResourceTypeType(pDef)||universeHelpers.isTraitType(pDef)){ return false; } var prop = p.property(); if(!prop){ return true; } if(universeHelpers.isTypeDeclarationDescendant(pDef)){ if(universeHelpers.isTypesProperty(prop)||universeHelpers.isAnnotationTypesProperty(prop)){ return false; } } var propRange = prop.range(); if(universeHelpers.isResourceTypeRefType(propRange)||universeHelpers.isTraitRefType(propRange)){ return false; } p = p.parent(); } return true; } function setAttributeDefaults(api:parserCoreApi.BasicNode,options){ options = options || {}; if (options.attributeDefaults != null && api) { (<any>api).setAttributeDefaults(options.attributeDefaults); } else if (api) { (<any>api).setAttributeDefaults(true); } } export function optionsForContent( content:string, arg2?:parserCoreApi.Options, _filePath?:string):parserCoreApi.Options{ let filePath = _filePath || virtualFilePath(arg2); let fsResolver = virtualFSResolver(filePath,content,arg2&&arg2.fsResolver); return { fsResolver:fsResolver, httpResolver:arg2?arg2.httpResolver:null, rejectOnErrors:arg2?arg2.rejectOnErrors:false, attributeDefaults:arg2?arg2.attributeDefaults:true } } function toOldStyleOptions(options:parserCoreApi.LoadOptions):parserCoreApi.Options{ if(!options){ return {}; } return { fsResolver: options.fsResolver, httpResolver: options.httpResolver, rejectOnErrors: false, attributeDefaults: true }; } export function loadOptionsForContent( content:string, arg2?:parserCoreApi.LoadOptions, _filePath?:string):parserCoreApi.LoadOptions{ let filePath = _filePath || virtualFilePath(arg2); let fsResolver = virtualFSResolver(filePath,content,arg2&&arg2.fsResolver); let result:parserCoreApi.LoadOptions = { fsResolver: fsResolver }; if(!arg2){ return result; } for(let key of Object.keys(arg2)){ if(key != "fsResolver"){ result[key] = arg2[key]; } } return result; } function consideredAsRamlContent(str:string):boolean{ str = str && str.trim(); if(!str){ return true; } if(str.length<="#%RAML".length){ return util.stringStartsWith("#%RAML",str); } else if(util.stringStartsWith(str,"#%RAML")){ return true; } return str.indexOf("\n")>=0; } function toNewFormatSerializeOptions(options: parserCoreApi.LoadOptions) { options = options || {}; return { rootNodeDetails: true, attributeDefaults: true, serializeMetadata: options.serializeMetadata || false, expandExpressions: options.expandExpressions, typeReferences: options.typeReferences, expandTypes: options.expandTypes, typeExpansionRecursionDepth: options.typeExpansionRecursionDepth, sourceMap: options.sourceMap }; } export function virtualFSResolver( filePath: string, content: string, originalResolver: resolversApi.FSResolver):resolversApi.FSResolver { if(filePath!=null){ filePath = filePath.replace(/\\/g,"/"); } return { content(pathStr: string): string { if (pathStr === filePath) { return content; } if (originalResolver) { return originalResolver.content(pathStr); } }, contentAsync(pathStr: string): Promise<string> { if (pathStr === filePath) { return Promise.resolve<string>(content); } if (originalResolver) { return originalResolver.contentAsync(pathStr); } } }; } export function virtualFilePath(opt:parserCoreApi.Options|parserCoreApi.LoadOptions):string{ let filePath = (opt && opt.filePath)||path.resolve("/#local.raml"); return filePath.replace(/\\/g,"/"); }
the_stack
import path = require('path'); import Tacks = require('tacks'); import tempy = require('tempy'); import touch = require('touch'); import { findConfigs, generateConfig, isUpToDate } from '../lib/pectin-api'; const { Dir, File, Symlink } = Tacks; type UpdateHelper = { (fp: string): Promise<void>; cwd: string; }; const makeUpdater = (cwd: string): UpdateHelper => { const ctime = Date.now() / 1000; // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore (the types are wrong, stuff it mr. typescript) const opts: touch.Options = { mtime: ctime + 1 }; const updater = async (fp: string): Promise<void> => touch(path.join(cwd, 'modules', fp), opts); // avoid process.cwd() calls updater.cwd = cwd; return updater; }; type TacksItem = Tacks.Dir | Tacks.File | Tacks.Symlink; function createFixture(pkgSpec: { [fp: string]: TacksItem }): UpdateHelper { const cwd = tempy.directory(); const fixture = new Tacks( Dir({ '.babelrc': File({ presets: ['@babel/preset-env'], }), 'lerna.json': File({ packages: ['modules/**'], }), 'package.json': File({ name: 'monorepo', private: true, }), 'modules': Dir(pkgSpec), }) ); fixture.create(cwd); process.chdir(cwd); return makeUpdater(cwd); } describe('pectin-api', () => { // avoid polluting other test state const REPO_ROOT = path.resolve(__dirname, '../../..'); afterAll(() => { process.chdir(REPO_ROOT); }); afterEach(() => { jest.restoreAllMocks(); delete process.env.ROLLUP_WATCH; }); it('builds packages when output directory is missing', async () => { createFixture({ 'no-output': Dir({ 'package.json': File({ name: '@test/no-output', main: 'dist/index.js', }), 'src': Dir({ 'index.js': File('export default "test";'), }), }), }); await expect(findConfigs()).resolves.toMatchObject([ { input: 'modules/no-output/src/index.js' }, ]); }); it('builds packages in topological order', async () => { createFixture({ 'a-dependent': Dir({ 'package.json': File({ name: '@test/a-dependent', main: 'dist/index.js', dependencies: { '@test/their-dependency': 'file:../their-dependency', }, }), 'src': Dir({ 'index.js': File('export default "test";'), }), }), 'their-dependency': Dir({ 'package.json': File({ name: '@test/their-dependency', main: 'dist/index.js', }), 'src': Dir({ 'index.js': File('export default "test";'), }), }), }); await expect(findConfigs()).resolves.toMatchObject([ { input: 'modules/their-dependency/src/index.js' }, { input: 'modules/a-dependent/src/index.js' }, ]); }); it('builds packages when input files are newer than output', async () => { const updateFile = createFixture({ 'old-output': Dir({ 'package.json': File({ name: '@test/old-output', main: 'lib/index.js', }), 'lib': Dir({ 'index.js': File('module.exports = "test";'), }), 'src': Dir({ 'index.js': File('export default from "./other";'), 'other.js': File('export default "test";'), }), }), }); await updateFile('old-output/src/other.js'); await expect(findConfigs()).resolves.toMatchObject([ { input: 'modules/old-output/src/index.js' }, ]); }); it('matches .jsx files, too', async () => { const updateFile = createFixture({ 'jsx-input': Dir({ 'package.json': File({ name: '@test/jsx-input', main: 'dist/index.js', }), 'dist': Dir({ 'index.js': File('module.exports = "test";'), }), 'src': Dir({ 'index.js': File('export default from "./other";'), 'other.jsx': File('export default "test";'), }), }), }); await updateFile('jsx-input/src/other.jsx'); await expect(findConfigs()).resolves.toMatchObject([ { input: 'modules/jsx-input/src/index.js' }, ]); }); it('does not build when input files are older than output', async () => { const updateFile = createFixture({ 'old-input': Dir({ 'package.json': File({ name: '@test/old-input', main: 'lib/index.js', }), 'lib': Dir({ 'index.js': File('module.exports = "test";'), }), 'src': Dir({ 'index.js': File('export default from "./other";'), 'other.js': File('export default "test";'), }), }), }); await Promise.all([ updateFile('old-input/lib/index.js'), // less than OR equal updateFile('old-input/src/other.js'), ]); await expect(findConfigs()).resolves.toStrictEqual([]); }); it('does not compare build output with itself', async () => { const updateFile = createFixture({ 'rooted-input': Dir({ 'package.json': File({ name: '@test/rooted-input', main: 'dist/index.js', rollup: { input: 'app.js', }, }), 'app.js': File('export default "test";'), 'dist': Dir({ 'index.js': File('module.exports = "test";'), }), }), }); await updateFile('rooted-input/dist/index.js'); await expect(findConfigs()).resolves.toStrictEqual([]); }); it('does not compare tests or node_modules with last build', async () => { const updateFile = createFixture({ 'rooted-ignore': Dir({ 'package.json': File({ name: '@test/rooted-ignore', main: 'dist/index.js', rollup: { input: 'app.js', }, }), 'app.js': File('export default "test";'), '__tests__': Dir({ 'ignored.js': File('ignored'), }), 'dist': Dir({ 'index.js': File('module.exports = "test";'), }), 'node_modules': Dir({ foo: Dir({ 'index.js': File('ignored'), 'package.json': File({ name: 'foo', main: 'index.js', }), }), }), 'src': Dir({ '__tests__': Dir({ 'ignored.js': File('ignored'), }), 'ignored-test.js': File('ignored'), 'ignored.test.js': File('ignored'), }), 'test': Dir({ 'ignored.js': File('ignored'), }), }), }); await Promise.all([ updateFile('rooted-ignore/__tests__/ignored.js'), updateFile('rooted-ignore/node_modules/foo/index.js'), updateFile('rooted-ignore/src/__tests__/ignored.js'), updateFile('rooted-ignore/src/ignored-test.js'), updateFile('rooted-ignore/src/ignored.test.js'), updateFile('rooted-ignore/test/ignored.js'), ]); await expect(findConfigs()).resolves.toStrictEqual([]); }); it('does not watch a module with pkg.rollup.ignoreWatch', async () => { const updateFile = createFixture({ unwatched: Dir({ 'package.json': File({ name: '@test/unwatched', main: 'dist/index.js', rollup: { ignoreWatch: true, }, }), 'dist': Dir({ 'index.js': File('module.exports = "test";'), }), 'src': Dir({ 'index.js': File('export default "test";'), }), }), }); await updateFile('unwatched/src/index.js'); // simulate `rollup --watch` process.env.ROLLUP_WATCH = 'true'; await expect(findConfigs()).resolves.toStrictEqual([]); }); it('does not build a module with pkg.rollup.skip', async () => { createFixture({ skipped: Dir({ 'package.json': File({ name: '@test/skipped', main: 'dist/index.js', rollup: { skip: true, }, }), 'lib': Dir({ 'index.js': File('module.exports = "test";'), }), }), }); await expect(findConfigs()).resolves.toStrictEqual([]); }); it('does not build a module with missing pkg.main', async () => { jest.spyOn(console, 'error').mockImplementation(() => { /* avoid console spam when error is logged */ }); createFixture({ 'no-pkg-main': Dir({ 'package.json': File({ name: '@test/no-pkg-main', }), 'lib': Dir({ 'index.js': File('module.exports = "test";'), }), }), }); await expect(findConfigs()).resolves.toStrictEqual([]); // eslint-disable-next-line no-console expect(console.error).toHaveBeenCalled(); }); it('uses cwd argument instead of implicit process.cwd()', async () => { const { cwd } = createFixture({ 'explicit-cwd': Dir({ 'package.json': File({ name: '@test/explicit-cwd', main: 'dist/index.js', }), 'src': Dir({ 'index.js': File('export default "test";'), }), }), }); // change implicit process.cwd() process.chdir(REPO_ROOT); await expect(findConfigs({ cwd })).resolves.toMatchObject([ { input: path.relative('.', path.join(cwd, 'modules/explicit-cwd/src/index.js')), }, ]); }); it('supports recursive package globs', async () => { const updateFile = createFixture({ app: Dir({ 'package.json': File({ name: '@test/app', main: 'dist/index.js', dependencies: { 'missing-dist': '../lib/missing-dist', }, }), 'dist': Dir({ 'index.js': File('module.exports = "test";'), }), 'node_modules': Dir({ 'missing-dist': Symlink('../../lib/missing-dist'), }), 'src': Dir({ 'index.js': File('export default from "./other";'), 'other.js': File('export default "test";'), }), }), lib: Dir({ 'missing-dist': Dir({ 'package.json': File({ name: '@test/missing-dist', main: 'dist/index.js', module: 'dist/index.module.js', dependencies: { bar: '^1.0.0', }, }), 'node_modules': Dir({ bar: Dir({ 'lib': Dir({ 'index.js': File('ignored'), }), 'package.json': File({ name: 'bar', main: 'lib/index.js', }), 'src': Dir({ 'index.js': File('do not transpile node_modules :P'), }), }), }), 'src': Dir({ 'index.js': File('export default "test";'), }), }), }), }); await Promise.all([ updateFile('app/src/other.js'), updateFile('lib/missing-dist/node_modules/bar/src/index.js'), ]); await expect(findConfigs()).resolves.toMatchObject([ { input: 'modules/lib/missing-dist/src/index.js', output: [{ format: 'cjs', exports: 'auto' }], }, { input: 'modules/lib/missing-dist/src/index.js', output: [{ format: 'esm', exports: 'named' }], }, { input: 'modules/app/src/index.js', output: [{ format: 'cjs', exports: 'auto' }], }, ]); }); it('sets watch config for all inputs when enabled', async () => { const updateFile = createFixture({ 'watch-existing': Dir({ 'package.json': File({ name: '@test/watch-existing', main: 'lib/index.js', module: 'lib/index.module.js', }), 'lib': Dir({ 'index.js': File('module.exports = "test";'), }), 'src': Dir({ 'index.js': File('export default from "./other";'), 'other.js': File('export default "test";'), }), }), 'watch-missing': Dir({ 'package.json': File({ name: '@test/watch-missing', main: 'lib/index.js', }), 'src': Dir({ 'index.js': File('export default "unbuilt";'), }), }), }); await Promise.all([ updateFile('watch-existing/lib/index.js'), // watch always builds _everything_ updateFile('watch-existing/src/other.js'), ]); await expect(findConfigs({ watch: true })).resolves.toMatchObject([ { watch: { clearScreen: false } }, { watch: { clearScreen: false } }, { watch: { clearScreen: false } }, ]); }); describe('generateConfig', () => { it('supports 1.x cwd config location', async () => { const { cwd } = createFixture({ 'package.json': File({ name: '@test/pkg-cwd', main: 'dist/index.js', }), 'src': Dir({ 'index.js': File('export default "test";'), }), }); const pkg = { name: '@test/pkg-cwd', main: 'dist/index.js', cwd, }; const opts = {}; const config = await generateConfig(pkg, opts); expect(config).toMatchObject([ { input: 'src/index.js', output: [{ format: 'cjs', exports: 'auto' }], }, ]); // options are not mutated expect(opts).toStrictEqual({}); }); }); describe('isUpToDate', () => { it('supports 1.x argument signature', async () => { const updateFile = createFixture({ 'package.json': File({ name: '@test/up-to-date', main: 'dist/index.js', }), 'dist': Dir({ 'index.js': File('module.exports = "test";'), }), 'src': Dir({ 'index.js': File('export default "test";'), }), }); const { cwd } = updateFile; await updateFile('src/index.js'); const result = await isUpToDate( { cwd }, { input: 'src/index.js', output: [ { file: path.resolve(cwd, 'dist/index.js'), format: 'cjs', exports: 'auto', }, ], } ); expect(result).toBe(false); }); }); });
the_stack
export class DataGridSharedData { public static getEmployees(count?: number): any[] { if (count === undefined) { count = 250; } const employees: any[] = []; let maleCount: number = 0; let femaleCount: number = 0; for (let i = 0; i < count; i += 1) { const age: number = Math.round(this.getRandomNumber(20, 40)); const gender: string = this.getRandomGender(); const firstName: string = this.getRandomNameFirst(gender); const lastName: string = this.getRandomNameLast(); const street: string = this.getRandomStreet(); const country: string = this.getRandomItem(this.countries); const city: string = this.getRandomCity(country); const generation = `${Math.floor(age / 10) * 10}s`; const email: string = `${firstName.toLowerCase()}@${this.getRandomItem(this.emails)}`; const website: string = `${firstName.toLowerCase()}-${this.getRandomItem(this.websites)}`; let photoPath: any; if (gender === 'male') { maleCount += 1; if (maleCount > 26) { maleCount = 1; } photoPath = this.getPhotoMale(maleCount); } else { femaleCount += 1; if (femaleCount > 24) { femaleCount = 1; } photoPath = this.getPhotoFemale(femaleCount); } const person: any = {}; person.Address = `${street},${city}`; person.Age = age; person.Birthday = this.getBirthday(age); person.City = city; person.Country = country; person.CountryFlag = this.getCountryFlag(country); person.Email = email; person.FirstName = firstName; person.Gender = this.getGenderPhoto(gender); person.Generation = generation; person.ID = this.pad(i + 1, 5); person.LastName = lastName; person.Name = `${firstName} ${lastName}`; person.Phone = this.getRandomPhone(); person.Photo = photoPath; person.Street = street; person.Salary = this.getRandomNumber(40, 200) * 1000; person.Sales = this.getRandomNumber(200, 980) * 1000; person.Website = website; person.Productivity = this.getProductivity(); if (person.Salary < 50000) { person.Income = 'Low'; } else if (person.Salary < 100000) { person.Income = 'Average'; } else { person.Income = 'High'; } employees.push(person); } return employees; } public static getProductivity(weekCount?: number): any[] { if (weekCount === undefined) { weekCount = 52; } const productivity: any[] = []; for (let w = 0; w < weekCount; w += 1) { const value = this.getRandomNumber(-50, 50); productivity.push({ Value: value, Week: w }); } return productivity; } public static getSales(count?: number): any[] { if (count === undefined) { count = 250; } const names: string[] = [ 'Intel CPU', 'AMD CPU', 'NVIDIA GPU', 'GIGABYTE GPU', 'Asus GPU', 'AMD GPU', 'MSI GPU', 'Corsair Memory', 'Patriot Memory', 'Skill Memory', 'Samsung HDD', 'WD HDD', 'Seagate HDD', 'Intel HDD', 'Samsung SSD', 'WD SSD', 'Seagate SSD', 'Intel SSD', 'Samsung Monitor', 'Asus Monitor', 'LG Monitor', 'HP Monitor']; const countries: string[] = ['USA', 'UK', 'France', 'Canada', 'Poland', 'Japan', 'Germany']; const status: string[] = ['Packing', 'Shipped', 'Delivered']; const sales: any[] = []; for (let i = 0; i < count; i += 1) { const price = this.getRandomNumber(100, 900); const items = this.getRandomNumber(10, 80); const value = price * items; const margin = this.getRandomNumber(3, 10); const profit = Math.round((price * (margin / 100)) * items); const country = this.getRandomItem(countries); sales.push({ BundlePrice: price, ProductPrice: price, Margin: margin, OrderDate: this.getRandomDate(new Date(2012, 0, 1), new Date()), OrderItems: items, OrderValue: value, // Math.round(value / 1000) + ',' + Math.round(value % 1000), ProductID: 1001 + i, ProductName: this.getRandomItem(names), Profit: profit, Countries: country, CountryFlag: this.getCountryFlag(country), Status: this.getRandomItem(status), }); } return sales; } public static getHouses(count?: number): any[] { if (count === undefined) { count = 250; } const houses: any[] = []; const property: string[] = ['Townhouse', 'Single', 'Condo', 'Villa']; const emails: string[] = ['estates.com', 'remax.com', 'zillow.com', 'realtor.com', 'coldwell.com']; const countries: string[] = ['USA', 'UK', 'France', 'Canada', 'Poland', 'Japan', 'Germany']; for (let i = 0; i < count; i += 1) { const year: number = this.getRandomNumber(1950, 2015); const age: number = 2020 - year; const gender: string = this.getRandomGender(); const firstName: string = this.getRandomNameFirst(gender); const lastName: string = this.getRandomNameLast(); const initials = firstName.substr(0, 1).toLowerCase(); const email: string = `${initials + lastName.toLowerCase()}@${this.getRandomItem(emails)}`; const street: string = this.getRandomStreet(); const country: string = this.getRandomItem(countries); const city: string = this.getRandomCity(country); houses.push({ Address: `${street},${city}`, Age: age, Agent: `${firstName} ${lastName}`, Area: this.getRandomNumber(50, 300), Baths: this.getRandomNumber(1, 3), Built: year, City: city, Country: country, CountryFlag: this.getCountryFlag(country), Email: email, ID: this.pad(i + 1, 5), Phone: this.getRandomPhone(), Price: this.getRandomNumber(210, 900) * 1000, Property: this.getRandomItem(property), Rooms: this.getRandomNumber(2, 5), SaleDate: this.getRandomDate(new Date(2015, 0, 1), new Date()), Street: street, }); } return houses; } private static websites: string[] = ['.com', '.gov', '.edu', '.org']; private static emails: string[] = ['gmail.com', 'yahoo.com', 'twitter.com']; private static genders: string[] = ['male', 'female']; private static maleNames: string[] = ['Kyle', 'Oscar', 'Ralph', 'Mike', 'Bill', 'Frank', 'Howard', 'Jack', 'Larry', 'Pete', 'Steve', 'Vince', 'Mark', 'Alex', 'Max', 'Brian', 'Chris', 'Andrew', 'Martin', 'Mike', 'Steve', 'Glenn', 'Bruce']; private static femaleNames: string[] = ['Gina', 'Irene', 'Katie', 'Brenda', 'Casey', 'Fiona', 'Holly', 'Kate', 'Liz', 'Pamela', 'Nelly', 'Marisa', 'Monica', 'Anna', 'Jessica', 'Sofia', 'Isabella', 'Margo', 'Jane', 'Audrey', 'Sally', 'Melanie', 'Greta', 'Aurora', 'Sally']; private static lastNames: string[] = ['Adams', 'Crowley', 'Ellis', 'Martinez', 'Irvine', 'Maxwell', 'Clark', 'Owens', 'Rooney', 'Lincoln', 'Thomas', 'Spacey', 'MOrgan', 'King', 'Newton', 'Fitzgerald', 'Holmes', 'Jefferson', 'Landry', 'Berry', 'Perez', 'Spencer', 'Starr', 'Carter', 'Edwards', 'Stark', 'Johnson', 'Fitz', 'Chief', 'Blanc', 'Perry', 'Stone', 'Williams', 'Lane', 'Jobs', 'Adams', 'Power', 'Tesla']; private static countries: string[] = ['USA', 'UK', 'France', 'Canada', 'Poland']; private static citiesUS: string[] = ['New York', 'Los Angeles', 'Miami', 'San Francisco', 'San Diego', 'Las Vegas']; private static citiesUK: string[] = ['London', 'Liverpool', 'Manchester']; private static citiesFR: string[] = ['Paris', 'Marseille', 'Lyon']; private static citiesCA: string[] = ['Toronto', 'Vancouver', 'Montreal']; private static citiesPL: string[] = ['Krakow', 'Warsaw', 'Wroclaw', 'Gdansk']; private static citiesJP: string[] = ['Tokyo', 'Osaka', 'Kyoto', 'Yokohama']; private static citiesGR: string[] = ['Berlin', 'Bonn', 'Cologne', 'Munich', 'Hamburg']; private static roadSuffixes: string[] = ['Road', 'Street', 'Way']; private static roadNames: string[] = ['Main', 'Garden', 'Broad', 'Oak', 'Cedar', 'Park', 'Pine', 'Elm', 'Market', 'Hill']; private static getRandomNumber(min: number, max: number): number { return Math.round(min + Math.random() * (max - min)); } private static getRandomItem(array: any[]): any { const index = Math.round(this.getRandomNumber(0, array.length - 1)); return array[index]; } private static getRandomDate(start: Date, end: Date) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); } private static getRandomPhone(): string { const phoneCode = this.getRandomNumber(100, 900); const phoneNum1 = this.getRandomNumber(100, 900); const phoneNum2 = this.getRandomNumber(1000, 9000); const phone = `${phoneCode}-${phoneNum1}-${phoneNum2}`; return phone; } private static getRandomGender(): string { return this.getRandomItem(this.genders); } private static getRandomNameLast(): string { return this.getRandomItem(this.lastNames); } private static getRandomNameFirst(gender: string): string { if (gender === 'male') { return this.getRandomItem(this.maleNames); } return this.getRandomItem(this.femaleNames); } private static getRandomCity(country: string): string { if (country === 'Canada') { return this.getRandomItem(this.citiesCA); } if (country === 'France') { return this.getRandomItem(this.citiesFR); } if (country === 'Poland') { return this.getRandomItem(this.citiesPL); } if (country === 'USA') { return this.getRandomItem(this.citiesUS); } if (country === 'Japan') { return this.getRandomItem(this.citiesJP); } if (country === 'Germany') { return this.getRandomItem(this.citiesGR); } // if (country === 'United Kingdom') return this.getRandomItem(this.citiesUK); } private static getRandomStreet(): string { const num = Math.round(this.getRandomNumber(100, 300)).toString(); const road = this.getRandomItem(this.roadNames); const suffix = this.getRandomItem(this.roadSuffixes); return `${num} ${road} ${suffix}`; } private static getBirthday(age: number): Date { const today: Date = new Date(); const year: number = today.getFullYear() - age; const month: number = this.getRandomNumber(0, 8); const day: number = this.getRandomNumber(10, 27); return new Date(year, month, day); } private static getPhotoMale(id: number): string { return `https://static.infragistics.com/xplatform/images/people//GUY${this.pad(id, 2)}.png`; } private static getPhotoFemale(id: number): string { return `https://static.infragistics.com/xplatform/images/people/GIRL${this.pad(id, 2)}.png`; } private static getGenderPhoto(gender: string): string { return `https://static.infragistics.com/xplatform/images/genders/${gender}.png`; } private static getCountryFlag(country: string): string { return `https://static.infragistics.com/xplatform/images/flags/${country}.png`; } private static pad(num: number, size: number) { let s = `${num}`; while (s.length < size) { s = `0${s}`; } return s; } }
the_stack
// ==================================================== // GraphQL fragment: ChannelTableContentsConnectable // ==================================================== export interface ChannelTableContentsConnectable_Attachment_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Attachment_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Attachment_connection { __typename: "Connection"; can: ChannelTableContentsConnectable_Attachment_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsConnectable_Attachment_connection_user | null; } export interface ChannelTableContentsConnectable_Attachment_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Attachment_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsConnectable_Attachment_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsConnectable_Attachment_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Attachment { __typename: "Attachment"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsConnectable_Attachment_connection | null; can: ChannelTableContentsConnectable_Attachment_can | null; source: ChannelTableContentsConnectable_Attachment_source | null; counts: ChannelTableContentsConnectable_Attachment_counts | null; created_at: string | null; updated_at: string | null; file_url: string | null; image_url: string | null; title: string; user: ChannelTableContentsConnectable_Attachment_user | null; } export interface ChannelTableContentsConnectable_Embed_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Embed_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Embed_connection { __typename: "Connection"; can: ChannelTableContentsConnectable_Embed_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsConnectable_Embed_connection_user | null; } export interface ChannelTableContentsConnectable_Embed_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Embed_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsConnectable_Embed_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsConnectable_Embed_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Embed { __typename: "Embed"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsConnectable_Embed_connection | null; can: ChannelTableContentsConnectable_Embed_can | null; source: ChannelTableContentsConnectable_Embed_source | null; counts: ChannelTableContentsConnectable_Embed_counts | null; created_at: string | null; updated_at: string | null; embed_html: string | null; image_url: string | null; title: string; user: ChannelTableContentsConnectable_Embed_user | null; } export interface ChannelTableContentsConnectable_Image_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Image_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Image_connection { __typename: "Connection"; can: ChannelTableContentsConnectable_Image_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsConnectable_Image_connection_user | null; } export interface ChannelTableContentsConnectable_Image_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Image_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsConnectable_Image_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsConnectable_Image_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Image { __typename: "Image"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsConnectable_Image_connection | null; can: ChannelTableContentsConnectable_Image_can | null; source: ChannelTableContentsConnectable_Image_source | null; find_original_url: string | null; counts: ChannelTableContentsConnectable_Image_counts | null; created_at: string | null; updated_at: string | null; image_url: string | null; title: string; user: ChannelTableContentsConnectable_Image_user | null; } export interface ChannelTableContentsConnectable_Link_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Link_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Link_connection { __typename: "Connection"; can: ChannelTableContentsConnectable_Link_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsConnectable_Link_connection_user | null; } export interface ChannelTableContentsConnectable_Link_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Link_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsConnectable_Link_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsConnectable_Link_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Link { __typename: "Link"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsConnectable_Link_connection | null; can: ChannelTableContentsConnectable_Link_can | null; source: ChannelTableContentsConnectable_Link_source | null; counts: ChannelTableContentsConnectable_Link_counts | null; created_at: string | null; updated_at: string | null; image_url: string | null; title: string; user: ChannelTableContentsConnectable_Link_user | null; } export interface ChannelTableContentsConnectable_PendingBlock_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_PendingBlock_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_PendingBlock_connection { __typename: "Connection"; can: ChannelTableContentsConnectable_PendingBlock_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsConnectable_PendingBlock_connection_user | null; } export interface ChannelTableContentsConnectable_PendingBlock_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_PendingBlock_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsConnectable_PendingBlock_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_PendingBlock { __typename: "PendingBlock"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsConnectable_PendingBlock_connection | null; can: ChannelTableContentsConnectable_PendingBlock_can | null; counts: ChannelTableContentsConnectable_PendingBlock_counts | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsConnectable_PendingBlock_user | null; } export interface ChannelTableContentsConnectable_Text_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Text_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Text_connection { __typename: "Connection"; can: ChannelTableContentsConnectable_Text_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsConnectable_Text_connection_user | null; } export interface ChannelTableContentsConnectable_Text_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Text_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelTableContentsConnectable_Text_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsConnectable_Text_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Text { __typename: "Text"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsConnectable_Text_connection | null; can: ChannelTableContentsConnectable_Text_can | null; source: ChannelTableContentsConnectable_Text_source | null; counts: ChannelTableContentsConnectable_Text_counts | null; created_at: string | null; updated_at: string | null; content: string; html: string; title: string; user: ChannelTableContentsConnectable_Text_user | null; } export interface ChannelTableContentsConnectable_Channel_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsConnectable_Channel_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Channel_connection { __typename: "Connection"; can: ChannelTableContentsConnectable_Channel_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsConnectable_Channel_connection_user | null; } export interface ChannelTableContentsConnectable_Channel_can { __typename: "ChannelCan"; mute: boolean | null; } export interface ChannelTableContentsConnectable_Channel_counts { __typename: "ChannelCounts"; connected_to_channels: number | null; contents: number | null; } export interface ChannelTableContentsConnectable_Channel_user { __typename: "User"; name: string; } export interface ChannelTableContentsConnectable_Channel { __typename: "Channel"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsConnectable_Channel_connection | null; can: ChannelTableContentsConnectable_Channel_can | null; visibility: string; title: string; counts: ChannelTableContentsConnectable_Channel_counts | null; created_at: string | null; updated_at: string | null; user: ChannelTableContentsConnectable_Channel_user | null; } export type ChannelTableContentsConnectable = ChannelTableContentsConnectable_Attachment | ChannelTableContentsConnectable_Embed | ChannelTableContentsConnectable_Image | ChannelTableContentsConnectable_Link | ChannelTableContentsConnectable_PendingBlock | ChannelTableContentsConnectable_Text | ChannelTableContentsConnectable_Channel;
the_stack