text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { join } from 'path' import markdownItAnchor from 'markdown-it-anchor' import { defaultsDeep } from 'lodash' import { pathToName, slugify, logger } from './utils' import Database from './content/database' import { Nuxtent } from '../types' import { RouteConfig, Route } from 'vue-router' import markdownIt from 'markdown-it' import markdownItTocDoneRight from 'markdown-it-toc-done-right' import { Nuxt } from '../types/nuxt' const createParser = (markdownConfig: Nuxtent.Config.Markdown) => { const config = markdownConfig.settings if (typeof markdownConfig.extend === 'function') { markdownConfig.extend(config) } const parser = markdownIt(config) const plugins = markdownConfig.plugins || {} Object.keys(plugins).forEach(plugin => { Array.isArray(plugins[plugin]) ? parser.use.apply(parser, plugins[ plugin ] as Nuxtent.Config.MarkdownItPluginArray) : parser.use(plugins[plugin] as Nuxtent.Config.MarkdownItPlugin) }) if (typeof markdownConfig.customize === 'function') { markdownConfig.customize(parser) } return parser } /** * @description Nuxtent Config Module * * @export * @class NuxtentConfig */ export default class NuxtentConfig implements Nuxtent.Config.Config { /** * @description The hostname to use the server * @type {String} * @memberOf NuxtentConfig */ public host: string = process.env.NUXTENT_HOST || process.env.HOST || 'localhost' /** * @description The port to use * @type {String} * @memberOf NuxtentConfig */ public port: string = process.env.NUXTENT_PORT || process.env.PORT || '3000' /** * @description The nuxt publicPath * @const {String} * @private * * @memberOf NuxtentConfig */ public publicPath = '/_nuxt/' public markdownSettings: Nuxtent.Config.MarkdownSettings = { html: true, linkify: true, preset: 'default', typographer: true, } public defaultMarkdown: Nuxtent.Config.Markdown = { customize: undefined, parser: undefined, plugins: {}, settings: { ...this.markdownSettings }, use: [], } public defaultToc: Nuxtent.Config.Toc = { level: 2, permalink: true, permalinkClass: 'nuxtent-anchor', permalinkSymbol: '🔗', slugify, } /** * @description * @type {NuxtentConfigContentGenereate} * * @memberOf NuxtentConfig */ public requestMethods: Nuxtent.RequestMethods[] = [ 'getOnly', 'get', ['getAll', { query: { exclude: ['body'] } }], ] public content: Nuxtent.ContentArray public api: Nuxtent.Config.Api public build: Nuxtent.Config.Build public markdown: Nuxtent.Config.Markdown public toc: Nuxtent.Config.Toc public routePaths: Nuxtent.RoutePaths = new Map() public assetMap: Nuxtent.AssetMap = new Map() public database: Map<string, Database> = new Map() /** * @description An array of the static pages to render during generate * */ public staticRoutes: string[] = [] /** * @description Is a static (--generate) build * */ public isStatic: boolean = false protected defaultContent: Nuxtent.Config.Content protected defaultBuild: Nuxtent.Config.Build = { buildDir: 'content', componentsDir: 'components', contentDir: 'content', contentDirWebpackAlias: '~/components', contentExtensions: ['json', 'md', 'yaml', 'yml'], ignorePrefix: '-', loaderComponentExtensions: ['.vue', '.js', '.mjs', '.tsx'], } protected get defaultApi(): Nuxtent.Config.Api { return { apiBrowserPrefix: this.publicPath + this.defaultBuild.buildDir, apiServerPrefix: '/content-api', baseURL: `http://${this.host}:${this.port}`, browserBaseURL: '', host: this.host, port: this.port, } } /** * @description The default container struture for content collections * * @memberOf NuxtentConfig */ protected defaultContentContainer: Nuxtent.ContentArray private userConfig: Nuxtent.Config.User /** * Creates an instance of NuxtentConfig. * @param {Object} [moduleOptions={}] The module of the config found on nuxt.config.js * @param {Object} options The nuxt options found on ModuleContainer.options * * @memberOf NuxtentConfig */ constructor(moduleOptions: Nuxt.ModuleConfiguration, options: Nuxt.Options) { this.build = { ...this.defaultBuild } this.markdown = { ...{ settigs: this.markdownSettings }, ...this.defaultMarkdown, } this.toc = { ...this.defaultToc } this.api = { ...this.defaultApi } this.defaultContent = { breadcrumbs: false, data: undefined, isPost: false, markdown: { ...this.defaultMarkdown }, method: [...this.requestMethods], page: '', permalink: ':slug', toc: { ...this.defaultToc }, } this.defaultContentContainer = [ ['/', this.defaultContent], ] this.content = this.defaultContentContainer this.userConfig = { api: { ...this.defaultApi }, build: { ...this.defaultBuild }, content: [ ...this.defaultContentContainer ], markdown: { ...this.defaultMarkdown }, toc: { ...this.defaultToc }, } this.userConfig = defaultsDeep({}, this.userConfig, moduleOptions, options.nuxtent) if (options.build) { this.publicPath = options.build.publicPath || this.publicPath } const srcDir = options.srcDir || '~/' this.build.contentDir = join(srcDir, 'content') this.build.componentsDir = join(srcDir, 'components') } /** * @description The public config object * * @readonly * * @memberOf NuxtentConfig */ get config() { return { api: this.api, build: this.build, content: this.content, markdown: this.markdown, toc: this.toc, } } public setApi(options: Nuxt.Options) { this.host = options.host || this.host this.port = options.port || this.port process.env.NUXTENT_HOST = this.host process.env.NUXTENT_PORT = this.port this.api = defaultsDeep({}, this.defaultApi, this.userConfig.api) } public async init(rootDir = '~/'): Promise<NuxtentConfig> { const userConfig = await this.loadNuxtentConfig(rootDir) let content!: Nuxtent.ContentArray if (!Array.isArray(userConfig.content)) { content = [ ['/', { ...this.defaultContent, ...userConfig.content }], ] } else { content = userConfig.content.map(([container, options]) => { return [container, defaultsDeep(options, this.defaultContent)] }) } delete userConfig.content defaultsDeep(this.userConfig, userConfig) this.api = defaultsDeep({}, this.defaultApi, this.userConfig.api) this.build = defaultsDeep({}, this.defaultBuild, this.userConfig.build) this.markdown = defaultsDeep({}, this.defaultMarkdown, this.userConfig.markdown) this.toc = defaultsDeep({}, this.defaultToc, this.userConfig.toc) this.content = content this.markdown.parser = createParser(this.markdown) for (const [, contentEntry] of this.content) { contentEntry.markdown = defaultsDeep({}, contentEntry.markdown, this.markdown) contentEntry.markdown.parser = createParser(contentEntry.markdown) } this.buildContent() return Promise.resolve(this) } /** * Load the nuxtent config file * @param {String} rootDir The root of the proyect */ public async loadNuxtentConfig( rootDir: string ): Promise<Nuxtent.Config.User> { const rootConfig = join(rootDir, 'nuxtent.config.js') try { const configModule = await import(rootConfig) return configModule.default ? configModule.default : configModule } catch (error) { if ( error.code === 'MODULE_NOT_FOUND' && error.message.includes('nuxtent.config.js') ) { logger.warn('nuxtent.config.js not found, fallingback to defaults') return this.userConfig } throw new Error(`[Invalid nuxtent configuration] ${error}`) } } /** * Formats the toc options * @param dirOpts The content definition * @returns The content with the toc formatted and the plugin inserted */ public setTocOptions( dirOpts: Nuxtent.Config.Content = this.defaultContent ): Nuxtent.Config.Content { // End early if is falsey if (!dirOpts.toc) { dirOpts.toc = false return dirOpts } // Local var to set the config const tocConfig = this.defaultToc if (typeof dirOpts.toc === 'number') { defaultsDeep(tocConfig, { level: dirOpts.toc, }) } else if (typeof dirOpts.toc === 'object') { defaultsDeep(tocConfig, dirOpts.toc) } else { dirOpts.toc = tocConfig } // Setting toc dirOpts.toc = tocConfig dirOpts.markdown.plugins.toc = [markdownItAnchor, tocConfig] dirOpts.markdown.plugins.markdownItTocDoneRight = [ markdownItTocDoneRight, { containerClass: 'nuxtent-toc', slugify, }, ] return dirOpts } public buildContent() { this.content.forEach(([, content]) => { const { page, permalink } = content if (page) { this.routePaths.set(pathToName(page), permalink) } }) } /** * Intercept the nuxt routes and map them to nuxtent, usefull for date routes * @param {*} moduleContianer - A map with all the routes * @returns {void} */ public interceptRoutes(moduleContianer: Nuxt.ModuleContainer): void { const renameRoutePath = (route: RouteConfig): RouteConfig => { if (!route.name) { return route } const overwritedPath = this.routePaths.get(route.name) if (overwritedPath !== undefined) { const isOptional = route.path.match(/\?$/) // QUESTION: Why did we had this? // const match = overwritedPath.match(/\/(.*)/) // if (match) { // overwritedPath = match[1] // } logger.debug( `Renamed ${route.name} path ${route.path} > ${overwritedPath}` ) route.path = isOptional ? overwritedPath + '?' : overwritedPath } // else if (route.children) { // route.children.forEach(renameRoutePath) // } return route } if (typeof moduleContianer.extendRoutes !== 'function') { throw new Error('There is no "extendRoutes"') } moduleContianer.extendRoutes((routes: RouteConfig[], resolve) => routes.map(renameRoutePath) ) } public createContentDatabase() { this.content.forEach(([dirName, content]) => { const db = new Database(this.build, dirName, content) this.database.set(dirName, db) }) return this.database } }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreFileUploader, CoreFileUploaderStoreFilesResult } from '@features/fileuploader/services/fileuploader'; import { FileEntry } from '@ionic-native/file/ngx'; import { CoreFile } from '@services/file'; import { CoreFileEntry } from '@services/file-helper'; import { CoreSites } from '@services/sites'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreFormFields } from '@singletons/form'; import { AddonModWorkshopAssessmentStrategyFieldErrors } from '../components/assessment-strategy/assessment-strategy'; import { AddonWorkshopAssessmentStrategyDelegate } from './assessment-strategy-delegate'; import { AddonModWorkshopExampleMode, AddonModWorkshopPhase, AddonModWorkshopUserOptions, AddonModWorkshopProvider, AddonModWorkshopData, AddonModWorkshop, AddonModWorkshopSubmissionData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, AddonModWorkshopPhaseTaskData, AddonModWorkshopSubmissionAssessmentData, AddonModWorkshopGetAssessmentFormDefinitionData, AddonModWorkshopAction, AddonModWorkshopOverallFeedbackMode, AddonModWorkshopGetAssessmentFormFieldsParsedData, } from './workshop'; import { AddonModWorkshopOffline, AddonModWorkshopOfflineSubmission } from './workshop-offline'; /** * Helper to gather some common functions for workshop. */ @Injectable({ providedIn: 'root' }) export class AddonModWorkshopHelperProvider { /** * Get a task by code. * * @param tasks Array of tasks. * @param taskCode Unique task code. * @return Task requested */ getTask(tasks: AddonModWorkshopPhaseTaskData[], taskCode: string): AddonModWorkshopPhaseTaskData | undefined { return tasks.find((task) => task.code == taskCode); } /** * Check is task code is done. * * @param tasks Array of tasks. * @param taskCode Unique task code. * @return True if task is completed. */ isTaskDone(tasks: AddonModWorkshopPhaseTaskData[], taskCode: string): boolean { const task = this.getTask(tasks, taskCode); if (task) { return !!task.completed; } // Task not found, assume true. return true; } /** * Return if a user can submit a workshop. * * @param workshop Workshop info. * @param access Access information. * @param tasks Array of tasks. * @return True if the user can submit the workshop. */ canSubmit( workshop: AddonModWorkshopData, access: AddonModWorkshopGetWorkshopAccessInformationWSResponse, tasks: AddonModWorkshopPhaseTaskData[], ): boolean { const examplesMust = workshop.useexamples && workshop.examplesmode == AddonModWorkshopExampleMode.EXAMPLES_BEFORE_SUBMISSION; const examplesDone = access.canmanageexamples || workshop.examplesmode == AddonModWorkshopExampleMode.EXAMPLES_VOLUNTARY || this.isTaskDone(tasks, 'examples'); return workshop.phase > AddonModWorkshopPhase.PHASE_SETUP && access.cansubmit && (!examplesMust || examplesDone); } /** * Return if a user can assess a workshop. * * @param workshop Workshop info. * @param access Access information. * @return True if the user can assess the workshop. */ canAssess(workshop: AddonModWorkshopData, access: AddonModWorkshopGetWorkshopAccessInformationWSResponse): boolean { const examplesMust = workshop.useexamples && workshop.examplesmode == AddonModWorkshopExampleMode.EXAMPLES_BEFORE_ASSESSMENT; const examplesDone = access.canmanageexamples; return !examplesMust || examplesDone; } /** * Return a particular user submission from the submission list. * * @param workshopId Workshop ID. * @param options Other options. * @return Resolved with the submission, resolved with false if not found. */ async getUserSubmission( workshopId: number, options: AddonModWorkshopUserOptions = {}, ): Promise<AddonModWorkshopSubmissionData | undefined> { const userId = options.userId || CoreSites.getCurrentSiteUserId(); const submissions = await AddonModWorkshop.getSubmissions(workshopId, options); return submissions.find((submission) => submission.authorid == userId); } /** * Return a particular submission. It will use prefetched data if fetch fails. * * @param workshopId Workshop ID. * @param submissionId Submission ID. * @param options Other options. * @return Resolved with the submission, resolved with false if not found. */ async getSubmissionById( workshopId: number, submissionId: number, options: AddonModWorkshopUserOptions = {}, ): Promise<AddonModWorkshopSubmissionData> { try { return await AddonModWorkshop.getSubmission(workshopId, submissionId, options); } catch { const submissions = await AddonModWorkshop.getSubmissions(workshopId, options); const submission = submissions.find((submission) => submission.id == submissionId); if (!submission) { throw new CoreError('Submission not found'); } return submission; } } /** * Return a particular assesment. It will use prefetched data if fetch fails. It will add assessment form data. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param options Other options. * @return Resolved with the assessment. */ async getReviewerAssessmentById( workshopId: number, assessmentId: number, options: AddonModWorkshopUserOptions = {}, ): Promise<AddonModWorkshopSubmissionAssessmentWithFormData> { let assessment: AddonModWorkshopSubmissionAssessmentWithFormData | undefined; try { assessment = await AddonModWorkshop.getAssessment(workshopId, assessmentId, options); } catch (error) { const assessments = await AddonModWorkshop.getReviewerAssessments(workshopId, options); assessment = assessments.find((assessment_1) => assessment_1.id == assessmentId); if (!assessment) { throw error; } } assessment.form = await AddonModWorkshop.getAssessmentForm(workshopId, assessmentId, options); return assessment; } /** * Retrieves the assessment of the given user and all the related data. * * @param workshopId Workshop ID. * @param options Other options. * @return Promise resolved when the workshop data is retrieved. */ async getReviewerAssessments( workshopId: number, options: AddonModWorkshopUserOptions = {}, ): Promise<AddonModWorkshopSubmissionAssessmentWithFormData[]> { options.siteId = options.siteId || CoreSites.getCurrentSiteId(); const assessments: AddonModWorkshopSubmissionAssessmentWithFormData[] = await AddonModWorkshop.getReviewerAssessments(workshopId, options); const promises: Promise<void>[] = []; assessments.forEach((assessment) => { promises.push(this.getSubmissionById(workshopId, assessment.submissionid, options).then((submission) => { assessment.submission = submission; return; })); promises.push(AddonModWorkshop.getAssessmentForm(workshopId, assessment.id, options).then((assessmentForm) => { assessment.form = assessmentForm; return; })); }); await Promise.all(promises); return assessments; } /** * Delete stored attachment files for a submission. * * @param workshopId Workshop ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when deleted. */ async deleteSubmissionStoredFiles(workshopId: number, siteId?: string): Promise<void> { const folderPath = await AddonModWorkshopOffline.getSubmissionFolder(workshopId, siteId); // Ignore any errors, CoreFileProvider.removeDir fails if folder doesn't exists. await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath)); } /** * Given a list of files (either online files or local files), store the local files in a local folder * to be submitted later. * * @param workshopId Workshop ID. * @param files List of files. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if success, rejected otherwise. */ async storeSubmissionFiles( workshopId: number, files: CoreFileEntry[], siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult> { // Get the folder where to store the files. const folderPath = await AddonModWorkshopOffline.getSubmissionFolder(workshopId, siteId); return CoreFileUploader.storeFilesToUpload(folderPath, files); } /** * Upload or store some files for a submission, depending if the user is offline or not. * * @param workshopId Workshop ID. * @param submissionId If not editing, it will refer to timecreated. * @param files List of files. * @param editing If the submission is being edited or added otherwise. * @param offline True if files sould be stored for offline, false to upload them. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if success. */ uploadOrStoreSubmissionFiles( workshopId: number, files: CoreFileEntry[], offline: true, siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult>; uploadOrStoreSubmissionFiles( workshopId: number, files: CoreFileEntry[], offline: false, siteId?: string, ): Promise<number>; uploadOrStoreSubmissionFiles( workshopId: number, files: CoreFileEntry[], offline: boolean, siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult | number> { if (offline) { return this.storeSubmissionFiles(workshopId, files, siteId); } return CoreFileUploader.uploadOrReuploadFiles(files, AddonModWorkshopProvider.COMPONENT, workshopId, siteId); } /** * Get a list of stored attachment files for a submission. See AddonModWorkshopHelperProvider#storeFiles. * * @param workshopId Workshop ID. * @param submissionId If not editing, it will refer to timecreated. * @param editing If the submission is being edited or added otherwise. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the files. */ async getStoredSubmissionFiles( workshopId: number, siteId?: string, ): Promise<FileEntry[]> { const folderPath = await AddonModWorkshopOffline.getSubmissionFolder(workshopId, siteId); // Ignore not found files. return CoreUtils.ignoreErrors(CoreFileUploader.getStoredFiles(folderPath), []); } /** * Get a list of stored attachment files for a submission and online files also. See AddonModWorkshopHelperProvider#storeFiles. * * @param filesObject Files object combining offline and online information. * @param workshopId Workshop ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the files. */ async getSubmissionFilesFromOfflineFilesObject( filesObject: CoreFileUploaderStoreFilesResult, workshopId: number, siteId?: string, ): Promise<CoreFileEntry[]> { const folderPath = await AddonModWorkshopOffline.getSubmissionFolder(workshopId, siteId); return CoreFileUploader.getStoredFilesFromOfflineFilesObject(filesObject, folderPath); } /** * Delete stored attachment files for an assessment. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when deleted. */ async deleteAssessmentStoredFiles(workshopId: number, assessmentId: number, siteId?: string): Promise<void> { const folderPath = await AddonModWorkshopOffline.getAssessmentFolder(workshopId, assessmentId, siteId); // Ignore any errors, CoreFileProvider.removeDir fails if folder doesn't exists. await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath)); } /** * Given a list of files (either online files or local files), store the local files in a local folder * to be submitted later. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param files List of files. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if success, rejected otherwise. */ async storeAssessmentFiles( workshopId: number, assessmentId: number, files: CoreFileEntry[], siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult> { // Get the folder where to store the files. const folderPath = await AddonModWorkshopOffline.getAssessmentFolder(workshopId, assessmentId, siteId); return CoreFileUploader.storeFilesToUpload(folderPath, files); } /** * Upload or store some files for an assessment, depending if the user is offline or not. * * @param workshopId Workshop ID. * @param assessmentId ID. * @param files List of files. * @param offline True if files sould be stored for offline, false to upload them. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if success. */ uploadOrStoreAssessmentFiles( workshopId: number, assessmentId: number, files: CoreFileEntry[], offline: true, siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult>; uploadOrStoreAssessmentFiles( workshopId: number, assessmentId: number, files: CoreFileEntry[], offline: false, siteId?: string, ): Promise<number> uploadOrStoreAssessmentFiles( workshopId: number, assessmentId: number, files: CoreFileEntry[], offline: boolean, siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult | number> { if (offline) { return this.storeAssessmentFiles(workshopId, assessmentId, files, siteId); } return CoreFileUploader.uploadOrReuploadFiles(files, AddonModWorkshopProvider.COMPONENT, workshopId, siteId); } /** * Get a list of stored attachment files for an assessment. See AddonModWorkshopHelperProvider#storeFiles. * * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the files. */ async getStoredAssessmentFiles(workshopId: number, assessmentId: number, siteId?: string): Promise<FileEntry[]> { const folderPath = await AddonModWorkshopOffline.getAssessmentFolder(workshopId, assessmentId, siteId); // Ignore not found files. return CoreUtils.ignoreErrors(CoreFileUploader.getStoredFiles(folderPath), []); } /** * Get a list of stored attachment files for an assessment and online files also. See AddonModWorkshopHelperProvider#storeFiles. * * @param filesObject Files object combining offline and online information. * @param workshopId Workshop ID. * @param assessmentId Assessment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the files. */ async getAssessmentFilesFromOfflineFilesObject( filesObject: CoreFileUploaderStoreFilesResult, workshopId: number, assessmentId: number, siteId?: string, ): Promise<CoreFileEntry[]> { const folderPath = await AddonModWorkshopOffline.getAssessmentFolder(workshopId, assessmentId, siteId); return CoreFileUploader.getStoredFilesFromOfflineFilesObject(filesObject, folderPath); } /** * Applies offline data to submission. * * @param submission Submission object to be modified. * @param actions Offline actions to be applied to the given submission. * @return Promise resolved with the files. */ async applyOfflineData( submission?: AddonModWorkshopSubmissionDataWithOfflineData, actions: AddonModWorkshopOfflineSubmission[] = [], ): Promise<AddonModWorkshopSubmissionDataWithOfflineData | undefined> { if (actions.length == 0) { return submission; } if (submission === undefined) { submission = { id: 0, workshopid: 0, title: '', content: '', timemodified: 0, example: false, authorid: 0, timecreated: 0, contenttrust: 0, attachment: 0, published: false, late: 0, }; } let attachmentsId: CoreFileUploaderStoreFilesResult | undefined; const workshopId = actions[0].workshopid; actions.forEach((action) => { switch (action.action) { case AddonModWorkshopAction.ADD: case AddonModWorkshopAction.UPDATE: submission!.title = action.title; submission!.content = action.content; submission!.title = action.title; submission!.courseid = action.courseid; submission!.submissionmodified = action.timemodified / 1000; submission!.offline = true; attachmentsId = action.attachmentsid as CoreFileUploaderStoreFilesResult; break; case AddonModWorkshopAction.DELETE: submission!.deleted = true; submission!.submissionmodified = action.timemodified / 1000; break; default: } }); // Check offline files for latest attachmentsid. if (attachmentsId) { submission.attachmentfiles = await this.getSubmissionFilesFromOfflineFilesObject(attachmentsId, workshopId); } else { submission.attachmentfiles = []; } return submission; } /** * Prepare assessment data to be sent to the server. * * @param workshop Workshop object. * @param selectedValues Assessment current values * @param feedbackText Feedback text. * @param feedbackFiles Feedback attachments. * @param form Assessment form original data. * @param attachmentsId The draft file area id for attachments. * @return Promise resolved with the data to be sent. Or rejected with the input errors object. */ async prepareAssessmentData( workshop: AddonModWorkshopData, selectedValues: AddonModWorkshopGetAssessmentFormFieldsParsedData[], feedbackText: string, form: AddonModWorkshopGetAssessmentFormDefinitionData, attachmentsId: CoreFileUploaderStoreFilesResult | number = 0, ): Promise<CoreFormFields<unknown>> { if (workshop.overallfeedbackmode == AddonModWorkshopOverallFeedbackMode.ENABLED_REQUIRED && !feedbackText) { const errors: AddonModWorkshopAssessmentStrategyFieldErrors = { feedbackauthor: Translate.instant('core.err_required') }; throw errors; } const data = (await AddonWorkshopAssessmentStrategyDelegate.prepareAssessmentData(workshop.strategy!, selectedValues, form)) || {}; data.feedbackauthor = feedbackText; data.feedbackauthorattachmentsid = attachmentsId; data.nodims = form.dimenssionscount; return data; } /** * Calculates the real value of a grade based on real_grade_value. * * @param value Percentual value from 0 to 100. * @param max The maximal grade. * @param decimals Decimals to show in the formatted grade. * @return Real grade formatted. */ protected realGradeValueHelper(value?: number | string, max = 0, decimals = 0): string | undefined { if (typeof value == 'string') { // Already treated. return value; } if (value == null || value === undefined) { return undefined; } if (max == 0) { return '0'; } value = CoreTextUtils.roundToDecimals(max * value / 100, decimals); return CoreUtils.formatFloat(value); } /** * Calculates the real value of a grades of an assessment. * * @param workshop Workshop object. * @param assessment Assessment data. * @return Assessment with real grades. */ realGradeValue( workshop: AddonModWorkshopData, assessment: AddonModWorkshopSubmissionAssessmentWithFormData, ): AddonModWorkshopSubmissionAssessmentWithFormData { assessment.grade = this.realGradeValueHelper(assessment.grade, workshop.grade, workshop.gradedecimals); assessment.gradinggrade = this.realGradeValueHelper(assessment.gradinggrade, workshop.gradinggrade, workshop.gradedecimals); assessment.gradinggradeover = this.realGradeValueHelper( assessment.gradinggradeover, workshop.gradinggrade, workshop.gradedecimals, ); return assessment; } /** * Check grade should be shown * * @param grade Grade to be shown * @return If grade should be shown or not. */ showGrade(grade?: number|string): boolean { return grade !== undefined && grade !== null; } } export const AddonModWorkshopHelper = makeSingleton(AddonModWorkshopHelperProvider); export type AddonModWorkshopSubmissionAssessmentWithFormData = Omit<AddonModWorkshopSubmissionAssessmentData, 'grade'|'gradinggrade'|'gradinggradeover'|'feedbackattachmentfiles'> & { form?: AddonModWorkshopGetAssessmentFormDefinitionData; submission?: AddonModWorkshopSubmissionData; offline?: boolean; strategy?: string; grade?: string | number; gradinggrade?: string | number; gradinggradeover?: string | number; ownAssessment?: boolean; feedbackauthor?: string; feedbackattachmentfiles: CoreFileEntry[]; // Feedbackattachmentfiles. }; export type AddonModWorkshopSubmissionDataWithOfflineData = Omit<AddonModWorkshopSubmissionData, 'attachmentfiles'> & { courseid?: number; submissionmodified?: number; offline?: boolean; deleted?: boolean; attachmentfiles?: CoreFileEntry[]; reviewedby?: AddonModWorkshopSubmissionAssessmentWithFormData[]; reviewerof?: AddonModWorkshopSubmissionAssessmentWithFormData[]; gradinggrade?: number; reviewedbydone?: number; reviewerofdone?: number; reviewedbycount?: number; reviewerofcount?: number; };
the_stack
import { expect } from "chai"; import { Field, NestedContentField, PropertiesField } from "../../presentation-common"; import { FieldDescriptor, FieldDescriptorType } from "../../presentation-common/content/Fields"; import { RelationshipMeaning } from "../../presentation-common/rules/content/modifiers/RelatedPropertiesSpecification"; import { createTestCategoryDescription, createTestNestedContentField, createTestPropertiesContentField, createTestSimpleContentField, } from "../_helpers/Content"; import { createTestECClassInfo, createTestPropertyInfo, createTestRelatedClassInfo } from "../_helpers/EC"; describe("Field", () => { describe("fromJSON", () => { it("creates valid Field from valid JSON", () => { const category = createTestCategoryDescription(); const json = createTestSimpleContentField({ category }).toJSON(); const field = Field.fromJSON({ ...json }, [category]); expect(field).to.matchSnapshot(); }); it("creates valid PropertiesField from valid JSON", () => { const category = createTestCategoryDescription(); const json = createTestPropertiesContentField({ category, properties: [{ property: createTestPropertyInfo() }], }).toJSON(); const field = Field.fromJSON(json, [category]); expect(field).to.matchSnapshot(); }); it("creates valid NestedContentField from valid JSON", () => { const category = createTestCategoryDescription(); const json = createTestNestedContentField({ category, nestedFields: [createTestSimpleContentField({ category })], }).toJSON(); const field = Field.fromJSON(json, [category]); expect(field).to.matchSnapshot(); }); it("returns undefined for undefined JSON", () => { const item = Field.fromJSON(undefined, []); expect(item).to.be.undefined; }); it("throws when creating field with category that doesn't exist in given list", () => { const category = createTestCategoryDescription(); const json = createTestSimpleContentField({ category }).toJSON(); expect(() => Field.fromJSON({ ...json, category: "does not exist" }, [category])).to.throw(); }); }); describe("isPropertiesField", () => { it("returns false for non-properties field", () => { const field = createTestSimpleContentField(); expect(field.isPropertiesField()).to.be.false; }); it("returns true for properties field", () => { const field = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo() }] }); expect(field.isPropertiesField()).to.be.true; }); }); describe("isNestedContentField", () => { it("returns false for non-nested content field", () => { const field = createTestSimpleContentField(); expect(field.isNestedContentField()).to.be.false; }); it("returns true for nested content field", () => { const field = createTestNestedContentField({ nestedFields: [], }); expect(field.isNestedContentField()).to.be.true; }); }); describe("getFieldDescriptor", () => { it("creates `NamedFieldDescriptor`", () => { const field = createTestSimpleContentField(); expect(field.getFieldDescriptor()).to.deep.eq({ type: FieldDescriptorType.Name, fieldName: field.name, }); }); }); describe("clone", () => { it("returns exact copy of itself", () => { const field = createTestSimpleContentField(); const clone = field.clone(); expect(clone).to.be.instanceOf(Field); expect(clone.toJSON()).to.deep.eq(field.toJSON()); }); }); }); describe("PropertiesField", () => { describe("fromJSON", () => { it("creates valid PropertiesField from valid JSON", () => { const category = createTestCategoryDescription(); const json = createTestPropertiesContentField({ category, properties: [{ property: createTestPropertyInfo() }], }).toJSON(); const field = Field.fromJSON(json, [category]); expect(field).to.matchSnapshot(); }); it("returns undefined for undefined JSON", () => { const field = PropertiesField.fromJSON(undefined, []); expect(field).to.be.undefined; }); }); describe("getFieldDescriptor", () => { it("creates `PropertiesFieldDescriptor` for root field", () => { const propertyInfo = createTestPropertyInfo(); const field = createTestPropertiesContentField({ properties: [{ property: propertyInfo }], }); expect(field.getFieldDescriptor()).to.deep.eq({ type: FieldDescriptorType.Properties, properties: [{ class: propertyInfo.classInfo.name, name: propertyInfo.name, }], pathFromSelectToPropertyClass: [], }); }); it("creates `PropertiesFieldDescriptor` for nested field", () => { const propertyInfo1 = createTestPropertyInfo({ name: "prop1" }); const propertyInfo2 = createTestPropertyInfo({ name: "prop2" }); const propertiesField = createTestPropertiesContentField({ properties: [{ property: propertyInfo1 }, { property: propertyInfo2 }], }); const parent1 = createTestNestedContentField({ nestedFields: [propertiesField], pathToPrimaryClass: [ createTestRelatedClassInfo({ sourceClassInfo: createTestECClassInfo({ name: "a" }), relationshipInfo: createTestECClassInfo({ name: "a-b" }), targetClassInfo: createTestECClassInfo({ name: "b" }), isForwardRelationship: true, isPolymorphicRelationship: true, isPolymorphicTargetClass: true, }), ], }); const parent2 = createTestNestedContentField({ nestedFields: [parent1], pathToPrimaryClass: [ createTestRelatedClassInfo({ sourceClassInfo: createTestECClassInfo({ name: "c" }), relationshipInfo: createTestECClassInfo({ name: "c-d" }), targetClassInfo: createTestECClassInfo({ name: "d" }), isForwardRelationship: false, isPolymorphicRelationship: false, isPolymorphicTargetClass: false, }), ], }); parent2.rebuildParentship(); expect(propertiesField.getFieldDescriptor()).to.deep.eq({ type: FieldDescriptorType.Properties, properties: [{ class: propertyInfo1.classInfo.name, name: propertyInfo1.name, }, { class: propertyInfo2.classInfo.name, name: propertyInfo2.name, }], pathFromSelectToPropertyClass: [{ sourceClassName: "d", relationshipName: "c-d", targetClassName: "c", isForwardRelationship: true, }, { sourceClassName: "b", relationshipName: "a-b", targetClassName: "a", isForwardRelationship: false, }], }); }); }); describe("clone", () => { it("returns exact copy of itself", () => { const field = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo() }], }); const clone = field.clone(); expect(clone).to.be.instanceOf(PropertiesField); expect(clone.toJSON()).to.deep.eq(field.toJSON()); }); }); }); describe("NestedContentField", () => { describe("getFieldByName", () => { it("returns undefined when there are no nested fields", () => { const field = createTestNestedContentField({ nestedFields: [] }); expect(field.getFieldByName("test")).to.be.undefined; }); it("returns undefined when field is not found", () => { const nested = createTestSimpleContentField(); const field = createTestNestedContentField({ nestedFields: [nested] }); expect(field.getFieldByName("does_not_exist", true)).to.be.undefined; }); it("returns a field", () => { const nested = createTestSimpleContentField(); const field = createTestNestedContentField({ nestedFields: [nested] }); expect(field.getFieldByName(nested.name)).to.eq(nested); }); }); describe("fromJSON", () => { it("creates valid NestedContentField from valid JSON", () => { const category = createTestCategoryDescription(); const json = createTestNestedContentField({ category, nestedFields: [createTestSimpleContentField({ category })], }).toJSON(); const field = Field.fromJSON(json, [category]); expect(field).to.matchSnapshot(); }); it("creates valid NestedContentField from valid JSON with `relationshipMeaning`", () => { const category = createTestCategoryDescription(); const json = createTestNestedContentField({ category, nestedFields: [createTestSimpleContentField({ category })], relationshipMeaning: RelationshipMeaning.SameInstance, }).toJSON(); const field = Field.fromJSON(json, [category]); expect(field).to.matchSnapshot(); }); it("returns undefined for undefined JSON", () => { const item = NestedContentField.fromJSON(undefined, []); expect(item).to.be.undefined; }); }); describe("rebuildParentship / resetParentship", () => { it("creates and resets parentship of self and nested fields", () => { const field1 = createTestSimpleContentField(); const field2 = createTestNestedContentField({ nestedFields: [field1] }); const field3 = createTestNestedContentField({ nestedFields: [field2] }); field2.rebuildParentship(field3); expect(field3.parent).to.be.undefined; expect(field2.parent).to.eq(field3); expect(field1.parent).to.eq(field2); field3.resetParentship(); expect(field3.parent).to.be.undefined; expect(field2.parent).to.be.undefined; expect(field1.parent).to.be.undefined; }); }); describe("clone", () => { it("returns exact copy of itself", () => { const field = createTestNestedContentField({ nestedFields: [createTestSimpleContentField()] }); const clone = field.clone(); expect(clone).to.be.instanceOf(NestedContentField); expect(clone.toJSON()).to.deep.eq(field.toJSON()); }); }); }); describe("FieldDescriptor", () => { describe("type guards", () => { it("correctly checks 'Name' descriptor", () => { expect(FieldDescriptor.isNamed({ type: FieldDescriptorType.Name, fieldName: "test", })).to.be.true; expect(FieldDescriptor.isNamed({ type: FieldDescriptorType.Properties, properties: [], pathFromSelectToPropertyClass: [], })).to.be.false; }); it("correctly checks 'Properties' descriptor", () => { expect(FieldDescriptor.isProperties({ type: FieldDescriptorType.Name, fieldName: "test", })).to.be.false; expect(FieldDescriptor.isProperties({ type: FieldDescriptorType.Properties, properties: [{ class: "test", name: "", }], pathFromSelectToPropertyClass: [], })).to.be.true; }); }); });
the_stack
"use strict"; import { UseCaseFunction } from "../src/FunctionalUseCaseContext"; import * as assert from "assert"; import { CompletedPayload, Context, DidExecutedPayload, Dispatcher, Payload, Store, StoreGroup, UseCase } from "../src"; import { InitializedPayload } from "../src/payload/InitializedPayload"; import { createStore, MockStore } from "./helper/create-new-store"; import { SinonStub } from "sinon"; const sinon = require("sinon"); const createAsyncChangeStoreUseCase = (store: MockStore<any>) => { class ChangeTheStoreUseCase extends UseCase { execute() { return Promise.resolve().then(() => { const newState = { a: {} }; store.updateStateWithoutEmit(newState); }); } } return new ChangeTheStoreUseCase(); }; const createChangeStoreUseCase = (store: MockStore<any>) => { class ChangeTheStoreUseCase extends UseCase { execute() { const newState = { a: {} }; store.updateStateWithoutEmit(newState); } } return new ChangeTheStoreUseCase(); }; describe("StoreGroup", function () { describe("constructor(map)", () => { it("throw error when invalid arguments", () => { assert.throws(() => { // @ts-ignore new StoreGroup(null); }); assert.throws(() => { // @ts-ignore new StoreGroup(); }); assert.throws(() => { new StoreGroup([] as any); }); assert.throws(() => { new StoreGroup({ a: 1, b: 2 } as any); }); }); it("support stateName and store mapping ", () => { class AStateStore extends Store { getState() { return "a"; } } class BStateStore extends Store { getState() { return "b"; } } const aStore = new AStateStore(); const bStore = new BStateStore(); const storeGroup = new StoreGroup({ a: aStore, b: bStore }); assert.deepEqual(storeGroup.getState(), { a: "a", b: "b" }); }); }); describe("#emitChange", function () { describe("when any store is not changed", function () { it("should not call onChange", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: store }); let isCalled = false; // then storeGroup.onChange(() => { isCalled = true; }); // when storeGroup.emitChange(); // But any store is not changed assert.ok(isCalled === false); }); }); }); describe("#onChange", function () { it("when actually store's state is changed", () => { it("call onChange handler", () => { const store = createStore({ name: "AStore", state: 1 }); const storeGroup = new StoreGroup({ a: store }); let isCalled = false; // then storeGroup.onChange(() => { isCalled = true; }); // when store.updateState(2); assert.ok(isCalled); }); }); describe("when UseCase never change any store", function () { it("should not be called", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: store }); let isCalled = false; // then storeGroup.onChange(() => { isCalled = true; }); // when const useCase = new (class NopeUseCase extends UseCase { execute() { // not change any store } })(); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); return context .useCase(useCase) .execute() .then(() => { assert.ok(isCalled === false); }); }); }); describe("onChange(changingStores)", () => { it("should changingStores are changed own state", () => { const storeA = createStore({ name: "AStore" }); const storeB = createStore({ name: "BStore" }); const storeGroup = new StoreGroup({ AStore: storeA, BStore: storeB }); let changedStores: Store[] = []; storeGroup.onChange((changingStores) => { changedStores = changingStores; }); // when class ChangeUseCase extends UseCase { execute() { storeA.updateState({ a: 1 }); storeB.updateState({ b: 2 }); } } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // when const useCase = new ChangeUseCase(); return context .useCase(useCase) .execute() .then(() => { assert.equal(changedStores.length, 2); // no specify in order assert.deepEqual(changedStores.sort(), [storeA, storeB].sort()); }); }); }); // sync describe("when SyncUseCase change the store", function () { it("should be called by sync", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ AStore: store }); let isCalled = false; // then storeGroup.onChange(() => { isCalled = true; }); // when const useCase = createChangeStoreUseCase(store); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); context.useCase(useCase).execute(); // sync change!!! assert.ok(isCalled); }); }); // async describe("when ASyncUseCase change the store", function () { it("should be called by async", function () { const store = createStore({ name: "" }); const storeGroup = new StoreGroup({ AStore: store }); let isCalled = false; storeGroup.onChange(() => { isCalled = true; }); // when const asyncUseCase = createAsyncChangeStoreUseCase(store); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // then const promise = context .useCase(asyncUseCase) .execute() .then(() => { assert.ok(isCalled, "after"); }); // not yet change assert.strictEqual(isCalled, false, "before"); return promise; }); }); describe("when UseCase is nesting", function () { it("should be called by all UseCases", function () { const aStore = createStore({ name: "AStore" }); const bStore = createStore({ name: "BStore" }); const storeGroup = new StoreGroup({ a: aStore, b: bStore }); let onChangeCounter = 0; storeGroup.onChange(() => { onChangeCounter += 1; }); // when const changeBUseCase = createAsyncChangeStoreUseCase(bStore); class ChangeAAndBUseCase extends UseCase { execute() { return this.context .useCase(changeBUseCase) .execute() .then(() => { aStore.updateState({ a: 1 }); }); } } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // then const useCase = new ChangeAAndBUseCase(); return context .useCase(useCase) .execute() .then(() => { assert.equal(onChangeCounter, 2); }); }); describe("when UseCase#dispatch is called", function () { it("should not be called - no changing store", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: store }); let isChanged = false; let dispatchedPayload = null; storeGroup.onChange(() => { isChanged = true; }); // when class DispatchAndFinishAsyncUseCase extends UseCase { execute() { // dispatch event this.dispatch({ type: "DispatchAndFinishAsyncUseCase" }); return new Promise((resolve) => { setTimeout(resolve, 100); }); } } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); context.events.onDispatch((payload) => { dispatchedPayload = payload; }); // when const useCase = new DispatchAndFinishAsyncUseCase(); const resultPromise = context.useCase(useCase).execute(); // then - should not be changed, but it is dispatched assert.ok(isChanged === false); assert.deepEqual(dispatchedPayload, { type: "DispatchAndFinishAsyncUseCase" }); return resultPromise; }); it("should be called by sync", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: store }); let isCalled = false; storeGroup.onChange(() => { isCalled = true; }); // when class DispatchAndFinishAsyncUseCase extends UseCase { execute() { // store is changed store.updateState({ a: 1 }); // dispatch event this.dispatch({ type: "DispatchAndFinishAsyncUseCase" }); return new Promise((resolve) => { setTimeout(resolve, 100); }); } } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // when const useCase = new DispatchAndFinishAsyncUseCase(); const resultPromise = context.useCase(useCase).execute(); // then - should be called by sync assert.ok(isCalled); return resultPromise; }); it("should be called each dispatch", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: store }); let calledCount = 0; storeGroup.onChange(() => { calledCount++; }); // when class DispatchAndFinishAsyncUseCase extends UseCase { execute() { // 1 store.updateState({ a: 1 }); this.dispatch({ type: "DispatchAndFinishAsyncUseCase" }); // 2 store.updateState({ a: 2 }); this.dispatch({ type: "DispatchAndFinishAsyncUseCase" }); } } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // when const useCase = new DispatchAndFinishAsyncUseCase(); return context .useCase(useCase) .execute() .then(() => { assert.equal(calledCount, 2); }); }); }); }); describe("when UseCase throwing Error", function () { it("should be called", function () { const aStore = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: aStore }); let onChangeCounter = 0; storeGroup.onChange(() => { onChangeCounter += 1; }); // when class FailUseCase extends UseCase { execute() { aStore.updateState({ a: 1 }); return Promise.reject(new Error("emit change but fail UseCase")); } } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // then const useCase = new FailUseCase(); return context .useCase(useCase) .execute() .catch(() => { assert.equal(onChangeCounter, 1); }); }); }); describe("when UseCase call `throwError()", function () { it("should be called", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: store }); let isCalled = false; // then storeGroup.onChange(() => { isCalled = true; }); // when const useCase = new (class ThrowErrorUseCase extends UseCase { execute() { store.updateState({ a: 1 }); // dispatch event this.throwError(new Error("error message")); } })(); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); return context .useCase(useCase) .execute() .then(() => { assert.ok(isCalled); }); }); }); describe("WhiteBox testing", function () { it("should thin out change events at once", function () { const aStore = createStore({ name: "AStore" }); const bStore = createStore({ name: "BStore" }); const storeGroup = new StoreGroup({ a: aStore, b: bStore }); class ChangeABUseCase extends UseCase { execute() { aStore.updateStateWithoutEmit({ a: 1 }); aStore.emitChange(); // *1 bStore.updateStateWithoutEmit({ b: 1 }); bStore.emitChange(); // *2 } } const useCase = new ChangeABUseCase(); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // then - called change handler a one-time let calledCount = 0; storeGroup.onChange((changedStores) => { calledCount++; assert.equal(changedStores.length, 2); }); // when return context .useCase(useCase) .execute() .then(() => { // collect up *1 and *2 // Store#onChange in StoreGroup only add changing queue. assert.equal(calledCount, 1, "onChange is called just once"); }); }); describe("when the UseCase don't return a promise", () => { it("StoreGroup#emitChange is called just one time", function () { const aStore = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: aStore }); class ChangeAUseCase extends UseCase { execute() { aStore.updateState({ a: 1 }); } } const useCase = new ChangeAUseCase(); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // then - called change handler a one-time let calledCount = 0; // override storeGroup.onChange(() => { calledCount++; }); // when return context .useCase(useCase) .execute() .then(() => { assert.equal(calledCount, 1, "StoreGroup#emitChange is called just once"); }); }); }); }); describe("Sync Change and Async Change in Edge case", function () { /* This useCase should update twice execute(){ model.count = 1; *1 // DidExecute -> refresh return Promise.resolve().then(() => { model.count = 2; * 1 }); // Complete -> refresh } */ it("should pass twice update scenario", function () { const store = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: store }); const asyncUseCase = createAsyncChangeStoreUseCase(store); class ChangeTheStoreUseCase extends UseCase { execute() { store.updateState({ a: 1 }); return this.context.useCase(asyncUseCase).execute(); // complete => update } // didExecute => update } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // count let calledCount = 0; storeGroup.onChange(() => { calledCount++; }); const useCase = new ChangeTheStoreUseCase(); // when return context .useCase(useCase) .execute() .then(() => { assert.equal(calledCount, 2); }); }); }); describe("onChange calling flow example", function () { it("should call onChange in order", function () { const aStore = createStore({ name: "AStore" }); const bStore = createStore({ name: "BStore" }); const cStore = createStore({ name: "CStore" }); const storeGroup = new StoreGroup({ a: aStore, b: bStore, c: cStore }); class ParentUseCase extends UseCase { execute() { const aUseCase = new ChildAUseCase(); const bUseCase = new ChildBUseCase(); return Promise.all([ this.context.useCase(aUseCase).execute(), this.context.useCase(bUseCase).execute() ]).then(() => { cStore.updateState({ c: 1 }); }); } } class ChildAUseCase extends UseCase { execute() { return new Promise((resolve) => { aStore.updateState({ a: 1 }); resolve(); }); } } class ChildBUseCase extends UseCase { execute() { return new Promise((resolve) => { bStore.updateState({ b: 1 }); resolve(); }); } } const useCase = new ParentUseCase(); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // then - called change handler a one-time let actualChangedStores: Store[] = []; storeGroup.onChange((changedStores) => { actualChangedStores = actualChangedStores.concat(changedStores); }); // when return context .useCase(useCase) .execute() .then(() => { assert.equal(actualChangedStores.length, 3); assert.deepEqual(actualChangedStores, [aStore, bStore, cStore]); }); }); }); describe("When StoreGroup calling Store#receivePayload", function () { it("should call count is necessary and sufficient for performance", function () { class AStore extends Store<any> { public receivedPayloadList: any[]; constructor() { super(); this.state = {}; this.receivedPayloadList = []; } receivePayload(payload: any) { this.receivedPayloadList.push(payload); if (payload.type === "test") { this.setState({ newKey: "update" }); } } getState() { return this.state; } } const aStore = new AStore(); const storeGroup = new StoreGroup({ a: aStore }); // when const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); class ExamplePayload extends Payload { type = "test"; } const useCaseSync: UseCaseFunction = ({ dispatcher }) => { return () => { dispatcher.dispatch(new ExamplePayload()); }; }; const useCaseAsync: UseCaseFunction = ({ dispatcher }) => { return () => { dispatcher.dispatch(new ExamplePayload()); return Promise.resolve(); }; }; // calling order of Store#receivedPay const expectedReceivedPayloadList = [ // StoreGroup Initialize InitializedPayload, // Sync UseCase ExamplePayload, DidExecutedPayload, // CompletedPayload is not called because sync useCase is already finished, // Async UseCase, ExamplePayload, DidExecutedPayload, CompletedPayload ]; // then return context .useCase(useCaseSync) .execute() .then(() => { return context.useCase(useCaseAsync).execute(); }) .then(() => { assert.strictEqual( aStore.receivedPayloadList.length, expectedReceivedPayloadList.length, "should be equal receive payload length" ); aStore.receivedPayloadList.forEach((payload, index) => { const ExpectedPayloadClass = expectedReceivedPayloadList[index]; assert.ok( payload instanceof ExpectedPayloadClass, `${payload.type} instanceof ${ExpectedPayloadClass}` ); }); }); }); }); describe("when Store#emitChange before receivePayload", function () { it("arguments includes the store", function () { const aStore = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: aStore }); let actualStores: Store[] = []; storeGroup.onChange((stores) => { actualStores = actualStores.concat(stores); }); // when const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // This useCas reset actualStores, // It aim to detect storeChanging in the between did and completed const useCase = () => { return () => { actualStores = []; aStore.updateState({ a: "new value" }); }; }; // then return context .useCase(useCase) .execute() .then(() => { assert.deepEqual(actualStores, [aStore]); }); }); }); describe("when Store is changed in receivePayload", function () { it("arguments includes the store", function () { class AStore extends Store { constructor() { super(); this.state = { key: "initial" }; } receivePayload(payload: any) { if (payload instanceof InitializedPayload) { return; } this.state = { key: "receivePayload" }; } getState() { return this.state; } } const aStore = new AStore(); const storeGroup = new StoreGroup({ a: aStore }); let actualStores: Store[] = []; storeGroup.onChange((stores) => { actualStores = actualStores.concat(stores); }); // when const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // This useCas reset actualStores, // It aim to detect storeChanging in the between did and completed const useCase = () => { return () => { actualStores = []; }; }; // then return context .useCase(useCase) .execute() .then(() => { assert.deepEqual(actualStores, [aStore]); }); }); }); }); describe("#getState", function () { it("should return a single state object", function () { class AStore extends Store { getState() { return "a value"; } } class BStore extends Store { getState() { return "b value"; } } const aStore = new AStore(); const bStore = new BStore(); const storeGroup = new StoreGroup({ a: aStore, b: bStore }); // when - a,b emit change at same time const state = storeGroup.getState(); // then - return a single state object that contain each store and merge assert.deepEqual(state, { a: "a value", b: "b value" }); }); describe("when getState() return State object", function () { it("should return a single state has {<key>: state} of return Store#getState", function () { class AState {} class AStore extends Store { getState() { return new AState(); } } class BState {} class BStore extends Store { getState() { return new BState(); } } const aStore = new AStore(); const bStore = new BStore(); const storeGroup = new StoreGroup({ a: aStore, b: bStore }); // when - a,b emit change at same time const state = storeGroup.getState(); // then - return a single state object that contain each store and merge const keys = Object.keys(state); assert.ok(keys.indexOf("a") !== -1); assert.ok(state["a"] instanceof AState); assert.ok(state["b"] instanceof BState); }); }); }); describe("Warning", () => { let consoleErrorStub: SinonStub; beforeEach(() => { consoleErrorStub = sinon.stub(console, "error"); }); afterEach(() => { consoleErrorStub.restore(); }); it("should check that a Store returned state immutability", function () { const store = createStore({ name: "AStore" }); class EmitStoreUseCase extends UseCase { execute() { // When the store is not changed, but call emitChange store.emitChange(); } } const context = new Context({ dispatcher: new Dispatcher(), store: new StoreGroup({ a: store }) }); return context .useCase(new EmitStoreUseCase()) .execute() .then(() => { assert.equal(consoleErrorStub.callCount, 1, "It throw immutable warning"); }); }); // See https://github.com/almin/almin/pull/205 it("State changing: A -> B -> A by Store#emitChange should not warn", function () { const state = { value: "init" }; class MyStore extends Store { constructor() { super(); this.state = Object.assign({}, state); } checkUpdate() { this.setState(Object.assign({}, state)); } getState() { return this.state; } } const store = new MyStore(); const storeGroup = new StoreGroup({ a: store }); class TransactionUseCase extends UseCase { execute() { // 1. change state.value = "next"; // emit change store.checkUpdate(); // 2. revert state.value = "init"; // <= same with initial state // re-emit change: // result: the `store` is not changed store.checkUpdate(); } } const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // init -> next -> init return context .useCase(new TransactionUseCase()) .execute() .then(() => { return context.useCase(new TransactionUseCase()).execute(); }) .then(() => { assert.equal( consoleErrorStub.callCount, 0, `This does call emitChange() warning should not be called. init -> next -> init in a execution of UseCase should be valid. Something wrong implementation of calling Store#emitChange at multiple` ); }); }); it("should check that a Store's state is changed but shouldStateUpdate return false", function () { class AStore extends Store { constructor() { super(); this.state = { a: "value" }; } getState() { return this.state; } } const store = new AStore(); const storeGroup = new StoreGroup({ a: store }); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // When the store is not changed, but call emitChange const useCase: UseCaseFunction = () => { return () => { // reference is change but shall-equal return false store.state = { a: "value" }; }; }; return context .useCase(useCase) .execute() .then(() => { assert.ok(consoleErrorStub.calledOnce); }); }); describe("when strict mode", () => { it("should not show warning if update store inside of receivePayload", function () { class AStore extends Store { constructor() { super(); this.state = { a: "value" }; } // Good: Update this store inside of receivePayload receivePayload(payload: any) { if (payload.type === "UPDATE_A") { this.setState(payload.body); } } getState() { return this.state; } } const store = new AStore(); const storeGroup = new StoreGroup({ a: store }); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup, options: { strict: true } }); const updateAStoreUseCase: UseCaseFunction = ({ dispatcher }) => { return () => { dispatcher.dispatch({ type: "UPDATE_A", body: "new value" }); }; }; return context .useCase(updateAStoreUseCase) .execute() .then(() => { assert.strictEqual(consoleErrorStub.callCount, 0); }); }); it("should show warning if update store outside of receivePayload", function () { class AStore extends Store { constructor() { super(); this.state = { a: "value" }; } getState() { return this.state; } } const store = new AStore(); const storeGroup = new StoreGroup({ a: store }); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup, options: { strict: true } }); const updateAStoreUseCase: UseCaseFunction = () => { return () => { // Bad: update state outside of receivePayload store.setState({ a: "new value" }); }; }; return context .useCase(updateAStoreUseCase) .execute() .then(() => { assert.strictEqual(consoleErrorStub.callCount, 1, "should not update state in a UseCase"); }); }); }); describe("Not support warning case", () => { it("directly modified and emitChange is mixed, we can't show warning", function () { class AStore extends Store { constructor() { super(); this.state = { a: "value" }; } getState() { return this.state; } } const store = new AStore(); const storeGroup = new StoreGroup({ a: store }); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); // When the store is not changed, but call emitChange const useCase: UseCaseFunction = () => { return () => { // emitChange style store.setState({ a: "1" }); // directly modified style store.state = { a: "value" }; }; }; return context .useCase(useCase) .execute() .then(() => { assert.equal(consoleErrorStub.callCount, 0, "Can't support this case"); }); }); }); }); describe("#release", function () { it("release onChange handler", function () { const aStore = createStore({ name: "AStore" }); const bStore = createStore({ name: "BStore" }); const storeGroup = new StoreGroup({ a: aStore, b: bStore }); // then - called change handler a one-time let isCalled = false; storeGroup.onChange(() => { isCalled = true; }); storeGroup.release(); storeGroup.emitChange(); assert.ok(!isCalled); }); }); describe("#receivePayload", () => { it("UseCase dispatch payload -> Store should receive it", () => { class AState { count: number; constructor(count: number) { this.count = count; } reduce(payload: any) { switch (payload.type) { case "increment": return new AState(this.count + 1); case "decrement": return new AState(this.count - 1); default: return this; } } } class AStore extends Store { constructor() { super(); this.state = new AState(0); } /** * update state * @param {Payload} payload */ receivePayload(payload: any) { this.state = this.state.reduce(payload); } getState() { return this.state; } } class IncrementUseCase extends UseCase { execute() { this.dispatch({ type: "increment" }); } } class DecrementUseCase extends UseCase { execute() { this.dispatch({ type: "decrement" }); } } const aStore = new AStore(); const storeGroup = new StoreGroup({ a: aStore }); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); const initialState = context.getState(); assert.ok(initialState.a instanceof AState); assert.strictEqual(initialState.a.count, 0); return context .useCase(new IncrementUseCase()) .execute() .then(() => { const state = context.getState(); assert.ok(state.a instanceof AState); assert.strictEqual(state.a.count, 1); }) .then(() => { return context.useCase(new DecrementUseCase()).execute(); }) .then(() => { const state = context.getState(); assert.ok(state.a instanceof AState); assert.strictEqual(state.a.count, 0); }); }); }); });
the_stack
import { renderDOM } from './renderDOM'; import { VNode, b, PropsArg, ChildArg, createTextVNode } from './createElement'; import { MachineComponent, SFC, Effect, DeriveTargetFunction, } from './component'; import { diff } from './diff'; import { RouTrie, Params } from './router'; import { machineRegistry, MachineInstance, machinesThatTransitioned, renderType, machineDuty, } from './machineRegistry'; let isTransitioning = false; let currentRootComponent: MachineComponent | SFC; let currentVRoot: VNode; let $root: HTMLElement; function transitionMachines( event: { type: string | number; [key: string]: any }, target = '*' ): void { let i: number; let l: number; const allEffects: Array<[Effect, MachineInstance]> = []; /** * logic for non-wildcard events (there is a named target) * * - find machine target * - it it exists, check if it has a spec/handler for its current state * - if so, add check if that spec/handler has a transition for the event * - it it does, check if cond resolves to true (or doesn't exist) * - if so, transition the machine to its next state and execute effects/effects */ if (target !== '*') { const machineInstance = machineRegistry.get(target); if (machineInstance) transitionMachine(machineInstance, event, allEffects); } else { /** high-level logic for wildcard events; check every machine to * see if it listens to this event in its current state. */ /** execute effects after transitions + onEntry + onExit. * using an array of tuples instead of a map so that the * same effect function can be used for multiple machine instances * * batch all effects for each event for executing so that all machines will * have transitioned before "nested"/"ping pong" events work as expected! * */ for (const [, machineInstance] of machineRegistry) { transitionMachine(machineInstance, event, allEffects); } } i = 0; l = allEffects.length; let machineInstance: MachineInstance; while (i < l) { machineInstance = allEffects[i][1]; allEffects[i++][0](machineInstance.x, event, machineInstance.id); } } function transitionMachine( machineInstance: MachineInstance, event: { type: string | number; [key: string]: any }, allEffects: Array<[Effect, MachineInstance]> = [] ): void { // check if there is a catch all listener for this event (root-level "on") const rootOn = machineInstance.s.on; let i: number, l: number, t = event.type; if (rootOn) { /** check if this machine always listens to this eventType */ const transitionHandler = rootOn[t]; /** * NEXT TASK: refactoring to support shorthand string target * * - common logic btwn root handler and state handler. * - if the whole handler is a string, go to next state and handle only onentry. * actually, if the handler is a string, the current state may still have a transition. * - else, handle both onexit and onentry * * tbh, just add this logic to "take to next state" */ if ( transitionHandler && (!transitionHandler.if || transitionHandler.if(machineInstance.x, event)) ) { machinesThatTransitioned.set(machineInstance.id, machineInstance.v.h!); const effects = transitionHandler.do; if (effects) if (typeof effects === 'function') allEffects.push([effects, machineInstance]); else { i = 0; l = effects.length; while (i < l) allEffects.push([effects[i++], machineInstance]); } // take to next state if target if (transitionHandler.to) takeToNextState( transitionHandler.to, machineInstance, machineInstance.s.when[machineInstance.st], allEffects ); } } /** check if the machine has a handler/behavior spec * for its current state (it has to if written in TS) */ const stateHandler = machineInstance.s.when[machineInstance.st]; /** for js users who may specify invalid states */ /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { if (!stateHandler) { throw TypeError( `The specified state handler for '${machineInstance.st}' does not exist on ${machineInstance.id}` ); } } if (stateHandler.on) { /** check if this machine listens to this eventType in its current state */ const transitionHandler = stateHandler.on[t]; if ( transitionHandler && (!transitionHandler.if || transitionHandler.if(machineInstance.x, event)) ) { machinesThatTransitioned.set(machineInstance.id, machineInstance.v.h!); const targetState = transitionHandler.to; const effects = transitionHandler.do; if (targetState) takeToNextState(targetState, machineInstance, stateHandler, allEffects); if (effects) if (typeof effects === 'function') allEffects.push([effects, machineInstance]); else { i = 0; l = effects.length; while (i < l) allEffects.push([effects[i++], machineInstance]); } } } } type StateHandler = { on?: any; entry?: any; exit?: any; }; function takeToNextState( targetState: string | DeriveTargetFunction<any, any>, machineInstance: MachineInstance, currentStateHandler: StateHandler, allEffects: Array<[Effect, MachineInstance]> = [] ): void { // check for target function. standardized to string let stdTargetState: string; if (typeof targetState === 'function') stdTargetState = targetState(machineInstance.x, machineInstance.s); else stdTargetState = targetState; if (stdTargetState !== machineInstance.st) { // only do anything if targetState !== current machine instance state const nextStateHandler = machineInstance.s.when[stdTargetState]; if (nextStateHandler) { machineInstance.st = stdTargetState; /** * * the pseudocode for the code below: * * machine.spec.states[oldState]?.exit() * machine.spec.states[target]?.entry() * * */ currentStateHandler.exit && allEffects.push([currentStateHandler.exit, machineInstance]); nextStateHandler.entry && allEffects.push([nextStateHandler.entry, machineInstance]); machinesThatTransitioned.set(machineInstance.id, machineInstance.v.h!); } else { /** for js users who may specify invalid targets */ /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { throw TypeError( `The specified target (${targetState}) for this transition (${machineInstance.st} => ${targetState}) does not exist on your ${machineInstance.id}` ); } } } } export function emit( event: { type: string | number; [key: string]: any }, target: string = '*' ): void { // make sure to set this for free 'memo' type optimizations for machines! renderType.t = 't'; /** * if already transitioning, transition machines, but don't start render process. * */ if (isTransitioning) { transitionMachines(event, target); return; } isTransitioning = true; transitionMachines(event, target); isTransitioning = false; /** * no rerenders if no machines transitioned. handle global * and targeted events in (almost) the same way */ if (machinesThatTransitioned.size === 0) return; /** array of tuples [instanceId, nodeDepth] */ const idNodeDepth: [string, number][] = []; for (const kv of machinesThatTransitioned) { idNodeDepth.push(kv); } let j = idNodeDepth.length; /** sort machines that transitioned in DESC order, iterate backwards, * so you render machines from top to bottom! * don't need to sort it if there's only one machine (e.g. targeted events) * */ j > 1 && idNodeDepth.sort((a, b) => b[1] - a[1]); while (j--) { const machInst = machineRegistry.get(idNodeDepth[j][0]); // the machine instance may not exist anymore (if an ancestor node stopped rendering it, for example) if (machInst) { let vNode: VNode | null = machInst.s.render( machInst.st, machInst.x, machInst.id, machInst.c ); // if (vNode == null) vNode = createTextVNode(''); save some bytes w/ short-circuit // machine.v.c.h! -> vnode.h -> node depth diff(machInst.v.c, vNode || createTextVNode(''), null, machInst.v.c.h!); machInst.v.c = vNode as VNode; } } machineDuty(); } export function router<Props extends PropsArg = any>( routerSchema: RouterSchema<Props>, prefix = '' ): SFC<Props & { children?: any }> { /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { if (typeof prefix !== 'string') throw TypeError('prefix must be a string'); } const myTrieRouter = new RouTrie<RouterCallback<any>>(); prefix && (prefix = prefix[prefix.length - 1] === '/' ? prefix.slice(0, prefix.length - 1) : prefix); for (const key in routerSchema) { /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { if (key[0] !== '*' && key[0] !== '/') throw SyntaxError('routes should begin with /'); } myTrieRouter.i(`${prefix}${key === '/' ? '' : key}`, routerSchema[key]); } function routerComp(props: Props, children: ChildArg): VNode | null { const match = myTrieRouter.f(location.pathname); // checking for handler for js users. (h = handler, p = params/route params) return match && match.h ? match.h(match.p, props, children) : null; } return routerComp; } /** * * Routing API * * process for route changes * - change the actual route, push state to browser. (omit this step for onpopstate) * - emit new_route event to machines * - rerender regardless of machine transitions; remember, routers are functional * * */ function newRoute(): void { // can't use emit here because we have to force rerender! routers are functional components, not machines. // eslint-disable-next-line @typescript-eslint/no-use-before-define transitionMachines({ type: 'NEW_ROUTE', location: { pathname: location.pathname, search: location.search, state: history.state, }, }); renderType.t = 'r'; // rerender const vNode: VNode | null = b(currentRootComponent, {}); diff(currentVRoot, vNode, $root, 0); currentVRoot = vNode; machineDuty(); } window.onpopstate = newRoute; function link(path: string, state: any = null): void { /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { if (typeof path !== 'string') throw new TypeError('link path must be a string'); } history.pushState(state, '', path[0] === '/' ? path : `/${path}`); newRoute(); } /** programmatic routing */ export function linkTo(path: string, state: any = null): void { /** wait for transitions/rerenders to complete. this logic is only in place because of the * possibility that a state transition could trigger a redirect. not really a good pattern, * but should be supported/behave in the expected manner. * * NOTE: this was originally `setTimeout`, but queuing a microtask prevents * the browser from rendering/painting twice for what is essentially one user event */ isTransitioning ? queueMicrotask(() => link(path, state)) : link(path, state); } /** link component */ export const Link: SFC<{ to: string | { path: string; state: any }; key?: string | number; onClick?: (e: JSX.TargetedEvent<HTMLAnchorElement, MouseEvent>) => void; target?: string; children?: any; ref?: (el: HTMLAnchorElement) => void; }> = (props, children) => { const path = typeof props.to === 'string' ? props.to : props.to.path; const o = props.onClick, target = props.target; const onClickOverride = ( e: JSX.TargetedEvent<HTMLAnchorElement, MouseEvent> ) => { if (o) o(e); /** * conditions from: * https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/Link.js#L43 * * behave like a normal anchor tag to open in new tabs etc. */ if ( !e.defaultPrevented && e.button === 0 && (!props.target || props.target === '_self') && !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) ) { e.preventDefault(); linkTo(path, typeof props.to === 'object' && props.to.state); } }; return b( 'a', { href: path, onClick: onClickOverride, target: target, key: props.key }, children ); }; export function mount( rootComponent: MachineComponent | SFC, $target: HTMLElement ): HTMLElement { machineRegistry.clear(); // have to render the whole tree on mount ofc, so making it behave like a route event works! renderType.t = 'r'; const vNode: VNode = b(rootComponent, {}); $root = renderDOM(vNode, 0) as HTMLElement; /** * used to be $target.replaceWith($root), but that isn't supported on some broswers released * as recently as 2016, so this method is good for now. just be sure to inform users to provide * a nice empty div for baahu to append to! */ $target.appendChild($root); currentRootComponent = rootComponent; currentVRoot = vNode; machineDuty(); return $root; } export type RouterSchema<Props extends PropsArg = any> = { [path: string]: RouterCallback<Props>; }; export type RouterCallback<Props extends PropsArg = any> = ( params: Params, props: Props, children: ChildArg ) => VNode;
the_stack
* @module Core */ import { ECSqlStatement, IModelDb } from "@itwin/core-backend"; import { assert, DbResult, Id64, Id64String } from "@itwin/core-bentley"; import { CategoryDescription, Content, ElementProperties, ElementPropertiesItem, ElementPropertiesPrimitiveArrayPropertyItem, ElementPropertiesPropertyItem, ElementPropertiesStructArrayPropertyItem, IContentVisitor, Item, PresentationError, PresentationStatus, ProcessFieldHierarchiesProps, ProcessMergedValueProps, ProcessPrimitiveValueProps, PropertyValueFormat, StartArrayProps, StartCategoryProps, StartContentProps, StartFieldProps, StartItemProps, StartStructProps, traverseContent, } from "@itwin/presentation-common"; /** @internal */ export const buildElementsProperties = (content: Content | undefined): ElementProperties[] => { if (!content || content.contentSet.length === 0) return []; const builder = new ElementPropertiesBuilder(); traverseContent(builder, content); return builder.items; }; /** @internal */ export function getElementsCount(db: IModelDb, classNames?: string[]) { const filter = createElementsFilter("e", classNames); const query = ` SELECT COUNT(e.ECInstanceId) FROM bis.Element e ${filter ? `WHERE ${filter}` : ""} `; return db.withPreparedStatement(query, (stmt: ECSqlStatement) => { return stmt.step() === DbResult.BE_SQLITE_ROW ? stmt.getValue(0).getInteger() : 0; }); } /** @internal */ export function* iterateElementIds(db: IModelDb, classNames?: string[], limit?: number) { let lastElementId; while (true) { const result = queryElementIds(db, classNames, limit, lastElementId); yield result.ids; lastElementId = result.lastElementId; if (!lastElementId) break; } } function queryElementIds(db: IModelDb, classNames?: string[], limit?: number, lastElementId?: Id64String) { function createWhereClause() { const classFilter = createElementsFilter("e", classNames); const elementFilter = lastElementId ? `e.ECInstanceId > ?` : undefined; if (!classFilter && !elementFilter) return ""; if (classFilter && elementFilter) return `WHERE ${classFilter} AND ${elementFilter}`; return `WHERE ${classFilter ?? ""} ${elementFilter ?? ""}`; } const query = ` SELECT e.ECInstanceId elId, eSchemaDef.Name || ':' || eClassDef.Name elClassName FROM bis.Element e LEFT JOIN meta.ECClassDef eClassDef ON eClassDef.ECInstanceId = e.ECClassId LEFT JOIN meta.ECSchemaDef eSchemaDef ON eSchemaDef.ECInstanceId = eClassDef.Schema.Id ${createWhereClause()} ORDER BY e.ECInstanceId ASC `; return db.withPreparedStatement(query, (stmt: ECSqlStatement) => { if (lastElementId) stmt.bindId(1, lastElementId); const ids = new Map<string, string[]>(); let currentClassName = ""; let currentIds: string[] = []; let loadedIds = 0; while (stmt.step() === DbResult.BE_SQLITE_ROW) { const row = stmt.getRow(); if (!row.elId || !row.elClassName) continue; if (currentClassName !== row.elClassName) { currentClassName = row.elClassName; const existingIds = ids.get(row.elClassName); if (!existingIds) { currentIds = []; ids.set(row.elClassName, currentIds); } else { currentIds = existingIds; } } currentIds.push(row.elId); loadedIds++; if (limit && loadedIds >= limit) return { ids, lastElementId: row.elId }; } return { ids, lastElementId: undefined }; }); } function createElementsFilter(elementAlias: string, classNames?: string[]) { if (classNames === undefined || classNames.length === 0) return undefined; // check if list contains only valid class names const classNameRegExp = new RegExp(/^[\w]+[.:][\w]+$/); const invalidName = classNames.find((name) => !name.match(classNameRegExp)); if (invalidName) { throw new PresentationError(PresentationStatus.InvalidArgument, `Encountered invalid class name - ${invalidName}. Valid class name formats: "<schema name or alias>.<class name>", "<schema name or alias>:<class name>"`); } return `${elementAlias}.ECClassId IS (${classNames.join(",")})`; } interface IPropertiesAppender { append(label: string, item: ElementPropertiesItem): void; finish(): void; } class ElementPropertiesAppender implements IPropertiesAppender { private _propertyItems: { [label: string]: ElementPropertiesItem } = {}; private _categoryItemAppenders: { [categoryName: string]: IPropertiesAppender } = {}; constructor(private _item: Item, private _onItemFinished: (item: ElementProperties) => void) { } public append(label: string, item: ElementPropertiesItem): void { this._propertyItems[label] = item; } public finish(): void { // eslint-disable-next-line guard-for-in for (const categoryName in this._categoryItemAppenders) { const appender = this._categoryItemAppenders[categoryName]; appender.finish(); } this._onItemFinished({ class: this._item.classInfo?.label ?? "", id: this._item.primaryKeys[0]?.id ?? Id64.invalid, label: this._item.label.displayValue, items: this._propertyItems, }); } public getCategoryAppender(parentAppender: IPropertiesAppender, category: CategoryDescription): IPropertiesAppender { let appender = this._categoryItemAppenders[category.name]; if (!appender) { appender = new CategoryItemAppender(parentAppender, category); this._categoryItemAppenders[category.name] = appender; } return appender; } } class CategoryItemAppender implements IPropertiesAppender { private _items: { [label: string]: ElementPropertiesItem } = {}; constructor(private _parentAppender: IPropertiesAppender, private _category: CategoryDescription) { } public append(label: string, item: ElementPropertiesItem): void { this._items[label] = item; } public finish(): void { if (Object.keys(this._items).length === 0) return; this._parentAppender.append(this._category.label, { type: "category", items: this._items, }); } } class ArrayItemAppender implements IPropertiesAppender { private _items: ElementPropertiesPropertyItem[] = []; constructor(private _parentAppender: IPropertiesAppender, private _props: StartArrayProps) { } public append(_label: string, item: ElementPropertiesItem): void { assert(item.type !== "category"); this._items.push(item); } public finish(): void { assert(this._props.valueType.valueFormat === PropertyValueFormat.Array); if (this._props.valueType.memberType.valueFormat === PropertyValueFormat.Primitive) this._parentAppender.append(this._props.hierarchy.field.label, this.createPrimitivesArray()); else this._parentAppender.append(this._props.hierarchy.field.label, this.createStructsArray()); } private createPrimitivesArray(): ElementPropertiesPrimitiveArrayPropertyItem { return { type: "array", valueType: "primitive", values: this._items.map((item) => { assert(item.type === "primitive"); return item.value; }), }; } private createStructsArray(): ElementPropertiesStructArrayPropertyItem { return { type: "array", valueType: "struct", values: this._items.map((item) => { assert(item.type === "struct"); return item.members; }), }; } } class StructItemAppender implements IPropertiesAppender { private _members: { [label: string]: ElementPropertiesPropertyItem } = {}; constructor(private _parentAppender: IPropertiesAppender, private _props: StartStructProps) { } public append(label: string, item: ElementPropertiesItem): void { assert(item.type !== "category"); this._members[label] = item; } public finish(): void { assert(this._props.valueType.valueFormat === PropertyValueFormat.Struct); this._parentAppender.append(this._props.hierarchy.field.label, { type: "struct", members: this._members, }); } } class ElementPropertiesBuilder implements IContentVisitor { private _appendersStack: IPropertiesAppender[] = []; private _items: ElementProperties[] = []; private _elementPropertiesAppender: ElementPropertiesAppender | undefined; public get items(): ElementProperties[] { return this._items; } private get _currentAppender(): IPropertiesAppender { const appender = this._appendersStack[this._appendersStack.length - 1]; assert(appender !== undefined); return appender; } public startContent(_props: StartContentProps): boolean { return true; } public finishContent(): void { } public processFieldHierarchies(_props: ProcessFieldHierarchiesProps): void { } public startItem(props: StartItemProps): boolean { this._elementPropertiesAppender = new ElementPropertiesAppender(props.item, (item) => { this._items.push(item); }); this._appendersStack.push(this._elementPropertiesAppender); return true; } public finishItem(): void { this._appendersStack.pop(); assert(this._elementPropertiesAppender !== undefined); this._elementPropertiesAppender.finish(); this._elementPropertiesAppender = undefined; } public startCategory(props: StartCategoryProps): boolean { assert(this._elementPropertiesAppender !== undefined); this._appendersStack.push(this._elementPropertiesAppender.getCategoryAppender(this._currentAppender, props.category)); return true; } public finishCategory(): void { this._appendersStack.pop(); } public startField(_props: StartFieldProps): boolean { return true; } public finishField(): void { } public startStruct(props: StartStructProps): boolean { this._appendersStack.push(new StructItemAppender(this._currentAppender, props)); return true; } public finishStruct(): void { this._appendersStack.pop()!.finish(); } public startArray(props: StartArrayProps): boolean { this._appendersStack.push(new ArrayItemAppender(this._currentAppender, props)); return true; } public finishArray(): void { this._appendersStack.pop()!.finish(); } public processMergedValue(props: ProcessMergedValueProps): void { this._currentAppender.append(props.mergedField.label, { type: "primitive", value: "", }); } public processPrimitiveValue(props: ProcessPrimitiveValueProps): void { this._currentAppender.append(props.field.label, { type: "primitive", value: props.displayValue?.toString() ?? "", }); } }
the_stack
import { Component, OnInit, } from '@angular/core'; import {MatSlideToggleChange, MatSliderChange} from '@angular/material'; import {DemoSettings} from './modules/convai-checker/convai-checker.component'; import { ConfigurationInput, LoadingIconStyle, ScoreThreshold, DEFAULT_FEEDBACK_TEXT } from './modules/convai-checker/perspective-status.component'; import {ActivatedRoute, Params, Router} from '@angular/router'; import * as _ from 'lodash'; /** Settings about the UI state that should be encoded in the URL. */ export interface UISettings { useCustomColorScheme: boolean; useCustomFeedbackText: boolean; customizeScoreThresholds: boolean; showDemoSettings: boolean; } /** Describes a configuration for demo colors. */ export interface ColorScheme { name: string; colors: string[]; } /** Names of color scheme options for the checker. */ const ColorSchemes = { DEFAULT: 'default', TRAFFIC_LIGHT: 'traffic lights', }; /** Arrays of colors that can be used as colors in a ColorScheme. */ const DEFAULT_COLORS = ['#25C1F9', '#7C4DFF', '#D400F9']; const TRAFFIC_LIGHT_COLORS = ['#4CAF50', '#FDD835', '#D50000']; /** Describes a configuration for feedback text to use in the demo. */ export interface FeedbackTextScheme { name: string; feedbackTextSet: [string, string, string]; } /** Names of feedback text options for the checker. */ const TextFeedbackSchemes = { DEFAULT_FEEDBACK_TEXT: DEFAULT_FEEDBACK_TEXT, PLEASE_REVIEW_FEEDBACK_TEXT: 'Please review before posting.', }; /** * Arrays of feedback text strings that can be used as a feedbackTextSet in a * FeedbackTextScheme. */ const DEFAULT_FEEDBACK_TEST_SET: [string, string, string] = [ DEFAULT_FEEDBACK_TEXT, DEFAULT_FEEDBACK_TEXT, DEFAULT_FEEDBACK_TEXT ]; const PLEASE_REVIEW_FEEDBACK_TEST_SET: [string, string, string] = [ TextFeedbackSchemes.PLEASE_REVIEW_FEEDBACK_TEXT, TextFeedbackSchemes.PLEASE_REVIEW_FEEDBACK_TEXT, TextFeedbackSchemes.PLEASE_REVIEW_FEEDBACK_TEXT ]; function arraysEqual<T>(array1: T[], array2: T[]): boolean { return array1.length === array2.length && array1.every((element, index) => element === array2[index]); } @Component({ selector: 'customizable-demo-form', templateUrl: './customizable-demo-form.component.html', styleUrls: ['./customizable-demo-form.component.css'], }) export class CustomizableDemoFormComponent implements OnInit { /** Whether to show the expanded demo settings. */ showDemoSettings = true; /** Color scheme options. */ colorSchemes: ColorScheme[] = [ {name: ColorSchemes.DEFAULT, colors: DEFAULT_COLORS}, {name: ColorSchemes.TRAFFIC_LIGHT, colors: TRAFFIC_LIGHT_COLORS}, ]; // Color scheme selected from the dropdown menu. selectedColorScheme: ColorScheme = this.colorSchemes[0]; useCustomColorScheme = false; // Color scheme selected with the color pickers. customColorScheme = DEFAULT_COLORS.slice(); /** Score threshold options. */ // Value of the slider; note that the slider is inverted for stylistic // reasons, so when using this value take 100 - sliderValue. sliderValue: number = (1 - ScoreThreshold.NEUTRAL) * 100; // Score thresholds determined from the slider value. sliderScoreNeutralThreshold = ScoreThreshold.NEUTRAL; sliderScoreToxicThreshold = ScoreThreshold.TOXIC; // Custom score thresholds. neutralScoreThreshold = ScoreThreshold.NEUTRAL; toxicScoreThreshold = ScoreThreshold.TOXIC; customizeScoreThresholds = false; /** Loading icon style options. */ loadingIconStyles = [ LoadingIconStyle.CIRCLE_SQUARE_DIAMOND, LoadingIconStyle.EMOJI, LoadingIconStyle.NONE ]; selectedLoadingIconStyle = LoadingIconStyle.CIRCLE_SQUARE_DIAMOND; /** Feedback text options. */ feedbackTextSchemes: FeedbackTextScheme[] = [ { name: TextFeedbackSchemes.DEFAULT_FEEDBACK_TEXT, feedbackTextSet: DEFAULT_FEEDBACK_TEST_SET }, { name: TextFeedbackSchemes.PLEASE_REVIEW_FEEDBACK_TEXT, feedbackTextSet: PLEASE_REVIEW_FEEDBACK_TEST_SET, } ]; // FeedbackTextScheme selected from the dropdown menu. selectedFeedbackTextScheme: FeedbackTextScheme = this.feedbackTextSchemes[0]; // Custom FeedbackTextScheme specified by user input. customFeedbackTextScheme: [string, string, string] = DEFAULT_FEEDBACK_TEST_SET; useCustomFeedbackText = false; /** Other settings. */ // Whether to use the endpoint for the plugin. usePluginEndpoint = false; // URL to use for the plugin endpoint (for debugging and local tests). pluginEndpointUrl = ''; // Whether to show feedback for scores below the neutral threshold. showFeedbackForLowScores = true; // Whether to show feedback for scores above the neutral threshold and below // the toxic threshold. showFeedbackForNeutralScores = true; // The id of the community using the widget. communityId = ''; // The name of the model to use. modelName = ''; // Font family as used in a CSS font-family rule. fontFamily = ''; demoSettings: DemoSettings|null = null; demoSettingsJson = ''; uiSettings: UISettings|null = null; constructor(private route: ActivatedRoute, private router: Router) {} ngOnInit() { this.route.params.subscribe((params: Params) => { if (params['uiSettings']) { const decodedUISettings: UISettings = JSON.parse( decodeURIComponent(params['uiSettings'] as string)); this.useCustomColorScheme = decodedUISettings.useCustomColorScheme; this.useCustomFeedbackText = decodedUISettings.useCustomFeedbackText; this.customizeScoreThresholds = decodedUISettings.customizeScoreThresholds; this.showDemoSettings = decodedUISettings.showDemoSettings; } if (params['encodedDemoSettings']) { const decodedDemoSettings: DemoSettings = JSON.parse( decodeURIComponent(params['encodedDemoSettings'] as string)); console.debug('I see demo settings in the url:', decodedDemoSettings); if (this.useCustomColorScheme) { this.customColorScheme = decodedDemoSettings.gradientColors; } else { // If the color setting wasn't custom, then it must be one of the ones // in our selection list. Iterate over the color schemes in the // selection list and find the one that equals the color scheme passed // in via the URL parameters. for (let i = 0; i < this.colorSchemes.length; i++) { const colorScheme = this.colorSchemes[i]; if (arraysEqual( colorScheme.colors, decodedDemoSettings.gradientColors)) { this.selectedColorScheme = this.colorSchemes[i]; } } } if (this.useCustomFeedbackText) { this.customFeedbackTextScheme = decodedDemoSettings.feedbackText; } else { // If the feedback text setting wasn't custom, then it must be one of // the ones in our selection list. Iterate over the feedback text // schemes in the selection list and find the one that equals the // feedback text passed in via the URL parameters. for (let i = 0; i < this.feedbackTextSchemes.length; i++) { const feedbackTextScheme = this.feedbackTextSchemes[i]; if (arraysEqual(feedbackTextScheme.feedbackTextSet, decodedDemoSettings.feedbackText)) { this.selectedFeedbackTextScheme = this.feedbackTextSchemes[i]; } } } if (this.customizeScoreThresholds) { this.neutralScoreThreshold = decodedDemoSettings.neutralScoreThreshold; this.toxicScoreThreshold = decodedDemoSettings.toxicScoreThreshold; } else { this.sliderScoreNeutralThreshold = decodedDemoSettings.neutralScoreThreshold; this.sliderScoreToxicThreshold = decodedDemoSettings.toxicScoreThreshold; this.sliderValue = (1 - this.sliderScoreNeutralThreshold) * 100; } this.showFeedbackForLowScores = decodedDemoSettings.showFeedbackForLowScores; this.showFeedbackForNeutralScores = decodedDemoSettings.showFeedbackForNeutralScores; this.selectedLoadingIconStyle = decodedDemoSettings.loadingIconStyle; this.fontFamily = decodedDemoSettings.fontFamily; } }); this.demoSettings = this.getDemoSettings(); this.demoSettingsJson = JSON.stringify(this.demoSettings); this.uiSettings = this.getUISettings(); console.debug('Updating this.demoSettings (init)', this.demoSettings); } /** Resets the custom color scheme UI to use the default color scheme. */ resetToDefaultColors() { this.customColorScheme = DEFAULT_COLORS.slice(); } /** * Updates the score thresholds from the slider value. * When using the slider, the position of the slider value equals the * threshold for a neutral toxicity score. The threshold for high toxicity is * the average of the threshold for neutral toxicity and the max toxicity * score. * * Note that the slider is inverted for UI reasons, which is why each value * is subtracted from the max slider value. Values are also divided by 100 to * fall between 0 and 1. */ onSliderValueChange(change: MatSliderChange) { this.sliderScoreNeutralThreshold = (change.source.max - change.value) / 100; this.sliderScoreToxicThreshold = (1 + this.sliderScoreNeutralThreshold) / 2; } onSettingsChanged() { const newDemoSettings = this.getDemoSettings(); const newUISettings = this.getUISettings(); if (!_.isEqual(this.demoSettings, newDemoSettings) || !_.isEqual(this.uiSettings, newUISettings)) { console.debug('Updating this.demoSettings', newDemoSettings); console.debug('Updating this.uiSettings', newUISettings); this.demoSettings = newDemoSettings; this.demoSettingsJson = JSON.stringify(this.demoSettings); this.uiSettings = newUISettings; const encodedUISettings = encodeURIComponent(JSON.stringify(this.uiSettings)); const encodedDemoSettings = encodeURIComponent(JSON.stringify(this.demoSettings)); this.router.navigate( ['/customize', encodedUISettings, encodedDemoSettings]); } else { console.debug( 'Calling onSettingsChanged(), but settings are unchanged', newDemoSettings); } } /** * Note: This function must be called to update this.demoSettings for Angular * to notice the change, because Angular will only call change detection if * the entire object has changed, and will not listen to sub-properties by * default. */ private getDemoSettings(): DemoSettings { return JSON.parse(JSON.stringify({ gradientColors: this.useCustomColorScheme ? this.customColorScheme : this.selectedColorScheme.colors, feedbackText: this.useCustomFeedbackText ? this.customFeedbackTextScheme : this.selectedFeedbackTextScheme.feedbackTextSet, neutralScoreThreshold: this.customizeScoreThresholds ? this.neutralScoreThreshold : this.sliderScoreNeutralThreshold, toxicScoreThreshold: this.customizeScoreThresholds ? this.toxicScoreThreshold : this.sliderScoreToxicThreshold, showFeedbackForLowScores: this.showFeedbackForLowScores, showFeedbackForNeutralScores: this.showFeedbackForNeutralScores, loadingIconStyle: this.selectedLoadingIconStyle, communityId: this.communityId, usePluginEndpoint: this.usePluginEndpoint, modelName: this.modelName, fontFamily: this.fontFamily })); } private getUISettings(): UISettings { return { useCustomColorScheme: this.useCustomColorScheme, useCustomFeedbackText: this.useCustomFeedbackText, customizeScoreThresholds: this.customizeScoreThresholds, showDemoSettings: this.showDemoSettings }; } }
the_stack
import { BrowserHelper, ElementHelper } from 'topcoder-testing-lib'; import * as config from '../../config/app-config.json'; import { logger } from '../../logger/logger'; import { CommonHelper } from '../common-page/common.helper'; import { LoginPage } from '../login/login.po'; import { IProjectMilestone } from './project-milestone.model'; import { ProjectMilestonePageObject } from './project-milestone.po'; let milestoneName: string; let milestoneDescription: string; let startDate: string[]; let endDate: string[]; export class ProjectMilestonePageHelper { /** * Initialize Create Project Milestone page object */ public static initialize() { this.projectMilestonePageObject = new ProjectMilestonePageObject(); this.loginPageObject = new LoginPage(); } /** * Open Home page * * @param isCustomer is cusomter */ public static async open(isCustomer: boolean = false) { await CommonHelper.goToRecentlyCreatedProject(isCustomer); await CommonHelper.waitForPageDisplayed(); await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.dashboardPageLoad, config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); } /** * Verify that User can Create / Edit / Delete Milestone * * @param projectMilestones Test Data for the test */ public static async verifyUserCanCreateEditDeleteMilestone(projectMilestones: IProjectMilestone) { await CommonHelper.waitForAddNewMilestones(); await this.addMilestones(projectMilestones, 1, projectMilestones.active); await this.projectMilestonePageObject.getEditButton(milestoneName).click(); logger.info('Clicked On Edit Button'); milestoneName = milestoneName + "EDITED"; milestoneDescription = milestoneDescription + "EDITED"; startDate = CommonHelper.getDate(3); endDate = CommonHelper.getDate(5); // await this.clickAddNewMilestoneButtonAndVerifyTitle(projectMilestones); await this.specifyMilestoneDetails(milestoneName, milestoneDescription, startDate, endDate, projectMilestones.active); const saveButton = await this.projectMilestonePageObject.saveButton(); await saveButton.click(); logger.info('Save button clicked.'); const isVerified = await this.verifyMileStoneDetails(milestoneName, milestoneDescription, startDate, endDate, projectMilestones.active); expect(isVerified).toEqual(true); logger.info('Verified Milestone Details Edited Successfully.'); const beforeDeletionCount = (await this.projectMilestonePageObject.milestoneTableRows).length; logger.info(`Before Deletion Milestone Length ${beforeDeletionCount}`); await this.projectMilestonePageObject.getDeleteButton(milestoneName).click(); logger.info('Clicked Delete Button'); const popupMessage = await this.projectMilestonePageObject.popupMessage.getText(); expect(popupMessage).toContain(projectMilestones.deleteConfirmation); expect(popupMessage).toContain(projectMilestones.deletePopupMessage); logger.info(`Verified Popup Message ${popupMessage}`); await this.projectMilestonePageObject.yesButton.click(); logger.info('Clicked Yes button'); // Verify Alert Message const milestoneDeletionMessage = await CommonHelper.getAlertMessageAndClosePopup(); expect(milestoneDeletionMessage).toEqual(projectMilestones.milestoneDeletionMessage); logger.info(`Verified Milestone Deletion Message ${milestoneDeletionMessage}`); const afterDeletionCount = (await this.projectMilestonePageObject.milestoneTableRows).length; logger.info(`After Deletion Milestone Length ${afterDeletionCount}`); expect(afterDeletionCount).toBeLessThan(beforeDeletionCount); logger.info('Verified Milestone After Deletion Count is Less than before Deletion'); } /** * Specify Milestone Details * @param mName Milestone Name * @param mDescription Milestone Description * @param mStartDate Milestone Start Date * @param mEndDate Milestone End Date * @param status Milestone Status */ public static async specifyMilestoneDetails(mName: string, mDescription: string, mStartDate: string[], mEndDate: string[], status: string) { const milestoneNameElement = this.projectMilestonePageObject.milestoneNameTextbox; await milestoneNameElement.clear(); await milestoneNameElement.sendKeys(mName); logger.info(`Specified Milestone Name ${mName}`); const milestoneDescElement = this.projectMilestonePageObject.milestoneDescriptionTextbox; await milestoneDescElement.clear(); await milestoneDescElement.sendKeys(mDescription); logger.info(`Specified Milestone Description ${mDescription}`); // const startDateValue = mStartDate[0]+mStartDate[1]+mStartDate[2]; // await this.projectMilestonePageObject.milestoneStartDateTextbox.sendKeys(startDateValue); // logger.info(`Specified Start Date ${startDateValue}`); // const endDateValue = mEndDate[0]+mEndDate[1]+mEndDate[2]; // await this.projectMilestonePageObject.milestoneEndDateTextbox.sendKeys(endDateValue); // logger.info(`Specified End Date ${endDateValue}`); await this.projectMilestonePageObject.milestoneDropdown.click(); await CommonHelper.waitForElementToBeVisible('xpath', this.projectMilestonePageObject.milestoneListXpath); const list = await this.projectMilestonePageObject.milestoneList; for (const milestone of list) { const name = await milestone.getText(); if (name === status) { await milestone.click(); logger.info(`Milestone Status ${status} selected.`); break; } } } public static async addNewMilestone(projectMilestones: IProjectMilestone, status: string) { await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.getAddButton(), config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); await this.clickAddNewMilestoneButtonAndVerifyTitle(projectMilestones); await this.specifyMilestoneDetails(milestoneName, milestoneDescription, startDate, endDate, status); logger.info(`Specified Milestone Details`); const saveButton = await this.projectMilestonePageObject.saveButton(); await saveButton.click(); logger.info('Clicked on Save button'); const milestoneCreationMessage = await CommonHelper.getAlertMessageAndClosePopup(); expect(milestoneCreationMessage).toEqual(projectMilestones.milestoneCreationMessage); logger.info(`Verified Milestone creating message ${milestoneCreationMessage}`); const isVerified = await this.verifyMileStoneDetails(milestoneName, milestoneDescription, startDate, endDate, status); expect(isVerified).toEqual(true); logger.info('Verified Newly created milestone details'); } /** * Click Add New Milestone Button and Verify Title * * @param projectMilestones Test Data for the test */ public static async clickAddNewMilestoneButtonAndVerifyTitle(projectMilestones: IProjectMilestone) { await this.projectMilestonePageObject.getAddButton().click(); logger.info("Clicked on Add New Milestone button"); const pageTitle = await this.projectMilestonePageObject.milestonesPageTitle.getText(); expect(pageTitle).toBe(projectMilestones.milestone); logger.info(`Verified Milestone Page Title $${pageTitle}`); const addButton = await this.projectMilestonePageObject.getAddButton().getText(); expect(addButton).toBe(projectMilestones.addButton); logger.info(`Verified Add New Milestone Button $${addButton}`); } /** * Verify Milestone Details * * @param mName Milestone Name * @param mDescription Milestone Description * @param mStartDate Milestone Start Date * @param mEndDate Milestone End Date * @param status Status * * @returns True / False */ public static async verifyMileStoneDetails(mName: string, mDescription: string, mStartDate: string[], mEndDate: string[], status: string) { let isVerified = false; const list = await this.projectMilestonePageObject.milestoneTableRows for (const milestoneRow of list) { const row = await milestoneRow.getText(); if (row.includes(mName)) { expect(row).toContain(mName); logger.info(`Verified Milestone Name ${mName}`); expect(row).toContain(mDescription); logger.info(`Verified Milestone Description ${mDescription}`); expect(row).toContain(status); logger.info(`Verified Milestone Status ${status}`); // expect(row).toContain(`${mStartDate[1]}-${mStartDate[0]}-${mStartDate[2]}`); // logger.info(`Verified Start Date ${mStartDate[1]}-${mStartDate[0]}-${mStartDate[2]}`); // expect(row).toContain(`${mEndDate[1]}-${mEndDate[0]}-${mEndDate[2]}`); // logger.info(`Verified End Date ${mStartDate[1]}-${mStartDate[0]}-${mStartDate[2]}`); isVerified = true; break; } } return isVerified; } /** * Verify User Can Add Copilot On Milestone * * @param projectMilestones Test Data for the test */ public static async verifyUserCanAddCopilotOnMilestone(projectMilestones: IProjectMilestone) { await CommonHelper.waitForAddNewMilestones(); milestoneName = CommonHelper.appendDate(projectMilestones.milestone); milestoneDescription = CommonHelper.appendDate(projectMilestones.description); startDate = CommonHelper.getDate(); endDate = CommonHelper.getDate(2); await this.clickAddNewMilestoneButtonAndVerifyTitle(projectMilestones); await this.specifyMilestoneDetails(milestoneName, milestoneDescription, startDate, endDate, projectMilestones.active); await this.projectMilestonePageObject.getAddCopilotButton(milestoneName).click(); logger.info('Click on Add Copilot button'); await CommonHelper.waitForElementToBeVisible('xpath', this.projectMilestonePageObject.copilotManagementWindowTitleXpath); const copilotManagementWindowTitle = await this.projectMilestonePageObject.copilotManagementWindowTitle.getText(); expect(copilotManagementWindowTitle).toEqual(projectMilestones.copilot); logger.info(`Verified Copilot Management Window Title ${copilotManagementWindowTitle}`); await this.projectMilestonePageObject.copilotDropdown.click(); await this.projectMilestonePageObject.copilotTextbox.sendKeys(projectMilestones.copilotName); await CommonHelper.searchTextFromListAndClick(await this.projectMilestonePageObject.copilotList, projectMilestones.copilotName, true); await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.getAddButton(2), config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); await this.projectMilestonePageObject.getAddButton(2).click(); logger.info('Clicked on Add Button'); const copilotNameLabelValue = await this.projectMilestonePageObject.copilotNameLabel.getText(); expect(copilotNameLabelValue).toEqual(projectMilestones.copilotName); logger.info(`Verified Copilot Name Label Value ${copilotNameLabelValue}`); await this.projectMilestonePageObject.closeIcon.click(); logger.info('Clicked Close Icon'); const saveButton = await this.projectMilestonePageObject.saveButton(); await saveButton.click(); logger.info('Clicked Save Icon'); const milestoneCreationMessage = await CommonHelper.getAlertMessageAndClosePopup(); expect(milestoneCreationMessage).toEqual(projectMilestones.milestoneCreationMessage); logger.info(`Verified Milestone Creation Message ${milestoneCreationMessage}`); const isVerified = await this.verifyMileStoneDetails(milestoneName, milestoneDescription, startDate, endDate, projectMilestones.active); expect(isVerified).toEqual(true); logger.info('Verified Milestone Details Successfully.'); await CommonHelper.waitForElementToBeVisible('xpath', this.projectMilestonePageObject.copilotImageXpath.replace('MILESTONE_NAME', milestoneName)); const copilotImageName = await this.projectMilestonePageObject.getCopilotImage(milestoneName).getAttribute("alt"); expect(copilotImageName).toEqual(projectMilestones.copilotName); logger.info(`Copilot Image Verified with attribute ${copilotImageName}`); } /** * Verify User Can Bulk Update the milestone * * @param projectMilestones Test data for the test * @param milestoneNames List of Milestones to be updated */ public static async verifyUserCanBulkUpdateTheMilestone(projectMilestones: IProjectMilestone) { const beforeRowDates = await this.getDateDetailsForAvailableMilestones(); await this.projectMilestonePageObject.milestoneSelectAllCheckbox.click(); logger.info('Click on Milestone Select All checkbox'); const message = await this.projectMilestonePageObject.projectSelectedLabel.getText(); expect(message).toContain(projectMilestones.projectsSelected); logger.info(`Verified Message ${message}`); await this.projectMilestonePageObject.addCopilotButton.click(); logger.info(`Clicked On Add Copilot Icon`); await CommonHelper.waitForElementToBeVisible('xpath', this.projectMilestonePageObject.copilotManagementWindowTitleXpath); const copilotManagementWindowTitle = await this.projectMilestonePageObject.copilotManagementWindowTitle.getText(); expect(copilotManagementWindowTitle).toEqual(projectMilestones.copilot); logger.info(`Verified Copilot Management Window Title ${copilotManagementWindowTitle}`); await this.projectMilestonePageObject.copilotDropdown.click(); await this.projectMilestonePageObject.copilotTextbox.sendKeys(projectMilestones.copilotName); await CommonHelper.searchTextFromListAndClick(await this.projectMilestonePageObject.copilotList, projectMilestones.copilotName, true); logger.info(`Selected Copilot from the list ${projectMilestones.copilotName}`); await this.projectMilestonePageObject.getAddButton(2).click(); const copilotNameLabelValue = await this.projectMilestonePageObject.copilotNameLabel.getText(); expect(copilotNameLabelValue).toEqual(projectMilestones.copilotName); logger.info(`Verified Copilot Name Label Value ${copilotNameLabelValue}`); await this.projectMilestonePageObject.closeIcon.click(); logger.info('Clicked Close Icon'); await this.projectMilestonePageObject.moveMilestoneButton.click(); logger.info('Clicked Move Milestone Icon'); await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.moveMilestonePopupMessage, config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); const moveMilestonePopupMessage = await this.projectMilestonePageObject.moveMilestonePopupMessage.getText(); expect(moveMilestonePopupMessage).toContain(projectMilestones.moveMilestoneDatesTitle); expect(moveMilestonePopupMessage).toContain(projectMilestones.moveMilestoneDatesDescription); logger.info(`Verified Move Milestone Popup Message: ${moveMilestonePopupMessage}`); const moveMilestoneInputBoxElement = this.projectMilestonePageObject.moveMilestoneInputBox; moveMilestoneInputBoxElement.clear(); moveMilestoneInputBoxElement.sendKeys(projectMilestones.noOfDays); logger.info(`Specified Value ${projectMilestones.noOfDays} in Move Milestone Textbox`); await this.projectMilestonePageObject.getMoveMilestoneButton().click(); logger.info('Clicked on Move Milestone button'); const afterRowDates = await this.getDateDetailsForAvailableMilestones(); await this.verifyMilestoneDatesAfterMovingDates(beforeRowDates, afterRowDates, projectMilestones.noOfDays); await this.projectMilestonePageObject.deleteMilestoneButton.click(); logger.info('Clicked on Move Milestone Delete button'); await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.moveMilestonePopupMessage, config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); const popupMessage = await this.projectMilestonePageObject.popupMessage.getText(); expect(popupMessage).toContain(projectMilestones.deleteConfirmation); expect(popupMessage).toContain(projectMilestones.deletePopupMessage); logger.info(`Verified Delete Milestone Popup Message: ${popupMessage}`); await this.projectMilestonePageObject.yesButton.click(); logger.info('Clicked Yes button'); const milestoneBulkDeletionMessage = await CommonHelper.getAlertMessageAndClosePopup(); expect(milestoneBulkDeletionMessage).toEqual(projectMilestones.milestoneBulkDeletionMessage); logger.info(`Verified Delete Milestone Message ${milestoneBulkDeletionMessage}`); } /** * Adds a new Milestone * * @param projectMilestones Test Data for Adding Milestone * @param count No. of Milestones to add * @param status Milestone Status * * @returns Names of Milestones created */ public static async addMilestones(projectMilestones: IProjectMilestone, count: any, status: string) { const milestoneNames = []; for (let cnt = 0; cnt < count; cnt++) { milestoneName = CommonHelper.appendDate(projectMilestones.milestone); milestoneDescription = CommonHelper.appendDate(projectMilestones.description); startDate = CommonHelper.getDate(cnt); endDate = CommonHelper.getDate(cnt + 2); await this.addNewMilestone(projectMilestones, status); milestoneNames.push(milestoneName); } return milestoneNames; } /** * Verify Add Milestone Button and Draft Milestone Should not be displayed for Customer * * @param projectMilestones Test Data for the test * * @param customerUser Customer User Details */ public static async verifyAddMilestoneButtonAndDraftMilestoneShouldNotBeDisplayed(projectMilestones: IProjectMilestone, customerUser: any) { // await this.addMilestones(projectMilestones, 1, projectMilestones.active); await this.addMilestones(projectMilestones, 1, projectMilestones.inReview); await this.addMilestones(projectMilestones, 1, projectMilestones.inReview); await this.addMilestones(projectMilestones, 1, projectMilestones.draft); await this.loginPageObject.logout(); await CommonHelper.login(customerUser.email, customerUser.password); logger.info('Logged in using Customer User'); await this.open(true); const isAddButtonPresent = await CommonHelper.isElementPresent('xpath', this.projectMilestonePageObject.addNewMilestoneXpath); expect(isAddButtonPresent).toEqual(false); logger.info('Verified Add Button is Not Visible for Customer User'); const isDraftMilestonePresent = await CommonHelper.isElementPresent('xpath', this.projectMilestonePageObject.milestoneStatusXpath); expect(isDraftMilestonePresent).toEqual(false); logger.info('Verified Draft Milestone Created by Copilot User s Not Visible for Customer User'); } /** * Deletes All Milestones Present * * @param projectMilestones Test Data for the test */ public static async deleteAllMilestones(projectMilestones: IProjectMilestone) { await CommonHelper.waitForMilestones(); await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.getAddButton(), config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); await this.projectMilestonePageObject.milestoneSelectAllCheckbox.click().then(async () => { logger.info('Click on Milestone Select All checkbox'); await this.projectMilestonePageObject.deleteMilestoneButton.click(); logger.info('Clicked on Move Milestone Delete button'); await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.moveMilestonePopupMessage, config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); const popupMessage = await this.projectMilestonePageObject.popupMessage.getText(); expect(popupMessage).toContain(projectMilestones.deleteConfirmation); expect(popupMessage).toContain(projectMilestones.deletePopupMessage); logger.info(`Verified Delete Milestone Popup Message: ${popupMessage}`); await this.projectMilestonePageObject.yesButton.click(); logger.info('Clicked Yes button'); const milestoneBulkDeletionMessage = await CommonHelper.getAlertMessageAndClosePopup(); expect(milestoneBulkDeletionMessage).toEqual(projectMilestones.milestoneBulkDeletionMessage); logger.info(`Verified Delete Milestone Message ${milestoneBulkDeletionMessage}`); await BrowserHelper.waitUntilClickableOf( this.projectMilestonePageObject.getAddButton(), config.Timeout.ElementClickable, config.LoggerErrors.ElementClickable ); }).catch((err) => { logger.info('No Milestones to Delete'); }); } /** * Gets Date Details for the Available Milestones * * @returns Date Details */ public static async getDateDetailsForAvailableMilestones() { const availableDates = []; const tableRows = await this.projectMilestonePageObject.milestoneTableRows; for (const test of tableRows) { const tableTds = await ElementHelper.getAllElementsByTag("td", test); for (let innerCnt = 0; innerCnt < tableTds.length; innerCnt++) { const dateString = await tableTds[innerCnt].getText(); if (innerCnt === 4) { availableDates.push(dateString); } if (innerCnt === 5) { availableDates.push(dateString); break; } } } return availableDates; } /** * Verify Date Difference after moving milestone dates * * @param beforeRowDates Before Moving Milestone Dates * @param afterRowDates After Moving Milestone Dates * @param differenceToCheck Difference number to check */ public static async verifyMilestoneDatesAfterMovingDates(beforeRowDates: string[], afterRowDates: string[], differenceToCheck: number) { for (let cnt = 0; cnt < beforeRowDates.length; cnt++) { const datesArray1 = beforeRowDates[cnt]; const datesArray2 = afterRowDates[cnt]; const date1 = new Date(datesArray1); const date2 = new Date(datesArray2); const diffTime = Math.abs(date2.getTime() - date1.getTime()); const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); expect(diffDays).toEqual(differenceToCheck); logger.info(`Verified Date Difference between dates ${date1.getDate()} and ${date2.getDate()} as ${differenceToCheck}`); } } /** * approve the milestone which are in review status */ public static async takeActionOnMilestone(projectMilestones: IProjectMilestone, customerUser: any, copilotUser: any) { await CommonHelper.waitForMilestones(); await this.verifyAddMilestoneButtonAndDraftMilestoneShouldNotBeDisplayed(projectMilestones, customerUser); await this.approveMilestoneAndVerify() await this.loginPageObject.logout(); await CommonHelper.login(copilotUser.email, copilotUser.password); logger.info('Logged in using Copilot User'); await this.open(); const milestoneApproveNotification = this.projectMilestonePageObject.allMilestoneApproveNotification() await BrowserHelper.waitUntilVisibilityOf(milestoneApproveNotification) logger.info(`'${await milestoneApproveNotification.getText()}' is displayed on the page.`) expect(milestoneApproveNotification.getText()).toContain(projectMilestones.allMilestoneApprovedNotificationStr) await CommonHelper.waitAndClickElement(this.projectMilestonePageObject.getDismissAllMilestoneApprovedNotificationButton()) logger.info(`The notification alert is dismissed.`) } /** * approve all milestone with customer role * @param message */ public static async approveMilestoneAndVerify() { const approveMilestoneButton = await this.projectMilestonePageObject.getAllMilestoneActionButtonsForCustomer('approve') let numberOfInReviewMilestones = (approveMilestoneButton).length let index: number = 0; logger.info(`Total ${numberOfInReviewMilestones} numbers of milestone found with 'In review' status`) const approveMilestoneButton1 = this.projectMilestonePageObject.getMilestoneActionButtonForCustomer('approve') await BrowserHelper.sleep(2000); while (numberOfInReviewMilestones !== 0) { logger.info("Approve milestone button is displayed on the page.") try { expect(await BrowserHelper.waitUntilClickableOf(approveMilestoneButton1)) await CommonHelper.waitAndClickElement(approveMilestoneButton1) logger.info(`${index + 1} milestone approved.`) index++ numberOfInReviewMilestones--; const approvedAlert = await CommonHelper.getAlertMessageAndClosePopup(); await BrowserHelper.waitUntilInVisibilityOf(approvedAlert) } catch (StaleElementReferenceError) { await BrowserHelper.sleep(4000); } } index = 0; logger.info("All milestone with 'In review' status are approved.") } private static loginPageObject: LoginPage; private static projectMilestonePageObject: ProjectMilestonePageObject; }
the_stack
module android.view { import Canvas = android.graphics.Canvas; import Point = android.graphics.Point; import Rect = android.graphics.Rect; import RectF = android.graphics.RectF; import Matrix = android.graphics.Matrix; import SystemClock = android.os.SystemClock; import Context = android.content.Context; import System = java.lang.System; import ArrayList = java.util.ArrayList; import Integer = java.lang.Integer; import Animation = android.view.animation.Animation; import Transformation = android.view.animation.Transformation; import AttrBinder = androidui.attr.AttrBinder; import ClassBinderMap = androidui.attr.AttrBinder.ClassBinderMap; export abstract class ViewGroup extends View implements ViewParent { static FLAG_CLIP_CHILDREN = 0x1; static FLAG_CLIP_TO_PADDING = 0x2; static FLAG_INVALIDATE_REQUIRED = 0x4; static FLAG_RUN_ANIMATION = 0x8; static FLAG_ANIMATION_DONE = 0x10; static FLAG_PADDING_NOT_NULL = 0x20; static FLAG_ANIMATION_CACHE = 0x40; static FLAG_OPTIMIZE_INVALIDATE = 0x80; static FLAG_CLEAR_TRANSFORMATION = 0x100; static FLAG_NOTIFY_ANIMATION_LISTENER = 0x200; static FLAG_USE_CHILD_DRAWING_ORDER = 0x400; static FLAG_SUPPORT_STATIC_TRANSFORMATIONS = 0x800; static FLAG_ALPHA_LOWER_THAN_ONE = 0x1000; static FLAG_ADD_STATES_FROM_CHILDREN = 0x2000; static FLAG_ALWAYS_DRAWN_WITH_CACHE = 0x4000; static FLAG_CHILDREN_DRAWN_WITH_CACHE = 0x8000; static FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE = 0x10000; static FLAG_MASK_FOCUSABILITY = 0x60000; static FOCUS_BEFORE_DESCENDANTS = 0x20000; static FOCUS_AFTER_DESCENDANTS = 0x40000; static FOCUS_BLOCK_DESCENDANTS = 0x60000; static FLAG_DISALLOW_INTERCEPT = 0x80000; static FLAG_SPLIT_MOTION_EVENTS = 0x200000; static FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW = 0x400000; static FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET = 0x800000; /** * Indicates which types of drawing caches are to be kept in memory. * This field should be made private, so it is hidden from the SDK. * {@hide} */ mPersistentDrawingCache:number; /** * Used to indicate that no drawing cache should be kept in memory. */ static PERSISTENT_NO_CACHE:number = 0x0; /** * Used to indicate that the animation drawing cache should be kept in memory. */ static PERSISTENT_ANIMATION_CACHE:number = 0x1; /** * Used to indicate that the scrolling drawing cache should be kept in memory. */ static PERSISTENT_SCROLLING_CACHE:number = 0x2; /** * Used to indicate that all drawing caches should be kept in memory. */ static PERSISTENT_ALL_CACHES:number = 0x3; static LAYOUT_MODE_UNDEFINED = -1; static LAYOUT_MODE_CLIP_BOUNDS = 0; //static LAYOUT_MODE_OPTICAL_BOUNDS = 1; static LAYOUT_MODE_DEFAULT = ViewGroup.LAYOUT_MODE_CLIP_BOUNDS; static CLIP_TO_PADDING_MASK = ViewGroup.FLAG_CLIP_TO_PADDING | ViewGroup.FLAG_PADDING_NOT_NULL; /** * Views which have been hidden or removed which need to be animated on * their way out. * This field should be made private, so it is hidden from the SDK. * {@hide} */ protected mDisappearingChildren:ArrayList<View>; mOnHierarchyChangeListener:ViewGroup.OnHierarchyChangeListener; private mFocused:View; private mFirstTouchTarget:TouchTarget; /** * A Transformation used when drawing children, to * apply on the child being drawn. */ private mChildTransformation:Transformation; /** * Used to track the current invalidation region. */ protected mInvalidateRegion:RectF; // For debugging only. You can see these in hierarchyviewer. private mLastTouchDownTime = 0; private mLastTouchDownIndex = -1; private mLastTouchDownX = 0; private mLastTouchDownY = 0; mGroupFlags=0; mLayoutMode = ViewGroup.LAYOUT_MODE_UNDEFINED; mChildren:Array<View> = []; get mChildrenCount() { return this.mChildren.length; } mSuppressLayout = false; private mLayoutCalledWhileSuppressed = false; private mChildCountWithTransientState = 0; private static ViewGroupClassAttrBind:AttrBinder.ClassBinderMap; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>){ super(context, bindElement, defStyle); this.initViewGroup(); if (bindElement || defStyle) { this.initFromAttributes(context, bindElement, defStyle); } } private initViewGroup() { // ViewGroup doesn't draw by default this.setFlags(View.WILL_NOT_DRAW, View.DRAW_MASK); this.mGroupFlags |= ViewGroup.FLAG_CLIP_CHILDREN; this.mGroupFlags |= ViewGroup.FLAG_CLIP_TO_PADDING; this.mGroupFlags |= ViewGroup.FLAG_ANIMATION_DONE; this.mGroupFlags |= ViewGroup.FLAG_ANIMATION_CACHE; this.mGroupFlags |= ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE; this.mGroupFlags |= ViewGroup.FLAG_SPLIT_MOTION_EVENTS; this.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); this.mPersistentDrawingCache = ViewGroup.PERSISTENT_SCROLLING_CACHE; } private initFromAttributes(context:Context, attrs:HTMLElement, defStyle?:Map<string, string>) { const a = context.obtainStyledAttributes(attrs, defStyle); for (let attr of a.getLowerCaseNoNamespaceAttrNames()) { switch (attr) { case 'clipchildren': this.setClipChildren(a.getBoolean(attr, true)); break; case 'cliptopadding': this.setClipToPadding(a.getBoolean(attr, true)); break; case 'animationcache': this.setAnimationCacheEnabled(a.getBoolean(attr, true)); break; case 'persistentdrawingcache': { let value = a.getAttrValue(attr); if (value === 'none') this.setPersistentDrawingCache(ViewGroup.PERSISTENT_NO_CACHE); else if (value === 'animation') this.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE); else if (value === 'scrolling') this.setPersistentDrawingCache(ViewGroup.PERSISTENT_SCROLLING_CACHE); else if (value === 'all') this.setPersistentDrawingCache(ViewGroup.PERSISTENT_ALL_CACHES); break; } case 'addstatesfromchildren': this.setAddStatesFromChildren(a.getBoolean(attr, false)); break; case 'alwaysdrawnwithcache': this.setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true)); break; case 'layoutanimation': // TODO when layout anim support // int id = a.getResourceId(attr, -1); // if (id > 0) { // setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id)); // } break; case 'descendantfocusability': { let value = a.getAttrValue(attr); if (value == 'beforeDescendants') this.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); else if (value == 'afterDescendants') this.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); else if (value == 'blocksDescendants') this.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); break; } case 'splitmotionevents': this.setMotionEventSplittingEnabled(a.getBoolean(attr, false)); break; case 'animatelayoutchanges': //TODO when layout transition support // let animateLayoutChanges = a.getBoolean(attr, false); // if (animateLayoutChanges) { // this.setLayoutTransition(new LayoutTransition()); // } break; case 'layoutmode': //TODO when more layout mode support // this.setLayoutMode(a.getInt(attr, LAYOUT_MODE_UNDEFINED)); break; } } a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder() .set('clipChildren', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { v.setClipChildren(attrBinder.parseBoolean(value)); }, getter(v:ViewGroup) { return v.getClipChildren(); } }).set('clipToPadding', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { v.setClipToPadding(attrBinder.parseBoolean(value)); }, getter(v:ViewGroup) { return v.isClipToPadding(); } }).set('animationCache', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { v.setAnimationCacheEnabled(attrBinder.parseBoolean(value, true)); } }).set('persistentDrawingCache', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { if(value === 'none') v.setPersistentDrawingCache(ViewGroup.PERSISTENT_NO_CACHE); else if(value === 'animation') v.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE); else if(value === 'scrolling') v.setPersistentDrawingCache(ViewGroup.PERSISTENT_SCROLLING_CACHE); else if(value === 'all') v.setPersistentDrawingCache(ViewGroup.PERSISTENT_ALL_CACHES); } }).set('addStatesFromChildren', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { v.setAddStatesFromChildren(attrBinder.parseBoolean(value, false)); } }).set('alwaysDrawnWithCache', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { v.setAlwaysDrawnWithCacheEnabled(attrBinder.parseBoolean(value, true)); } }).set('descendantFocusability', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { if(value == 'beforeDescendants') this.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); else if(value == 'afterDescendants') this.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); else if(value == 'blocksDescendants') this.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); } }).set('splitMotionEvents', { setter(v:ViewGroup, value:any, attrBinder:AttrBinder) { v.setMotionEventSplittingEnabled(attrBinder.parseBoolean(value, false)); } }); } getDescendantFocusability():number { return this.mGroupFlags & ViewGroup.FLAG_MASK_FOCUSABILITY; } setDescendantFocusability(focusability:number) { switch (focusability) { case ViewGroup.FOCUS_BEFORE_DESCENDANTS: case ViewGroup.FOCUS_AFTER_DESCENDANTS: case ViewGroup.FOCUS_BLOCK_DESCENDANTS: break; default: throw new Error("must be one of FOCUS_BEFORE_DESCENDANTS, " + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS"); } this.mGroupFlags &= ~ViewGroup.FLAG_MASK_FOCUSABILITY; this.mGroupFlags |= (focusability & ViewGroup.FLAG_MASK_FOCUSABILITY); } handleFocusGainInternal(direction:number, previouslyFocusedRect:Rect) { if (this.mFocused != null) { this.mFocused.unFocus(); this.mFocused = null; } super.handleFocusGainInternal(direction, previouslyFocusedRect); } requestChildFocus(child:View, focused:View) { if (View.DBG) { System.out.println(this + " requestChildFocus()"); } if (this.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { return; } // Unfocus us, if necessary super.unFocus(); // We had a previous notion of who had focus. Clear it. if (this.mFocused != child) { if (this.mFocused != null) { this.mFocused.unFocus(); } this.mFocused = child; } if (this.mParent != null) { this.mParent.requestChildFocus(this, focused); } } focusableViewAvailable(v:View) { if (this.mParent != null // shortcut: don't report a new focusable view if we block our descendants from // getting focus && (this.getDescendantFocusability() != ViewGroup.FOCUS_BLOCK_DESCENDANTS) // shortcut: don't report a new focusable view if we already are focused // (and we don't prefer our descendants) // // note: knowing that mFocused is non-null is not a good enough reason // to break the traversal since in that case we'd actually have to find // the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and // an ancestor of v; this will get checked for at ViewAncestor && !(this.isFocused() && this.getDescendantFocusability() != ViewGroup.FOCUS_AFTER_DESCENDANTS)) { this.mParent.focusableViewAvailable(v); } } focusSearch(direction:number):View; focusSearch(focused:View, direction:number):View; focusSearch(...args):View { if(arguments.length === 1){ return super.focusSearch(args[0]); } const focused:View = <View>args[0]; const direction:number = args[1]; if (this.isRootNamespace()) { // root namespace means we should consider ourselves the top of the // tree for focus searching; otherwise we could be focus searching // into other tabs. see LocalActivityManager and TabHost for more info return FocusFinder.getInstance().findNextFocus(this, focused, direction); } else if (this.mParent != null) { return this.mParent.focusSearch(focused, direction); } return null; } requestChildRectangleOnScreen(child:View, rectangle:Rect, immediate:boolean) { return false; } childHasTransientStateChanged(child:View, childHasTransientState:boolean) { const oldHasTransientState = this.hasTransientState(); if (childHasTransientState) { this.mChildCountWithTransientState++; } else { this.mChildCountWithTransientState--; } const newHasTransientState = this.hasTransientState(); if (this.mParent != null && oldHasTransientState != newHasTransientState) { this.mParent.childHasTransientStateChanged(this, newHasTransientState); } } hasTransientState():boolean { return this.mChildCountWithTransientState > 0 || super.hasTransientState(); } dispatchUnhandledMove(focused:android.view.View, direction:number):boolean { return this.mFocused != null && this.mFocused.dispatchUnhandledMove(focused, direction); } clearChildFocus(child:View) { if (View.DBG) { System.out.println(this + " clearChildFocus()"); } this.mFocused = null; if (this.mParent != null) { this.mParent.clearChildFocus(this); } } clearFocus() { if (View.DBG) { System.out.println(this + " clearFocus()"); } if (this.mFocused == null) { super.clearFocus(); } else { let focused = this.mFocused; this.mFocused = null; focused.clearFocus(); } } unFocus() { if (View.DBG) { System.out.println(this + " unFocus()"); } if (this.mFocused == null) { super.unFocus(); } else { this.mFocused.unFocus(); this.mFocused = null; } } getFocusedChild():View { return this.mFocused; } hasFocus():boolean { return (this.mPrivateFlags & View.PFLAG_FOCUSED) != 0 || this.mFocused != null; } findFocus():View { if (ViewGroup.DBG) { System.out.println("Find focus in " + this + ": flags=" + this.isFocused() + ", child=" + this.mFocused); } if (this.isFocused()) { return this; } if (this.mFocused != null) { return this.mFocused.findFocus(); } return null; } hasFocusable():boolean { if ((this.mViewFlags & View.VISIBILITY_MASK) != View.VISIBLE) { return false; } if (this.isFocusable()) { return true; } const descendantFocusability = this.getDescendantFocusability(); if (descendantFocusability != ViewGroup.FOCUS_BLOCK_DESCENDANTS) { const count = this.mChildrenCount; const children = this.mChildren; for (let i = 0; i < count; i++) { const child = children[i]; if (child.hasFocusable()) { return true; } } } return false; } addFocusables(views:ArrayList<View>, direction:number, focusableMode = View.FOCUSABLES_TOUCH_MODE):void { const focusableCount = views.size(); const descendantFocusability = this.getDescendantFocusability(); if (descendantFocusability != ViewGroup.FOCUS_BLOCK_DESCENDANTS) { const count = this.mChildrenCount; const children = this.mChildren; for (let i = 0; i < count; i++) { const child = children[i]; if ((child.mViewFlags & View.VISIBILITY_MASK) == View.VISIBLE) { child.addFocusables(views, direction, focusableMode); } } } // we add ourselves (if focusable) in all cases except for when we are // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is // to avoid the focus search finding layouts when a more precise search // among the focusable children would be more interesting. if (descendantFocusability != ViewGroup.FOCUS_AFTER_DESCENDANTS // No focusable descendants || (focusableCount == views.size())) { super.addFocusables(views, direction, focusableMode); } } requestFocus(direction=View.FOCUS_DOWN, previouslyFocusedRect=null):boolean { if (View.DBG) { System.out.println(this + " ViewGroup.requestFocus direction=" + direction); } let descendantFocusability = this.getDescendantFocusability(); switch (descendantFocusability) { case ViewGroup.FOCUS_BLOCK_DESCENDANTS: return super.requestFocus(direction, previouslyFocusedRect); case ViewGroup.FOCUS_BEFORE_DESCENDANTS: { const took = super.requestFocus(direction, previouslyFocusedRect); return took ? took : this.onRequestFocusInDescendants(direction, previouslyFocusedRect); } case ViewGroup.FOCUS_AFTER_DESCENDANTS: { const took = this.onRequestFocusInDescendants(direction, previouslyFocusedRect); return took ? took : super.requestFocus(direction, previouslyFocusedRect); } default: throw new Error("descendant focusability must be " + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS " + "but is " + descendantFocusability); } } protected onRequestFocusInDescendants(direction:number, previouslyFocusedRect:Rect):boolean { let index; let increment; let end; let count = this.mChildrenCount; if ((direction & View.FOCUS_FORWARD) != 0) { index = 0; increment = 1; end = count; } else { index = count - 1; increment = -1; end = -1; } const children = this.mChildren; for (let i = index; i != end; i += increment) { let child = children[i]; if ((child.mViewFlags & View.VISIBILITY_MASK) == View.VISIBLE) { if (child.requestFocus(direction, previouslyFocusedRect)) { return true; } } } return false; } addView(view:View); addView(view:View, index:number); addView(view:View, params:ViewGroup.LayoutParams); addView(view:View, index:number, params:ViewGroup.LayoutParams); addView(view:View, width:number, height:number); addView(...args); addView(...args) { let child:View = args[0]; let params = child.getLayoutParams(); let index = -1; if (args.length == 2) { if (args[1] instanceof ViewGroup.LayoutParams) params = args[1]; else if(typeof args[1] === 'number') index = args[1]; } else if (args.length == 3) { if (args[2] instanceof ViewGroup.LayoutParams) { index = args[1]; params = args[2]; } else { params = this.generateDefaultLayoutParams(); params.width = args[1]; params.height = args[2]; } } if (params == null) { params = this.generateDefaultLayoutParams(); if (params == null) { throw new Error("generateDefaultLayoutParams() cannot return null"); } } // addViewInner() will call child.requestLayout() when setting the new LayoutParams // therefore, we call requestLayout() on ourselves before, so that the child's request // will be blocked at our level this.requestLayout(); this.invalidate(true); this.addViewInner(child, index, params, false); } protected checkLayoutParams(p:ViewGroup.LayoutParams):boolean { return p != null; } setOnHierarchyChangeListener(listener:ViewGroup.OnHierarchyChangeListener) { this.mOnHierarchyChangeListener = listener; } protected onViewAdded(child:View) { if (this.mOnHierarchyChangeListener != null) { this.mOnHierarchyChangeListener.onChildViewAdded(this, child); } } protected onViewRemoved(child:View) { if (this.mOnHierarchyChangeListener != null) { this.mOnHierarchyChangeListener.onChildViewRemoved(this, child); } } clearCachedLayoutMode() { if (!this.hasBooleanFlag(ViewGroup.FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET)) { this.mLayoutMode = ViewGroup.LAYOUT_MODE_UNDEFINED; } } addViewInLayout(child:View, index:number, params:ViewGroup.LayoutParams, preventRequestLayout = false):boolean { child.mParent = null; this.addViewInner(child, index, params, preventRequestLayout); child.mPrivateFlags = (child.mPrivateFlags & ~ViewGroup.PFLAG_DIRTY_MASK) | ViewGroup.PFLAG_DRAWN; return true; } cleanupLayoutState(child:View) { child.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT; } addViewInner(child:View, index:number, params:ViewGroup.LayoutParams, preventRequestLayout:boolean) { if (child.getParent() != null) { throw new Error("The specified child already has a parent. " + "You must call removeView() on the child's parent first."); } if (!this.checkLayoutParams(params)) { params = this.generateLayoutParams(params); } if (preventRequestLayout) { child.mLayoutParams = params; } else { child.setLayoutParams(params); } if (index < 0) { index = this.mChildrenCount; } if(this.mDisappearingChildren) this.mDisappearingChildren.remove(child);//androidui add, remove disappearing child. this.addInArray(child, index); // tell our children if (preventRequestLayout) { child.assignParent(this); } else { child.mParent = this; } if (child.hasFocus()) { this.requestChildFocus(child, child.findFocus()); } let ai = this.mAttachInfo; if (ai != null && (this.mGroupFlags & ViewGroup.FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) { child.dispatchAttachedToWindow(this.mAttachInfo, (this.mViewFlags & ViewGroup.VISIBILITY_MASK)); } this.onViewAdded(child); if ((child.mViewFlags & ViewGroup.DUPLICATE_PARENT_STATE) == ViewGroup.DUPLICATE_PARENT_STATE) { this.mGroupFlags |= ViewGroup.FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE; } //if (child.hasTransientState()) { // childHasTransientStateChanged(child, true); //} } private addInArray(child:View, index:number) { let count = this.mChildrenCount; if (index == count) { this.mChildren.push(child); this.addToBindElement(child.bindElement, null); } else if (index < count) { let refChild = this.getChildAt(index); this.mChildren.splice(index, 0, child); this.addToBindElement(child.bindElement, refChild.bindElement); } else { throw new Error("index=" + index + " count=" + count); } } private addToBindElement(childElement:HTMLElement, insertBeforeElement:HTMLElement){ if(childElement.parentElement){ if(childElement.parentElement == this.bindElement) return; childElement.parentElement.removeChild(childElement); } if (insertBeforeElement) { this.bindElement.insertBefore(childElement, insertBeforeElement);//insert to dom }else{ this.bindElement.appendChild(childElement);//append to dom } } private removeChildElement(childElement:HTMLElement){ try { this.bindElement.removeChild(childElement);//remove from dom } catch (e) { } } private removeFromArray(index:number, count = 1) { let start = Math.max(0, index); let end = Math.min(this.mChildrenCount, start + count); if (start == end) { return; } for (let i = start; i < end; i++) { this.mChildren[i].mParent = null; this.removeChildElement(this.mChildren[i].bindElement);//remove from dom } this.mChildren.splice(index, end - start); } removeView(view:View) { this.removeViewInternal(view); this.requestLayout(); this.invalidate(true); } removeViewInLayout(view:View) { this.removeViewInternal(view); } removeViewsInLayout(start:number, count:number) { this.removeViewsInternal(start, count); } removeViewAt(index:number) { this.removeViewsInternal(index, 1); //this.removeViewInternal(index, this.getChildAt(index)); this.requestLayout(); this.invalidate(true); } removeViews(start:number, count:number) { this.removeViewsInternal(start, count); this.requestLayout(); this.invalidate(true); } private removeViewInternal(view:View) { let index = this.indexOfChild(view); if (index >= 0) { this.removeViewsInternal(index, 1); } } private removeViewsInternal(start:number, count:number) { let focused = this.mFocused; let clearChildFocus = false; const detach = this.mAttachInfo != null; const children = this.mChildren; const end = start + count; for (let i = start; i < end; i++) { const view = children[i]; if (view == focused) { view.unFocus(); clearChildFocus = true; } this.cancelTouchTarget(view); //this.cancelHoverTarget(view);//TODO when hover ok if (view.getAnimation() != null // ||(mTransitioningViews != null && mTransitioningViews.contains(view)) //TODO when Transition ok ){ this.addDisappearingView(view); } else if (detach) { view.dispatchDetachedFromWindow(); } //if (view.hasTransientState()) { // childHasTransientStateChanged(view, false); //} this.onViewRemoved(view); } this.removeFromArray(start, count); if (clearChildFocus) { this.clearChildFocus(focused); if (!this.rootViewRequestFocus()) { this.notifyGlobalFocusCleared(focused); } } } removeAllViews() { this.removeAllViewsInLayout(); this.requestLayout(); this.invalidate(true); } removeAllViewsInLayout() { const count = this.mChildrenCount; if (count <= 0) { return; } this.removeViewsInternal(0, count); } detachViewFromParent(child:View|number):void { if(child instanceof View) child = this.indexOfChild(<View>child); this.removeFromArray(<number>child); } /** * Finishes the removal of a detached view. This method will dispatch the detached from * window event and notify the hierarchy change listener. * <p> * This method is intended to be lightweight and makes no assumptions about whether the * parent or child should be redrawn. Proper use of this method will include also making * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls. * For example, callers can {@link #post(Runnable) post} a {@link Runnable} * which performs a {@link #requestLayout()} on the next frame, after all detach/remove * calls are finished, causing layout to be run prior to redrawing the view hierarchy. * * @param child the child to be definitely removed from the view hierarchy * @param animate if true and the view has an animation, the view is placed in the * disappearing views list, otherwise, it is detached from the window * * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) * @see #detachAllViewsFromParent() * @see #detachViewFromParent(View) * @see #detachViewFromParent(int) */ removeDetachedView(child:View, animate:boolean):void { //if (this.mTransition != null) { // this.mTransition.removeChild(this, child); //} if (child == this.mFocused) { child.clearFocus(); } //child.clearAccessibilityFocus(); this.cancelTouchTarget(child); //TODO impl when hover //this.cancelHoverTarget(child); if ((animate && child.getAnimation() != null) //|| (this.mTransitioningViews != null && this.mTransitioningViews.contains(child)) ) { this.addDisappearingView(child); } else if (child.mAttachInfo != null) { child.dispatchDetachedFromWindow(); } if (child.hasTransientState()) { this.childHasTransientStateChanged(child, false); } this.onViewRemoved(child); } /** * Attaches a view to this view group. Attaching a view assigns this group as the parent, * sets the layout parameters and puts the view in the list of children so that * it can be retrieved by calling {@link #getChildAt(int)}. * <p> * This method is intended to be lightweight and makes no assumptions about whether the * parent or child should be redrawn. Proper use of this method will include also making * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls. * For example, callers can {@link #post(Runnable) post} a {@link Runnable} * which performs a {@link #requestLayout()} on the next frame, after all detach/attach * calls are finished, causing layout to be run prior to redrawing the view hierarchy. * <p> * This method should be called only for views which were detached from their parent. * * @param child the child to attach * @param index the index at which the child should be attached * @param params the layout parameters of the child * * @see #removeDetachedView(View, boolean) * @see #detachAllViewsFromParent() * @see #detachViewFromParent(View) * @see #detachViewFromParent(int) */ attachViewToParent(child:View, index:number, params:ViewGroup.LayoutParams):void { child.mLayoutParams = params; if (index < 0) { index = this.mChildrenCount; } this.addInArray(child, index); child.mParent = this; child.mPrivateFlags = (child.mPrivateFlags & ~ViewGroup.PFLAG_DIRTY_MASK & ~ViewGroup.PFLAG_DRAWING_CACHE_VALID) | ViewGroup.PFLAG_DRAWN | ViewGroup.PFLAG_INVALIDATED; this.mPrivateFlags |= ViewGroup.PFLAG_INVALIDATED; if (child.hasFocus()) { this.requestChildFocus(child, child.findFocus()); } } /** * Detaches a range of views from their parents. Detaching a view should be followed * either by a call to * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be * temporary; reattachment or removal should happen within the same drawing cycle as * detachment. When a view is detached, its parent is null and cannot be retrieved by a * call to {@link #getChildAt(int)}. * * @param start the first index of the childrend range to detach * @param count the number of children to detach * * @see #detachViewFromParent(View) * @see #detachViewFromParent(int) * @see #detachAllViewsFromParent() * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) * @see #removeDetachedView(View, boolean) */ detachViewsFromParent(start:number, count:number=1):void { this.removeFromArray(start, count); } /** * Detaches all views from the parent. Detaching a view should be followed * either by a call to * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be * temporary; reattachment or removal should happen within the same drawing cycle as * detachment. When a view is detached, its parent is null and cannot be retrieved by a * call to {@link #getChildAt(int)}. * * @see #detachViewFromParent(View) * @see #detachViewFromParent(int) * @see #detachViewsFromParent(int, int) * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) * @see #removeDetachedView(View, boolean) */ detachAllViewsFromParent():void { const count:number = this.mChildrenCount; if (count <= 0) { return; } const children:View[] = this.mChildren; //this.mChildrenCount = 0; this.mChildren = []; for (let i:number = count - 1; i >= 0; i--) { children[i].mParent = null; //children[i] = null; this.removeChildElement(children[i].bindElement);//remove from dom } } indexOfChild(child:View):number { return this.mChildren.indexOf(child); } getChildCount():number { return this.mChildrenCount; } getChildAt(index:number) { if (index < 0 || index >= this.mChildrenCount) { return null; } return this.mChildren[index]; } bringChildToFront(child:View) { let index = this.indexOfChild(child); if (index >= 0) { this.removeFromArray(index); this.addInArray(child, this.mChildrenCount); child.mParent = this; this.requestLayout(); this.invalidate(); } } hasBooleanFlag(flag:number) { return (this.mGroupFlags & flag) == flag; } setBooleanFlag(flag:number, value:boolean) { if (value) { this.mGroupFlags |= flag; } else { this.mGroupFlags &= ~flag; } } dispatchGenericPointerEvent(event:MotionEvent):boolean{ // Send the event to the child under the pointer. const childrenCount = this.mChildrenCount; if (childrenCount != 0) { const children = this.mChildren; const x = event.getX(); const y = event.getY(); const customOrder = this.isChildrenDrawingOrderEnabled(); for (let i = childrenCount - 1; i >= 0; i--) { const childIndex = customOrder ? this.getChildDrawingOrder(childrenCount, i) : i; const child = children[childIndex]; if (!ViewGroup.canViewReceivePointerEvents(child) || !this.isTransformedTouchPointInView(x, y, child, null)) { continue; } if (this.dispatchTransformedGenericPointerEvent(event, child)) { return true; } } } // No child handled the event. Send it to this view group. return super.dispatchGenericPointerEvent(event); } private dispatchTransformedGenericPointerEvent(event:MotionEvent, child:View):boolean { const offsetX = this.mScrollX - child.mLeft; const offsetY = this.mScrollY - child.mTop; let handled:boolean; if (!child.hasIdentityMatrix()) { //TODO when Inverse matrix ok //let transformedEvent = MotionEvent.obtain(event); //transformedEvent.offsetLocation(offsetX, offsetY); //transformedEvent.transform(child.getInverseMatrix()); //handled = child.dispatchGenericMotionEvent(transformedEvent); //transformedEvent.recycle(); } else { event.offsetLocation(offsetX, offsetY); handled = child.dispatchGenericMotionEvent(event); event.offsetLocation(-offsetX, -offsetY); } return handled; } dispatchKeyEvent(event:android.view.KeyEvent):boolean { if ((this.mPrivateFlags & (View.PFLAG_FOCUSED | View.PFLAG_HAS_BOUNDS)) == (View.PFLAG_FOCUSED | View.PFLAG_HAS_BOUNDS)) { if (super.dispatchKeyEvent(event)) { return true; } } else if (this.mFocused != null && (this.mFocused.mPrivateFlags & View.PFLAG_HAS_BOUNDS) == View.PFLAG_HAS_BOUNDS) { if (this.mFocused.dispatchKeyEvent(event)) { return true; } } return false; } /** * {@inheritDoc} */ dispatchWindowFocusChanged(hasFocus:boolean):void { super.dispatchWindowFocusChanged(hasFocus); const count:number = this.mChildrenCount; const children:View[] = this.mChildren; for (let i:number = 0; i < count; i++) { children[i].dispatchWindowFocusChanged(hasFocus); } } addTouchables(views:java.util.ArrayList<android.view.View>):void { super.addTouchables(views); const count = this.mChildrenCount; const children = this.mChildren; for (let i = 0; i < count; i++) { const child = children[i]; if ((child.mViewFlags & View.VISIBILITY_MASK) == View.VISIBLE) { child.addTouchables(views); } } } onInterceptTouchEvent(ev:MotionEvent) { return false; } dispatchTouchEvent(ev:MotionEvent):boolean { let handled = false; if (this.onFilterTouchEventForSecurity(ev)) { let action = ev.getAction(); let actionMasked = action & MotionEvent.ACTION_MASK; // Handle an initial down. if (actionMasked == MotionEvent.ACTION_DOWN) { // Throw away all previous state when starting a new touch gesture. // The framework may have dropped the up or cancel event for the previous gesture // due to an app switch, ANR, or some other state change. this.cancelAndClearTouchTargets(ev); this.resetTouchState(); } // Check for interception. let intercepted; if (actionMasked == MotionEvent.ACTION_DOWN || this.mFirstTouchTarget != null) { let disallowIntercept = (this.mGroupFlags & ViewGroup.FLAG_DISALLOW_INTERCEPT) != 0; if (!disallowIntercept) { intercepted = this.onInterceptTouchEvent(ev); ev.setAction(action); // restore action in case it was changed } else { intercepted = false; } } else { // There are no touch targets and this action is not an initial down // so this view group continues to intercept touches. intercepted = true; } // Check for cancelation. let canceled = ViewGroup.resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL; // Update list of touch targets for pointer down, if needed. let split = (this.mGroupFlags & ViewGroup.FLAG_SPLIT_MOTION_EVENTS) != 0; let newTouchTarget:TouchTarget = null; let alreadyDispatchedToNewTouchTarget = false; if (!canceled && !intercepted) { if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { let actionIndex = ev.getActionIndex(); // always 0 for down let idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS; // Clean up earlier touch targets for this pointer id in case they // have become out of sync. this.removePointersFromTouchTargets(idBitsToAssign); let childrenCount = this.mChildrenCount; if (newTouchTarget == null && childrenCount != 0) { let x = ev.getX(actionIndex); let y = ev.getY(actionIndex); // Find a child that can receive the event. // Scan children from front to back. let children = this.mChildren; let customOrder = this.isChildrenDrawingOrderEnabled(); for (let i = childrenCount - 1; i >= 0; i--) { let childIndex = customOrder ? this.getChildDrawingOrder(childrenCount, i) : i; let child = children[childIndex]; if (!ViewGroup.canViewReceivePointerEvents(child) || !this.isTransformedTouchPointInView(x, y, child, null)) { continue; } newTouchTarget = this.getTouchTarget(child); if (newTouchTarget != null) { // Child is already receiving touch within its bounds. // Give it the new pointer in addition to the ones it is handling. newTouchTarget.pointerIdBits |= idBitsToAssign; break; } ViewGroup.resetCancelNextUpFlag(child); if (this.dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { // Child wants to receive touch within its bounds. this.mLastTouchDownTime = ev.getDownTime(); this.mLastTouchDownIndex = childIndex; this.mLastTouchDownX = ev.getX(); this.mLastTouchDownY = ev.getY(); newTouchTarget = this.addTouchTarget(child, idBitsToAssign); alreadyDispatchedToNewTouchTarget = true; break; } } } if (newTouchTarget == null && this.mFirstTouchTarget != null) { // Did not find a child to receive the event. // Assign the pointer to the least recently added target. newTouchTarget = this.mFirstTouchTarget; while (newTouchTarget.next != null) { newTouchTarget = newTouchTarget.next; } newTouchTarget.pointerIdBits |= idBitsToAssign; } } } // Dispatch to touch targets. if (this.mFirstTouchTarget == null) { // No touch targets so treat this as an ordinary view. handled = this.dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS); } else { // Dispatch to touch targets, excluding the new touch target if we already // dispatched to it. Cancel touch targets if necessary. let predecessor:TouchTarget = null; let target:TouchTarget = this.mFirstTouchTarget; while (target != null) { const next:TouchTarget = target.next; if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { handled = true; } else { let cancelChild = ViewGroup.resetCancelNextUpFlag(target.child) || intercepted; if (this.dispatchTransformedTouchEvent(ev, cancelChild, target.child, target.pointerIdBits)) { handled = true; } if (cancelChild) { if (predecessor == null) { this.mFirstTouchTarget = next; } else { predecessor.next = next; } target.recycle(); target = next; continue; } } predecessor = target; target = next; } } // Update list of touch targets for pointer up or cancel, if needed. if (canceled || actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { this.resetTouchState(); } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) { let actionIndex = ev.getActionIndex(); let idBitsToRemove = 1 << ev.getPointerId(actionIndex); this.removePointersFromTouchTargets(idBitsToRemove); } } return handled; } private resetTouchState() { this.clearTouchTargets(); ViewGroup.resetCancelNextUpFlag(this); this.mGroupFlags &= ~ViewGroup.FLAG_DISALLOW_INTERCEPT; } private static resetCancelNextUpFlag(view:View):boolean { if ((view.mPrivateFlags & View.PFLAG_CANCEL_NEXT_UP_EVENT) != 0) { view.mPrivateFlags &= ~View.PFLAG_CANCEL_NEXT_UP_EVENT; return true; } return false; } private clearTouchTargets() { let target = this.mFirstTouchTarget; if (target != null) { do { let next = target.next; target.recycle(); target = next; } while (target != null); this.mFirstTouchTarget = null; } } private cancelAndClearTouchTargets(event:MotionEvent) { if (this.mFirstTouchTarget != null) { let syntheticEvent = false; if (event == null) { let now = SystemClock.uptimeMillis(); event = MotionEvent.obtainWithAction(now, now, MotionEvent.ACTION_CANCEL, 0, 0); //event.setSource(InputDevice.SOURCE_TOUCHSCREEN); syntheticEvent = true; } for (let target = this.mFirstTouchTarget; target != null; target = target.next) { ViewGroup.resetCancelNextUpFlag(target.child); this.dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits); } this.clearTouchTargets(); if (syntheticEvent) { event.recycle(); } } } private getTouchTarget(child:View):TouchTarget { for (let target = this.mFirstTouchTarget; target != null; target = target.next) { if (target.child == child) { return target; } } return null; } private addTouchTarget(child:View, pointerIdBits:number):TouchTarget { let target = TouchTarget.obtain(child, pointerIdBits); target.next = this.mFirstTouchTarget; this.mFirstTouchTarget = target; return target; } private removePointersFromTouchTargets(pointerIdBits:number) { let predecessor:TouchTarget = null; let target = this.mFirstTouchTarget; while (target != null) { let next = target.next; if ((target.pointerIdBits & pointerIdBits) != 0) { target.pointerIdBits &= ~pointerIdBits; if (target.pointerIdBits == 0) { if (predecessor == null) { this.mFirstTouchTarget = next; } else { predecessor.next = next; } target.recycle(); target = next; continue; } } predecessor = target; target = next; } } private cancelTouchTarget(view:View) { let predecessor:TouchTarget = null; let target = this.mFirstTouchTarget; while (target != null) { let next = target.next; if (target.child == view) { if (predecessor == null) { this.mFirstTouchTarget = next; } else { predecessor.next = next; } target.recycle(); let now = SystemClock.uptimeMillis(); let event = MotionEvent.obtainWithAction(now, now, MotionEvent.ACTION_CANCEL, 0, 0); //event.setSource(InputDevice.SOURCE_TOUCHSCREEN); view.dispatchTouchEvent(event); event.recycle(); return; } predecessor = target; target = next; } } private static canViewReceivePointerEvents(child:View):boolean { return (child.mViewFlags & View.VISIBILITY_MASK) == View.VISIBLE || child.getAnimation() != null ; } protected isTransformedTouchPointInView(x:number, y:number, child:View, outLocalPoint:Point):boolean { let localX = x + this.mScrollX - child.mLeft; let localY = y + this.mScrollY - child.mTop; //if (! child.hasIdentityMatrix() && mAttachInfo != null) { //TODO when invers matrix ok // final float[] localXY = mAttachInfo.mTmpTransformLocation; // localXY[0] = localX; // localXY[1] = localY; // child.getInverseMatrix().mapPoints(localXY); // localX = localXY[0]; // localY = localXY[1]; //} let isInView = child.pointInView(localX, localY); if (isInView && outLocalPoint != null) { outLocalPoint.set(localX, localY); } return isInView; } private dispatchTransformedTouchEvent(event:MotionEvent, cancel:boolean, child:View, desiredPointerIdBits:number):boolean { let handled:boolean; // Canceling motions is a special case. We don't need to perform any transformations // or filtering. The important part is the action, not the contents. const oldAction = event.getAction(); if (cancel || oldAction == MotionEvent.ACTION_CANCEL) { event.setAction(MotionEvent.ACTION_CANCEL); if (child == null) { handled = super.dispatchTouchEvent(event); } else { handled = child.dispatchTouchEvent(event); } event.setAction(oldAction); return handled; } // Calculate the number of pointers to deliver. const oldPointerIdBits = event.getPointerIdBits(); const newPointerIdBits = oldPointerIdBits & desiredPointerIdBits; // If for some reason we ended up in an inconsistent state where it looks like we // might produce a motion event with no pointers in it, then drop the event. if (newPointerIdBits == 0) { return false; } // If the number of pointers is the same and we don't need to perform any fancy // irreversible transformations, then we can reuse the motion event for this // dispatch as long as we are careful to revert any changes we make. // Otherwise we need to make a copy. let transformedEvent:MotionEvent; if (newPointerIdBits == oldPointerIdBits) { if (child == null || child.hasIdentityMatrix()) { if (child == null) { handled = super.dispatchTouchEvent(event); } else { let offsetX = this.mScrollX - child.mLeft; let offsetY = this.mScrollY - child.mTop; event.offsetLocation(offsetX, offsetY); handled = child.dispatchTouchEvent(event); event.offsetLocation(-offsetX, -offsetY); } return handled; } transformedEvent = MotionEvent.obtain(event); } else { transformedEvent = event.split(newPointerIdBits); } // Perform any necessary transformations and dispatch. if (child == null) { handled = super.dispatchTouchEvent(transformedEvent); } else { let offsetX = this.mScrollX - child.mLeft; let offsetY = this.mScrollY - child.mTop; transformedEvent.offsetLocation(offsetX, offsetY); //if (! child.hasIdentityMatrix()) {//TODO when view InverseMatrix ok // transformedEvent.transform(child.getInverseMatrix()); //} handled = child.dispatchTouchEvent(transformedEvent); } // Done. transformedEvent.recycle(); return handled; } /** * Enable or disable the splitting of MotionEvents to multiple children during touch event * dispatch. This behavior is enabled by default for applications that target an * SDK version of {@link Build.VERSION_CODES#HONEYCOMB} or newer. * * <p>When this option is enabled MotionEvents may be split and dispatched to different child * views depending on where each pointer initially went down. This allows for user interactions * such as scrolling two panes of content independently, chording of buttons, and performing * independent gestures on different pieces of content. * * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple * child views. <code>false</code> to only allow one child view to be the target of * any MotionEvent received by this ViewGroup. * @attr ref android.R.styleable#ViewGroup_splitMotionEvents */ setMotionEventSplittingEnabled(split:boolean):void { // with gestures in progress when this is changed. if (split) { this.mGroupFlags |= ViewGroup.FLAG_SPLIT_MOTION_EVENTS; } else { this.mGroupFlags &= ~ViewGroup.FLAG_SPLIT_MOTION_EVENTS; } } /** * Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children. * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children. */ isMotionEventSplittingEnabled():boolean { return (this.mGroupFlags & ViewGroup.FLAG_SPLIT_MOTION_EVENTS) == ViewGroup.FLAG_SPLIT_MOTION_EVENTS; } /** * Indicates whether the children's drawing cache is used during a layout * animation. By default, the drawing cache is enabled but this will prevent * nested layout animations from working. To nest animations, you must disable * the cache. * * @return true if the animation cache is enabled, false otherwise * * @see #setAnimationCacheEnabled(boolean) * @see View#setDrawingCacheEnabled(boolean) */ isAnimationCacheEnabled():boolean { return (this.mGroupFlags & ViewGroup.FLAG_ANIMATION_CACHE) == ViewGroup.FLAG_ANIMATION_CACHE; } /** * Enables or disables the children's drawing cache during a layout animation. * By default, the drawing cache is enabled but this will prevent nested * layout animations from working. To nest animations, you must disable the * cache. * * @param enabled true to enable the animation cache, false otherwise * * @see #isAnimationCacheEnabled() * @see View#setDrawingCacheEnabled(boolean) */ setAnimationCacheEnabled(enabled:boolean):void { this.setBooleanFlag(ViewGroup.FLAG_ANIMATION_CACHE, enabled); } /** * Indicates whether this ViewGroup will always try to draw its children using their * drawing cache. By default this property is enabled. * * @return true if the animation cache is enabled, false otherwise * * @see #setAlwaysDrawnWithCacheEnabled(boolean) * @see #setChildrenDrawnWithCacheEnabled(boolean) * @see View#setDrawingCacheEnabled(boolean) */ isAlwaysDrawnWithCacheEnabled():boolean { return (this.mGroupFlags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) == ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE; } /** * Indicates whether this ViewGroup will always try to draw its children using their * drawing cache. This property can be set to true when the cache rendering is * slightly different from the children's normal rendering. Renderings can be different, * for instance, when the cache's quality is set to low. * * When this property is disabled, the ViewGroup will use the drawing cache of its * children only when asked to. It's usually the task of subclasses to tell ViewGroup * when to start using the drawing cache and when to stop using it. * * @param always true to always draw with the drawing cache, false otherwise * * @see #isAlwaysDrawnWithCacheEnabled() * @see #setChildrenDrawnWithCacheEnabled(boolean) * @see View#setDrawingCacheEnabled(boolean) * @see View#setDrawingCacheQuality(int) */ setAlwaysDrawnWithCacheEnabled(always:boolean):void { this.setBooleanFlag(ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE, always); } /** * Indicates whether the ViewGroup is currently drawing its children using * their drawing cache. * * @return true if children should be drawn with their cache, false otherwise * * @see #setAlwaysDrawnWithCacheEnabled(boolean) * @see #setChildrenDrawnWithCacheEnabled(boolean) */ isChildrenDrawnWithCacheEnabled():boolean { return (this.mGroupFlags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) == ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE; } /** * Tells the ViewGroup to draw its children using their drawing cache. This property * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache * will be used only if it has been enabled. * * Subclasses should call this method to start and stop using the drawing cache when * they perform performance sensitive operations, like scrolling or animating. * * @param enabled true if children should be drawn with their cache, false otherwise * * @see #setAlwaysDrawnWithCacheEnabled(boolean) * @see #isChildrenDrawnWithCacheEnabled() */ setChildrenDrawnWithCacheEnabled(enabled:boolean):void { this.setBooleanFlag(ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled); } /** * Enables or disables the drawing cache for each child of this view group. * * @param enabled true to enable the cache, false to dispose of it */ setChildrenDrawingCacheEnabled(enabled:boolean):void { if (enabled || (this.mPersistentDrawingCache & ViewGroup.PERSISTENT_ALL_CACHES) != ViewGroup.PERSISTENT_ALL_CACHES) { const children:View[] = this.mChildren; const count:number = this.mChildrenCount; for (let i:number = 0; i < count; i++) { children[i].setDrawingCacheEnabled(enabled); } } } protected onAnimationStart():void { super.onAnimationStart(); // When this ViewGroup's animation starts, build the cache for the children if ((this.mGroupFlags & ViewGroup.FLAG_ANIMATION_CACHE) == ViewGroup.FLAG_ANIMATION_CACHE) { const count:number = this.mChildrenCount; const children:View[] = this.mChildren; const buildCache:boolean = !this.isHardwareAccelerated(); for (let i:number = 0; i < count; i++) { const child:View = children[i]; if ((child.mViewFlags & ViewGroup.VISIBILITY_MASK) == ViewGroup.VISIBLE) { child.setDrawingCacheEnabled(true); if (buildCache) { child.buildDrawingCache(true); } } } this.mGroupFlags |= ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE; } } protected onAnimationEnd():void { super.onAnimationEnd(); // When this ViewGroup's animation ends, destroy the cache of the children if ((this.mGroupFlags & ViewGroup.FLAG_ANIMATION_CACHE) == ViewGroup.FLAG_ANIMATION_CACHE) { this.mGroupFlags &= ~ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE; if ((this.mPersistentDrawingCache & ViewGroup.PERSISTENT_ANIMATION_CACHE) == 0) { this.setChildrenDrawingCacheEnabled(false); } } } /** * Returns an integer indicating what types of drawing caches are kept in memory. * * @see #setPersistentDrawingCache(int) * @see #setAnimationCacheEnabled(boolean) * * @return one or a combination of {@link #PERSISTENT_NO_CACHE}, * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} * and {@link #PERSISTENT_ALL_CACHES} */ getPersistentDrawingCache():number { return this.mPersistentDrawingCache; } /** * Indicates what types of drawing caches should be kept in memory after * they have been created. * * @see #getPersistentDrawingCache() * @see #setAnimationCacheEnabled(boolean) * * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE}, * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} * and {@link #PERSISTENT_ALL_CACHES} */ setPersistentDrawingCache(drawingCacheToKeep:number):void { this.mPersistentDrawingCache = drawingCacheToKeep & ViewGroup.PERSISTENT_ALL_CACHES; } isChildrenDrawingOrderEnabled():boolean { return (this.mGroupFlags & ViewGroup.FLAG_USE_CHILD_DRAWING_ORDER) == ViewGroup.FLAG_USE_CHILD_DRAWING_ORDER; } setChildrenDrawingOrderEnabled(enabled:boolean) { this.setBooleanFlag(ViewGroup.FLAG_USE_CHILD_DRAWING_ORDER, enabled); } getChildDrawingOrder(childCount:number , i:number):number { return i; } public generateLayoutParamsFromAttr(attrs:HTMLElement):ViewGroup.LayoutParams { return new ViewGroup.LayoutParams(this.getContext(), attrs); } protected generateLayoutParams(p:ViewGroup.LayoutParams):ViewGroup.LayoutParams { return p; } protected generateDefaultLayoutParams():ViewGroup.LayoutParams { return new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); } measureChildren(widthMeasureSpec:number, heightMeasureSpec:number) { const size = this.mChildren.length; for (let i = 0; i < size; ++i) { const child = this.mChildren[i]; if ((child.mViewFlags & View.VISIBILITY_MASK) != View.GONE) { this.measureChild(child, widthMeasureSpec, heightMeasureSpec); } } } protected measureChild(child:View, parentWidthMeasureSpec:number, parentHeightMeasureSpec:number) { let lp = child.getLayoutParams(); const childWidthMeasureSpec = ViewGroup.getChildMeasureSpec(parentWidthMeasureSpec, this.mPaddingLeft + this.mPaddingRight, lp.width); const childHeightMeasureSpec = ViewGroup.getChildMeasureSpec(parentHeightMeasureSpec, this.mPaddingTop + this.mPaddingBottom, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } protected measureChildWithMargins(child:View, parentWidthMeasureSpec:number, widthUsed:number, parentHeightMeasureSpec:number, heightUsed:number) { let lp = child.getLayoutParams(); if (lp instanceof ViewGroup.MarginLayoutParams) { const childWidthMeasureSpec = ViewGroup.getChildMeasureSpec(parentWidthMeasureSpec, this.mPaddingLeft + this.mPaddingRight + lp.leftMargin + lp.rightMargin + widthUsed, lp.width); const childHeightMeasureSpec = ViewGroup.getChildMeasureSpec(parentHeightMeasureSpec, this.mPaddingTop + this.mPaddingBottom + lp.topMargin + lp.bottomMargin + heightUsed, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } static getChildMeasureSpec(spec:number, padding:number, childDimension:number):number { let MeasureSpec = View.MeasureSpec; let specMode = MeasureSpec.getMode(spec); let specSize = MeasureSpec.getSize(spec); let size = Math.max(0, specSize - padding); let resultSize = 0; let resultMode = 0; switch (specMode) { // Parent has imposed an exact size on us case MeasureSpec.EXACTLY: if (childDimension >= 0) { resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == ViewGroup.LayoutParams.MATCH_PARENT) { // Child wants to be our size. So be it. resultSize = size; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == ViewGroup.LayoutParams.WRAP_CONTENT) { // Child wants to determine its own size. It can't be // bigger than us. resultSize = size; resultMode = MeasureSpec.AT_MOST; } break; // Parent has imposed a maximum size on us case MeasureSpec.AT_MOST: if (childDimension >= 0) { // Child wants a specific size... so be it resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == ViewGroup.LayoutParams.MATCH_PARENT) { // Child wants to be our size, but our size is not fixed. // Constrain child to not be bigger than us. resultSize = size; resultMode = MeasureSpec.AT_MOST; } else if (childDimension == ViewGroup.LayoutParams.WRAP_CONTENT) { // Child wants to determine its own size. It can't be // bigger than us. resultSize = size; resultMode = MeasureSpec.AT_MOST; } break; // Parent asked to see how big we want to be case MeasureSpec.UNSPECIFIED: if (childDimension >= 0) { // Child wants a specific size... let him have it resultSize = childDimension; resultMode = MeasureSpec.EXACTLY; } else if (childDimension == ViewGroup.LayoutParams.MATCH_PARENT) { // Child wants to be our size... find out how big it should // be resultSize = 0; resultMode = MeasureSpec.UNSPECIFIED; } else if (childDimension == ViewGroup.LayoutParams.WRAP_CONTENT) { // Child wants to determine its own size.... find out how // big it should be resultSize = 0; resultMode = MeasureSpec.UNSPECIFIED; } break; } return MeasureSpec.makeMeasureSpec(resultSize, resultMode); } /** * Removes any pending animations for views that have been removed. Call * this if you don't want animations for exiting views to stack up. */ clearDisappearingChildren():void { if (this.mDisappearingChildren != null) { this.mDisappearingChildren.clear(); this.invalidate(); } } /** * Add a view which is removed from mChildren but still needs animation * * @param v View to add */ private addDisappearingView(v:View):void { let disappearingChildren:ArrayList<View> = this.mDisappearingChildren; if (disappearingChildren == null) { disappearingChildren = this.mDisappearingChildren = new ArrayList<View>(); } disappearingChildren.add(v); } /** * Cleanup a view when its animation is done. This may mean removing it from * the list of disappearing views. * * @param view The view whose animation has finished * @param animation The animation, cannot be null */ finishAnimatingView(view:View, animation:Animation):void { const disappearingChildren:ArrayList<View> = this.mDisappearingChildren; if (disappearingChildren != null) { if (disappearingChildren.contains(view)) { disappearingChildren.remove(view); if (view.mAttachInfo != null) { view.dispatchDetachedFromWindow(); } view.clearAnimation(); this.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; } } if (animation != null && !animation.getFillAfter()) { view.clearAnimation(); } if ((view.mPrivateFlags & ViewGroup.PFLAG_ANIMATION_STARTED) == ViewGroup.PFLAG_ANIMATION_STARTED) { view.onAnimationEnd(); // Should be performed by onAnimationEnd() but this avoid an infinite loop, // so we'd rather be safe than sorry view.mPrivateFlags &= ~ViewGroup.PFLAG_ANIMATION_STARTED; // Draw one more frame after the animation is done this.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; } } dispatchAttachedToWindow(info:View.AttachInfo, visibility:number) { this.mGroupFlags |= ViewGroup.FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW; super.dispatchAttachedToWindow(info, visibility); this.mGroupFlags &= ~ViewGroup.FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW; const count = this.mChildrenCount; const children = this.mChildren; for (let i = 0; i < count; i++) { const child = children[i]; child.dispatchAttachedToWindow(info, visibility | (child.mViewFlags & View.VISIBILITY_MASK)); } } protected onAttachedToWindow() { super.onAttachedToWindow(); this.clearCachedLayoutMode(); } protected onDetachedFromWindow() { super.onDetachedFromWindow(); this.clearCachedLayoutMode(); } dispatchDetachedFromWindow() { // If we still have a touch target, we are still in the process of // dispatching motion events to a child; we need to get rid of that // child to avoid dispatching events to it after the window is torn // down. To make sure we keep the child in a consistent state, we // first send it an ACTION_CANCEL motion event. this.cancelAndClearTouchTargets(null); // Similarly, set ACTION_EXIT to all hover targets and clear them. //this.exitHoverTargets(); // In case view is detached while transition is running this.mLayoutCalledWhileSuppressed = false; this.mChildren.forEach((child)=>child.dispatchDetachedFromWindow()); super.dispatchDetachedFromWindow(); } /** * {@inheritDoc} */ dispatchDisplayHint(hint:number):void { super.dispatchDisplayHint(hint); const count:number = this.mChildrenCount; const children:View[] = this.mChildren; for (let i:number = 0; i < count; i++) { children[i].dispatchDisplayHint(hint); } } /** * Called when a view's visibility has changed. Notify the parent to take any appropriate * action. * * @param child The view whose visibility has changed * @param oldVisibility The previous visibility value (GONE, INVISIBLE, or VISIBLE). * @param newVisibility The new visibility value (GONE, INVISIBLE, or VISIBLE). * @hide */ onChildVisibilityChanged(child:View, oldVisibility:number, newVisibility:number):void { //if (this.mTransition != null) { // if (newVisibility == ViewGroup.VISIBLE) { // this.mTransition.showChild(this, child, oldVisibility); // } else { // this.mTransition.hideChild(this, child, newVisibility); // if (this.mTransitioningViews != null && this.mTransitioningViews.contains(child)) { // // and don't need special handling during drawChild() // if (this.mVisibilityChangingChildren == null) { // this.mVisibilityChangingChildren = new ArrayList<View>(); // } // this.mVisibilityChangingChildren.add(child); // this.addDisappearingView(child); // } // } //} //// in all cases, for drags //if (this.mCurrentDrag != null) { // if (newVisibility == ViewGroup.VISIBLE) { // this.notifyChildOfDrag(child); // } //} } dispatchVisibilityChanged(changedView:View, visibility:number) { super.dispatchVisibilityChanged(changedView, visibility); const count = this.mChildrenCount; let children = this.mChildren; for (let i = 0; i < count; i++) { children[i].dispatchVisibilityChanged(changedView, visibility); } } dispatchSetSelected(selected:boolean) { const children = this.mChildren; const count = this.mChildrenCount; for (let i = 0; i < count; i++) { children[i].setSelected(selected); } } dispatchSetActivated(activated:boolean) { const children = this.mChildren; const count = this.mChildrenCount; for (let i = 0; i < count; i++) { children[i].setActivated(activated); } } dispatchSetPressed(pressed:boolean):void { const children = this.mChildren; const count = this.mChildrenCount; for (let i = 0; i < count; i++) { const child = children[i]; // Children that are clickable on their own should not // show a pressed state when their parent view does. // Clearing a pressed state always propagates. if (!pressed || (!child.isClickable() && !child.isLongClickable())) { child.setPressed(pressed); } } } dispatchCancelPendingInputEvents():void { super.dispatchCancelPendingInputEvents(); const children:View[] = this.mChildren; const count:number = this.mChildrenCount; for (let i:number = 0; i < count; i++) { children[i].dispatchCancelPendingInputEvents(); } } offsetDescendantRectToMyCoords(descendant:View, rect:Rect){ this.offsetRectBetweenParentAndChild(descendant, rect, true, false); } offsetRectIntoDescendantCoords(descendant:View, rect:Rect) { this.offsetRectBetweenParentAndChild(descendant, rect, false, false); } offsetRectBetweenParentAndChild(descendant:View, rect:Rect, offsetFromChildToParent:boolean, clipToBounds:boolean){ // already in the same coord system :) if (descendant == this) { return; } let theParent = descendant.mParent; // search and offset up to the parent while ((theParent != null) && (theParent instanceof View) && (theParent != this)) { if (offsetFromChildToParent) { rect.offset(descendant.mLeft - descendant.mScrollX, descendant.mTop - descendant.mScrollY); if (clipToBounds) { let p = <View><any>theParent; rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); } } else { if (clipToBounds) { let p = <View><any>theParent; rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); } rect.offset(descendant.mScrollX - descendant.mLeft, descendant.mScrollY - descendant.mTop); } descendant = <View><any>theParent; theParent = descendant.mParent; } // now that we are up to this view, need to offset one more time // to get into our coordinate space if (theParent == this) { if (offsetFromChildToParent) { rect.offset(descendant.mLeft - descendant.mScrollX, descendant.mTop - descendant.mScrollY); } else { rect.offset(descendant.mScrollX - descendant.mLeft, descendant.mScrollY - descendant.mTop); } } else { throw new Error("parameter must be a descendant of this view"); } } offsetChildrenTopAndBottom(offset:number) { const count = this.mChildrenCount; const children = this.mChildren; for (let i = 0; i < count; i++) { const v = children[i]; v.mTop += offset; v.mBottom += offset; } this.invalidateViewProperty(false, false); } suppressLayout(suppress:boolean) { this.mSuppressLayout = suppress; if (!suppress) { if (this.mLayoutCalledWhileSuppressed) { this.requestLayout(); this.mLayoutCalledWhileSuppressed = false; } } } isLayoutSuppressed() { return this.mSuppressLayout; } layout(l:number, t:number, r:number, b:number):void { if (!this.mSuppressLayout) { super.layout(l, t, r, b); } else { // record the fact that we noop'd it; request layout when transition finishes this.mLayoutCalledWhileSuppressed = true; } } canAnimate():boolean { //layout animation no impl return false; } protected abstract onLayout(changed:boolean, l:number, t:number, r:number, b:number):void; getChildVisibleRect(child:View, r:Rect, offset:Point):boolean{ // It doesn't make a whole lot of sense to call this on a view that isn't attached, // but for some simple tests it can be useful. If we don't have attach info this // will allocate memory. const rect = this.mAttachInfo != null ? this.mAttachInfo.mTmpTransformRect : new Rect(); rect.set(r); if (!child.hasIdentityMatrix()) { child.getMatrix().mapRect(rect); } let dx = child.mLeft - this.mScrollX; let dy = child.mTop - this.mScrollY; rect.offset(dx, dy); if (offset != null) { if (!child.hasIdentityMatrix()) { let position = this.mAttachInfo != null ? this.mAttachInfo.mTmpTransformLocation : androidui.util.ArrayCreator.newNumberArray(2); position[0] = offset.x; position[1] = offset.y; child.getMatrix().mapPoints(position); offset.x = Math.floor(position[0] + 0.5); offset.y = Math.floor(position[1] + 0.5); } offset.x += dx; offset.y += dy; } if (rect.intersect(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop)) { if (this.mParent == null) return true; r.set(rect); return this.mParent.getChildVisibleRect(this, r, offset); } return false; } protected dispatchDraw(canvas:Canvas) { let count = this.mChildrenCount; let children = this.mChildren; let flags = this.mGroupFlags; //TODO when layout animation impl //if ((flags & ViewGroup.FLAG_RUN_ANIMATION) != 0 && this.canAnimate()) { // const cache:boolean = (this.mGroupFlags & ViewGroup.FLAG_ANIMATION_CACHE) == ViewGroup.FLAG_ANIMATION_CACHE; // const buildCache:boolean = !this.isHardwareAccelerated(); // for (let i:number = 0; i < count; i++) { // const child:View = children[i]; // if ((child.mViewFlags & ViewGroup.VISIBILITY_MASK) == ViewGroup.VISIBLE) { // const params:ViewGroup.LayoutParams = child.getLayoutParams(); // this.attachLayoutAnimationParameters(child, params, i, count); // this.bindLayoutAnimation(child); // if (cache) { // child.setDrawingCacheEnabled(true); // if (buildCache) { // child.buildDrawingCache(true); // } // } // } // } // const controller:LayoutAnimationController = this.mLayoutAnimationController; // if (controller.willOverlap()) { // this.mGroupFlags |= ViewGroup.FLAG_OPTIMIZE_INVALIDATE; // } // controller.start(); // this.mGroupFlags &= ~ViewGroup.FLAG_RUN_ANIMATION; // this.mGroupFlags &= ~ViewGroup.FLAG_ANIMATION_DONE; // if (cache) { // this.mGroupFlags |= ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE; // } // if (this.mAnimationListener != null) { // this.mAnimationListener.onAnimationStart(controller.getAnimation()); // } //} let saveCount = 0; let clipToPadding = (flags & ViewGroup.CLIP_TO_PADDING_MASK) == ViewGroup.CLIP_TO_PADDING_MASK; if (clipToPadding) { saveCount = canvas.save(); canvas.clipRect(this.mScrollX + this.mPaddingLeft, this.mScrollY + this.mPaddingTop, this.mScrollX + this.mRight - this.mLeft - this.mPaddingRight, this.mScrollY + this.mBottom - this.mTop - this.mPaddingBottom); } // We will draw our child's animation, let's reset the flag this.mPrivateFlags &= ~ViewGroup.PFLAG_DRAW_ANIMATION; this.mGroupFlags &= ~ViewGroup.FLAG_INVALIDATE_REQUIRED; let more:boolean = false; const drawingTime:number = this.getDrawingTime(); if ((flags & ViewGroup.FLAG_USE_CHILD_DRAWING_ORDER) == 0) { for (let i:number = 0; i < count; i++) { const child:View = children[i]; if ((child.mViewFlags & ViewGroup.VISIBILITY_MASK) == ViewGroup.VISIBLE || child.getAnimation() != null) { more = this.drawChild(canvas, child, drawingTime) || more; } } } else { for (let i:number = 0; i < count; i++) { const child:View = children[this.getChildDrawingOrder(count, i)]; if ((child.mViewFlags & ViewGroup.VISIBILITY_MASK) == ViewGroup.VISIBLE || child.getAnimation() != null) { more = this.drawChild(canvas, child, drawingTime) || more; } } } // Draw any disappearing views that have animations if (this.mDisappearingChildren != null) { const disappearingChildren:ArrayList<View> = this.mDisappearingChildren; const disappearingCount:number = disappearingChildren.size() - 1; // Go backwards -- we may delete as animations finish for (let i:number = disappearingCount; i >= 0; i--) { const child:View = disappearingChildren.get(i); more = this.drawChild(canvas, child, drawingTime) || more; } } if (clipToPadding) { canvas.restoreToCount(saveCount); } // mGroupFlags might have been updated by drawChild() flags = this.mGroupFlags; if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == ViewGroup.FLAG_INVALIDATE_REQUIRED) { this.invalidate(true); } } protected drawChild(canvas:Canvas, child:View , drawingTime:number):boolean { return child.drawFromParent(canvas, this, drawingTime); } protected drawableStateChanged() { super.drawableStateChanged(); if ((this.mGroupFlags & ViewGroup.FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) { if ((this.mGroupFlags & ViewGroup.FLAG_ADD_STATES_FROM_CHILDREN) != 0) { throw new Error("addStateFromChildren cannot be enabled if a" + " child has duplicateParentState set to true"); } const children = this.mChildren; const count = this.mChildrenCount; for (let i = 0; i < count; i++) { const child = children[i]; if ((child.mViewFlags & View.DUPLICATE_PARENT_STATE) != 0) { child.refreshDrawableState(); } } } } jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); const children = this.mChildren; const count = this.mChildrenCount; for (let i = 0; i < count; i++) { children[i].jumpDrawablesToCurrentState(); } } protected onCreateDrawableState(extraSpace:number):Array<number> { if ((this.mGroupFlags & ViewGroup.FLAG_ADD_STATES_FROM_CHILDREN) == 0) { return super.onCreateDrawableState(extraSpace); } let need = 0; let n = this.getChildCount(); for (let i = 0; i < n; i++) { let childState = this.getChildAt(i).getDrawableState(); if (childState != null) { need += childState.length; } } let state = super.onCreateDrawableState(extraSpace + need); for (let i = 0; i < n; i++) { let childState = this.getChildAt(i).getDrawableState(); if (childState != null) { state = View.mergeDrawableStates(state, childState); } } return state; } setAddStatesFromChildren(addsStates:boolean) { if (addsStates) { this.mGroupFlags |= ViewGroup.FLAG_ADD_STATES_FROM_CHILDREN; } else { this.mGroupFlags &= ~ViewGroup.FLAG_ADD_STATES_FROM_CHILDREN; } this.refreshDrawableState(); } addStatesFromChildren():boolean { return (this.mGroupFlags & ViewGroup.FLAG_ADD_STATES_FROM_CHILDREN) != 0; } childDrawableStateChanged(child:android.view.View) { if ((this.mGroupFlags & ViewGroup.FLAG_ADD_STATES_FROM_CHILDREN) != 0) { this.refreshDrawableState(); } } getClipChildren():boolean { return ((this.mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); } setClipChildren(clipChildren:boolean) { let previousValue = (this.mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN; if (clipChildren != previousValue) { this.setBooleanFlag(ViewGroup.FLAG_CLIP_CHILDREN, clipChildren); } } setClipToPadding(clipToPadding:boolean) { this.setBooleanFlag(ViewGroup.FLAG_CLIP_TO_PADDING, clipToPadding); } isClipToPadding():boolean{ return (this.mGroupFlags & ViewGroup.FLAG_CLIP_TO_PADDING) == ViewGroup.FLAG_CLIP_TO_PADDING; } invalidateChild(child:View, dirty:Rect):void { let parent = this; const attachInfo = this.mAttachInfo; if (attachInfo != null) { // If the child is drawing an animation, we want to copy this flag onto // ourselves and the parent to make sure the invalidate request goes // through const drawAnimation = (child.mPrivateFlags & View.PFLAG_DRAW_ANIMATION) == View.PFLAG_DRAW_ANIMATION; // Check whether the child that requests the invalidate is fully opaque // Views being animated or transformed are not considered opaque because we may // be invalidating their old position and need the parent to paint behind them. let childMatrix = child.getMatrix(); const isOpaque = child.isOpaque() && !drawAnimation && child.getAnimation() == null && childMatrix.isIdentity(); // Mark the child as dirty, using the appropriate flag // Make sure we do not set both flags at the same time let opaqueFlag = isOpaque ? View.PFLAG_DIRTY_OPAQUE : View.PFLAG_DIRTY; if (child.mLayerType != View.LAYER_TYPE_NONE) { this.mPrivateFlags |= View.PFLAG_INVALIDATED; this.mPrivateFlags &= ~View.PFLAG_DRAWING_CACHE_VALID; child.mLocalDirtyRect.union(dirty); } const location = attachInfo.mInvalidateChildLocation; location[0] = child.mLeft; location[1] = child.mTop; if (!childMatrix.isIdentity() || (this.mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { let boundingRect = attachInfo.mTmpTransformRect; boundingRect.set(dirty); let transformMatrix:Matrix; if ((this.mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { let t = attachInfo.mTmpTransformation; let transformed = this.getChildStaticTransformation(child, t); if (transformed) { transformMatrix = attachInfo.mTmpMatrix; transformMatrix.set(t.getMatrix()); if (!childMatrix.isIdentity()) { transformMatrix.preConcat(childMatrix); } } else { transformMatrix = childMatrix; } } else { transformMatrix = childMatrix; } transformMatrix.mapRect(boundingRect); dirty.set(boundingRect); } do { let view:View = null; if (parent instanceof View) { view = <View> parent; } if (drawAnimation) { if (view != null) { view.mPrivateFlags |= ViewGroup.PFLAG_DRAW_ANIMATION; } else if (parent instanceof ViewRootImpl) { (<ViewRootImpl><any>parent).mIsAnimating = true; } } // If the parent is dirty opaque or not dirty, mark it dirty with the opaque // flag coming from the child that initiated the invalidate if (view != null) { //if ((view.mViewFlags & ViewGroup.FADING_EDGE_MASK) != 0 &&//TODO when fade edge effect ok // view.getSolidColor() == 0) { opaqueFlag = View.PFLAG_DIRTY; //} if ((view.mPrivateFlags & View.PFLAG_DIRTY_MASK) != View.PFLAG_DIRTY) { view.mPrivateFlags = (view.mPrivateFlags & ~View.PFLAG_DIRTY_MASK) | opaqueFlag; } } parent = <any>parent.invalidateChildInParent(location, dirty); if (view != null) { // Account for transform on current parent let m = view.getMatrix(); if (!m.isIdentity()) { let boundingRect = attachInfo.mTmpTransformRect; boundingRect.set(dirty); m.mapRect(boundingRect); dirty.set(boundingRect); } } } while (parent != null); } } invalidateChildInParent(location:Array<number>, dirty:Rect):ViewParent { if ((this.mPrivateFlags & View.PFLAG_DRAWN) == View.PFLAG_DRAWN || (this.mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) == View.PFLAG_DRAWING_CACHE_VALID) { if ((this.mGroupFlags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) != ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { dirty.offset(location[0] - this.mScrollX, location[1] - this.mScrollY); if ((this.mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) == 0) { dirty.union(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); } const left = this.mLeft; const top = this.mTop; if ((this.mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN) { if (!dirty.intersect(0, 0, this.mRight - left, this.mBottom - top)) { dirty.setEmpty(); } } this.mPrivateFlags &= ~View.PFLAG_DRAWING_CACHE_VALID; location[0] = left; location[1] = top; if (this.mLayerType != View.LAYER_TYPE_NONE) { this.mPrivateFlags |= View.PFLAG_INVALIDATED; this.mLocalDirtyRect.union(dirty); } return this.mParent; } else { this.mPrivateFlags &= ~View.PFLAG_DRAWN & ~View.PFLAG_DRAWING_CACHE_VALID; location[0] = this.mLeft; location[1] = this.mTop; if ((this.mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN) { dirty.set(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); } else { // in case the dirty rect extends outside the bounds of this container dirty.union(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); } if (this.mLayerType != View.LAYER_TYPE_NONE) { this.mPrivateFlags |= View.PFLAG_INVALIDATED; this.mLocalDirtyRect.union(dirty); } return this.mParent; } } return null; } invalidateChildFast(child:View, dirty:Rect):void{ let parent:ViewParent = this; const attachInfo = this.mAttachInfo; if (attachInfo != null) { if (child.mLayerType != View.LAYER_TYPE_NONE) { child.mLocalDirtyRect.union(dirty); } let left = child.mLeft; let top = child.mTop; if (!child.getMatrix().isIdentity()) { child.transformRect(dirty); } do { if (parent instanceof ViewGroup) { let parentVG = <ViewGroup> parent; if (parentVG.mLayerType != View.LAYER_TYPE_NONE) { // Layered parents should be recreated, not just re-issued parentVG.invalidate(); parent = null; } else { parent = parentVG.invalidateChildInParentFast(left, top, dirty); left = parentVG.mLeft; top = parentVG.mTop; } } else { // Reached the top; this calls into the usual invalidate method in // ViewRootImpl, which schedules a traversal const location = attachInfo.mInvalidateChildLocation; location[0] = left; location[1] = top; parent = parent.invalidateChildInParent(location, dirty); } } while (parent != null); } } invalidateChildInParentFast(left:number, top:number, dirty:Rect):ViewParent{ if ((this.mPrivateFlags & View.PFLAG_DRAWN) == View.PFLAG_DRAWN || (this.mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) == View.PFLAG_DRAWING_CACHE_VALID) { dirty.offset(left - this.mScrollX, top - this.mScrollY); if ((this.mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) == 0) { dirty.union(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); } if ((this.mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) == 0 || dirty.intersect(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop)) { if (this.mLayerType != View.LAYER_TYPE_NONE) { this.mLocalDirtyRect.union(dirty); } if (!this.getMatrix().isIdentity()) { this.transformRect(dirty); } return this.mParent; } } return null; } /** * Sets <code>t</code> to be the static transformation of the child, if set, returning a * boolean to indicate whether a static transform was set. The default implementation * simply returns <code>false</code>; subclasses may override this method for different * behavior. {@link #setStaticTransformationsEnabled(boolean)} must be set to true * for this method to be called. * * @param child The child view whose static transform is being requested * @param t The Transformation which will hold the result * @return true if the transformation was set, false otherwise * @see #setStaticTransformationsEnabled(boolean) */ protected getChildStaticTransformation(child:View, t:Transformation):boolean { return false; } getChildTransformation():Transformation { if (this.mChildTransformation == null) { this.mChildTransformation = new Transformation(); } return this.mChildTransformation; } protected findViewTraversal(id:string):View { if (id == this.mID) { return this; } let where:View[] = this.mChildren; const len = this.mChildrenCount; for (let i = 0; i < len; i++) { let v = where[i]; if ((v.mPrivateFlags & View.PFLAG_IS_ROOT_NAMESPACE) == 0) { v = v.findViewById(id); if (v != null) { return v; } } } return null; } protected findViewWithTagTraversal(tag:any):View { if (tag != null && tag === this.mTag) { return this; } let where:View[] = this.mChildren; const len = this.mChildrenCount; for (let i = 0; i < len; i++) { let v = where[i]; if ((v.mPrivateFlags & View.PFLAG_IS_ROOT_NAMESPACE) == 0) { v = v.findViewWithTag(tag); if (v != null) { return v; } } } return null; } protected findViewByPredicateTraversal(predicate:View.Predicate<View>, childToSkip:View):View { if (predicate.apply(this)) { return this; } const where = this.mChildren; const len = this.mChildrenCount; for (let i = 0; i < len; i++) { let v = where[i]; if (v != childToSkip && (v.mPrivateFlags & View.PFLAG_IS_ROOT_NAMESPACE) == 0) { v = v.findViewByPredicate(predicate); if (v != null) { return v; } } } return null; } requestDisallowInterceptTouchEvent(disallowIntercept:boolean) { if (disallowIntercept == ((this.mGroupFlags & ViewGroup.FLAG_DISALLOW_INTERCEPT) != 0)) { // We're already in this state, assume our ancestors are too return; } if (disallowIntercept) { this.mGroupFlags |= ViewGroup.FLAG_DISALLOW_INTERCEPT; } else { this.mGroupFlags &= ~ViewGroup.FLAG_DISALLOW_INTERCEPT; } // Pass it up to our parent if (this.mParent != null) { this.mParent.requestDisallowInterceptTouchEvent(disallowIntercept); } } shouldDelayChildPressedState():boolean { return true; } onSetLayoutParams(child:View, layoutParams:ViewGroup.LayoutParams) { } } export module ViewGroup { export class LayoutParams extends java.lang.JavaObject { private static ClassAttrBinderClazzMap = new Map<java.lang.Class, AttrBinder.ClassBinderMap>(); static FILL_PARENT = -1; static MATCH_PARENT = -1; static WRAP_CONTENT = -2; public width = 0; public height = 0; private _attrBinder:AttrBinder; constructor(context:Context, attrs:HTMLElement); constructor(width:number, height:number); constructor(src:LayoutParams); constructor(...args); constructor(...args) { super(); if (args[0] instanceof Context && args[1] instanceof HTMLElement) { const a = (<Context>args[0]).obtainStyledAttributes(args[1]); this.setBaseAttributes(a, 'layout_width', 'layout_height'); a.recycle(); } else if (typeof args[0] === 'number' && typeof args[1] === 'number') { this.width = args[0]; this.height = args[1]; } else if (args[0] instanceof LayoutParams) { this.width = args[0].width; this.height = args[0].height; } else if (args.length === 0) { // do nothing } } /** * Extracts the layout parameters from the supplied attributes. * * @param a the style attributes to extract the parameters from * @param widthAttr the identifier of the width attribute * @param heightAttr the identifier of the height attribute */ protected setBaseAttributes(a:android.content.res.TypedArray, widthAttr:string, heightAttr:string):void { this.width = a.getLayoutDimension(widthAttr, LayoutParams.WRAP_CONTENT); this.height = a.getLayoutDimension(heightAttr, LayoutParams.WRAP_CONTENT); } getAttrBinder():AttrBinder { if (!this._attrBinder) { this._attrBinder = this.initBindAttr(); } return this._attrBinder; } private initBindAttr():AttrBinder { let classAttrBinder = LayoutParams.ClassAttrBinderClazzMap.get(this.getClass()); if (!classAttrBinder) { classAttrBinder = this.createClassAttrBinder(); LayoutParams.ClassAttrBinderClazzMap.set(this.getClass(), classAttrBinder); } const attrBinder = new AttrBinder(this); attrBinder.setClassAttrBind(classAttrBinder); return attrBinder; } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return new androidui.attr.AttrBinder.ClassBinderMap() .set('layout_width', { setter(host:LayoutParams, value:any, attrBinder:AttrBinder) { host.width = attrBinder.parseDimension(value, host.width); }, getter(host:LayoutParams) { return host.width; } }).set('layout_height', { setter(host:LayoutParams, value:any, attrBinder:AttrBinder) { host.height = attrBinder.parseDimension(value, host.height); }, getter(host:LayoutParams) { return host.height; } }) } } export class MarginLayoutParams extends LayoutParams { static DEFAULT_MARGIN_RELATIVE:number = Integer.MIN_VALUE; static DEFAULT_MARGIN_RESOLVED:number = 0; static UNDEFINED_MARGIN = MarginLayoutParams.DEFAULT_MARGIN_RELATIVE; public leftMargin = 0; public topMargin = 0; public rightMargin = 0; public bottomMargin = 0; constructor(context:Context, attrs:HTMLElement); constructor(src:MarginLayoutParams); constructor(src:LayoutParams); constructor(width:number, height:number); constructor(...args); constructor(...args) { super(...(() => { if (args[0] instanceof Context && args[1] instanceof HTMLElement) return [0, 0]; else if (typeof args[0] === 'number' && typeof args[1] === 'number') return [args[0], args[1]]; else if (args[0] instanceof MarginLayoutParams) return [args[0]]; else if (args[0] instanceof ViewGroup.LayoutParams) return [args[0]]; })()); if (args[0] instanceof Context && args[1] instanceof HTMLElement) { const a = (<Context>args[0]).obtainStyledAttributes(args[1]); this.setBaseAttributes(a, 'layout_width', 'layout_height'); let margin = a.getDimensionPixelSize('layout_margin', -1); if (margin >= 0) { this.leftMargin = margin; this.topMargin = margin; this.rightMargin= margin; this.bottomMargin = margin; } else { this.leftMargin = a.getDimensionPixelSize('layout_marginLeft', 0); this.rightMargin = a.getDimensionPixelSize('layout_marginRight', 0); this.topMargin = a.getDimensionPixelSize('layout_marginTop', 0); this.bottomMargin = a.getDimensionPixelSize('layout_marginBottom', 0); this.leftMargin = a.getDimensionPixelSize('layout_marginStart', this.leftMargin); this.rightMargin = a.getDimensionPixelSize('layout_marginEnd', this.rightMargin); } a.recycle(); } else if (typeof args[0] === 'number' && typeof args[1] === 'number') { } else if (args[0] instanceof MarginLayoutParams) { const source = args[0]; this.width = source.width; this.height = source.height; this.leftMargin = source.leftMargin; this.topMargin = source.topMargin; this.rightMargin = source.rightMargin; this.bottomMargin = source.bottomMargin; } else if (args[0] instanceof ViewGroup.LayoutParams) { } } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('layout_marginLeft', { setter(host:MarginLayoutParams, value:any) { if(value==null) value = 0; host.leftMargin = value; }, getter(host:MarginLayoutParams) { return host.leftMargin; } }).set('layout_marginStart', { setter(host:MarginLayoutParams, value:any) { if(value==null) value = 0; host.leftMargin = value; }, getter(host:MarginLayoutParams) { return host.leftMargin; } }).set('layout_marginTop', { setter(host:MarginLayoutParams, value:any) { if(value==null) value = 0; host.topMargin = value; }, getter(host:MarginLayoutParams) { return host.topMargin; } }).set('layout_marginRight', { setter(host:MarginLayoutParams, value:any) { if(value==null) value = 0; host.rightMargin = value; }, getter(host:MarginLayoutParams) { return host.rightMargin; } }).set('layout_marginEnd', { setter(host:MarginLayoutParams, value:any) { if(value==null) value = 0; host.rightMargin = value; }, getter(host:MarginLayoutParams) { return host.rightMargin; } }).set('layout_marginBottom', { setter(host:MarginLayoutParams, value:any) { if(value==null) value = 0; host.bottomMargin = value; }, getter(host:MarginLayoutParams) { return host.bottomMargin; } }).set('layout_margin', { setter(host:MarginLayoutParams, value:any, attrBinder:AttrBinder) { if(value==null) value = 0; let [top, right, bottom, left] = attrBinder.parsePaddingMarginTRBL(value); host.topMargin = top; host.rightMargin = right; host.bottomMargin = bottom; host.leftMargin = left; }, getter(host:MarginLayoutParams) { return host.topMargin + ' ' + host.rightMargin + ' ' + host.bottomMargin + ' ' + host.leftMargin; } }); } setMargins(left:number, top:number, right:number, bottom:number) { this.leftMargin = left; this.topMargin = top; this.rightMargin = right; this.bottomMargin = bottom; } setLayoutDirection(layoutDirection:number):void { } getLayoutDirection():number { return View.LAYOUT_DIRECTION_LTR; } isLayoutRtl():boolean { return this.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; } resolveLayoutDirection(layoutDirection:number):void { //do nothing } } export interface OnHierarchyChangeListener { onChildViewAdded(parent:View, child:View); onChildViewRemoved(parent:View, child:View); } } class TouchTarget { private static MAX_RECYCLED = 32; private static sRecycleBin:TouchTarget; private static sRecycledCount=0; static ALL_POINTER_IDS = -1; // all ones child:View; pointerIdBits:number; next:TouchTarget; static obtain(child:View , pointerIdBits:number ) { let target:TouchTarget; if (TouchTarget.sRecycleBin == null) { target = new TouchTarget(); } else { target = TouchTarget.sRecycleBin; TouchTarget.sRecycleBin = target.next; TouchTarget.sRecycledCount--; target.next = null; } target.child = child; target.pointerIdBits = pointerIdBits; return target; } public recycle() { if (TouchTarget.sRecycledCount < TouchTarget.MAX_RECYCLED) { this.next = TouchTarget.sRecycleBin; TouchTarget.sRecycleBin = this; TouchTarget.sRecycledCount += 1; } else { this.next = null; } this.child = null; } } }
the_stack
module CorsicaTests { var _ElementResizeInstrument = <typeof WinJS.UI.PrivateElementResizeInstrument> Helper.require("WinJS/Controls/ElementResizeInstrument/_ElementResizeInstrument")._ElementResizeInstrument; var resizeEvent = _ElementResizeInstrument.EventNames.resize; var readyEvent = _ElementResizeInstrument.EventNames._ready; function disposeAndRemoveElement(element: HTMLElement) { if (element.winControl) { element.winControl.dispose(); } WinJS.Utilities.disposeSubTree(element); if (element.parentElement) { element.parentElement.removeChild(element); } } function awaitInitialResizeEvent(resizeInstrument: WinJS.UI.PrivateElementResizeInstrument): WinJS.Promise<any> { // When the _ElementResizeHandler finishes loading, it will fire an initial resize event. Some tests may want // to account for that to avoid false positives in tests. return new WinJS.Promise((c) => { resizeInstrument.addEventListener(resizeEvent, function handleInitialResize() { resizeInstrument.removeEventListener(resizeEvent, handleInitialResize); c(); }); }); } function allowTimeForAdditionalResizeEvents(): WinJS.Promise<any> { // Helper function used to let enough time pass for a resize event to occur, // usually this is to capture any additional resize events that may have been pending, // particularly when we want to verify that no redundant events will be fired. return WinJS.Promise.timeout(300); } export class ElementResizeInstrumentTests { "use strict"; _element: HTMLElement; _parent: HTMLElement; _child: HTMLElement; _parentInstrument: WinJS.UI.PrivateElementResizeInstrument; _childInstrument: WinJS.UI.PrivateElementResizeInstrument; setUp() { // Setup creates a subTree of two elements "parent" and "child", // and gives each its own _ElementResizeInstrument. LiveUnit.LoggingCore.logComment("In setup"); // Host element for our subTree. this._element = document.createElement("DIV"); // Create two elements (parent & child), each styled with percentage heights & widths and each with its own _ElementResizeInstrument. this._parent = document.createElement("DIV"); this._child = document.createElement("DIV"); this._parent.appendChild(this._child); this._element.appendChild(this._parent); document.body.appendChild(this._element); // Let host element be the nearest positioned ancestor of the parent element this._element.style.cssText = "position: relative; height: 800px; width: 800px;"; // Parent and Child need to be positioned in order to have resizes detected by the resizeInstruments. Not necessary to set CSS offsets. var parentStyleText = "position: relative; width: 65%; maxWidth: inherit; minWidth: inherit; height: 65%; maxHeight: inherit; minHeight: inherit; padding: 0px;"; var childStyleText = parentStyleText; this._parent.id = "parent"; this._parent.style.cssText = parentStyleText; this._parentInstrument = new _ElementResizeInstrument(); this._parent.appendChild(this._parentInstrument.element); this._child.id = "child"; this._child.style.cssText = childStyleText; this._childInstrument = new _ElementResizeInstrument(); this._child.appendChild(this._childInstrument.element); } tearDown() { if (this._element) { disposeAndRemoveElement(this._element) this._element = null; this._parent = null; this._child = null; this._parentInstrument = null; this._childInstrument = null; } } testInitialResizeEvent(complete) { // Verify that an _ElementResizeInstrument will asynchronously fire a "resize" event after it has // been initialized and added to the DOM. // The _ElementResizeInstrument uses an <object> element and its contentWindow to detect resize events in whichever element the // _ElementResizeInstrument is appended to. Some browsers will fire an async "resize" event for the <object> element automatically when // it gets added to the DOM, others won't. In both cases it is up to the _ElementResizeHandler to make sure that an initial async "resize" // event is always fired in all browsers. var parentInstrumentReadyPromise = new WinJS.Promise((c) => { this._parentInstrument.addEventListener(readyEvent, c); this._parentInstrument.addedToDom(); }) var childInstrumentReadyPromise = new WinJS.Promise((c) => { this._childInstrument.addEventListener(readyEvent, c); this._childInstrument.addedToDom(); }) // The ready event is a private event used for unit tests. The ready event fires whenever the _ElementResizeInstrument's underlying // <object> element has successfully loaded and the _ElementResizeInstrument has successfully hooked up a "resize" event listener // to the <object> element's contentWindow. WinJS.Promise .join([ // Verify that everything was hooked up correctly. parentInstrumentReadyPromise, childInstrumentReadyPromise, ]).then(() => { // If everything was hooked up correctly, we expect an initial resize event from both instruments. var parentInstrumentResizePromise = awaitInitialResizeEvent(this._parentInstrument); var childInstrumentResizePromise = awaitInitialResizeEvent(this._childInstrument); return WinJS.Promise .join([ parentInstrumentResizePromise, childInstrumentResizePromise, ]); }).done(complete); } testInitialResizeEventFiresOnlyOnce(complete) { // Verify that in all browsers each _ElementResizeInstrument fires exactly one initial resize event. // The _ElementResizeInstrument uses an <object> element and its contentWindow to detect resize events in whichever element the // _ElementResizeInstrument is appended to. Some browsers will fire an async "resize" event for the <object> element automatically when // it gets added to the DOM, others won't. In both cases it is up to the _ElementResizeHandler to make sure that an initial aysnc "resize" // event is always fired in all browsers. this._parentInstrument.addedToDom(); this._childInstrument.addedToDom(); var expectedResizeCount = 1; var parentResizeCount = 0; var childResizeCount = 0; this._parentInstrument.addEventListener(resizeEvent, () => { parentResizeCount++; }); this._childInstrument.addEventListener(resizeEvent, () => { childResizeCount++; }) allowTimeForAdditionalResizeEvents() .done(() => { LiveUnit.Assert.areEqual(expectedResizeCount, parentResizeCount, "Only 1 resize event should have been detected by the parent instrument"); LiveUnit.Assert.areEqual(expectedResizeCount, childResizeCount, "Only 1 resize event should have been detected by the child instrument"); complete(); }); } testChildElementResize(complete) { // Verifies that when both the parent and child elements have _ElementResizeInstruments, resizing // the child element will trigger child resize events, but will not trigger parent resize events. function parentFailEvent(): void { LiveUnit.Assert.fail("Size changes to the child element should not trigger resize events in the parent element."); } var childStyle = this._child.style; var childResizedCounter = 0; var expectedChildResizeEvents = 7; var childResizedSignal: WinJS._Signal<any>; function childResizeHandler(): void { childResizedCounter++; childResizedSignal.complete(); } this._parentInstrument.addedToDom(); this._childInstrument.addedToDom(); WinJS.Promise .join([ awaitInitialResizeEvent(this._parentInstrument), awaitInitialResizeEvent(this._childInstrument) ]) .then(() => { this._childInstrument.addEventListener(resizeEvent, childResizeHandler); this._parentInstrument.addEventListener(resizeEvent, parentFailEvent); childResizedSignal = new WinJS._Signal(); childStyle.width = "50%"; return childResizedSignal.promise; }) .then(() => { childResizedSignal = new WinJS._Signal(); childStyle.height = "50%"; return childResizedSignal.promise; }) .then(() => { childResizedSignal = new WinJS._Signal(); childStyle.padding = "5px"; return childResizedSignal.promise; }) .then(() => { childResizedSignal = new WinJS._Signal(); childStyle.maxWidth = "40%"; return childResizedSignal.promise; }) .then(() => { childResizedSignal = new WinJS._Signal(); childStyle.maxHeight = "40%"; return childResizedSignal.promise; }) .then(() => { childResizedSignal = new WinJS._Signal(); childStyle.minWidth = "60%"; return childResizedSignal.promise; }) .then(() => { childResizedSignal = new WinJS._Signal(); childStyle.minHeight = "60%"; return childResizedSignal.promise; }).done(function () { LiveUnit.Assert.areEqual(expectedChildResizeEvents, childResizedCounter, "Incorrect number of resize events fired for child element"); complete(); }); } testResizeEventsAreBatched(complete) { var childStyle = this._child.style; var childResizedCounter = 0; var expectedChildResizeEvents = 1; function childResizeHandler(): void { childResizedCounter++; } this._childInstrument.addedToDom(); awaitInitialResizeEvent(this._childInstrument) .then(() => { this._childInstrument.addEventListener(resizeEvent, childResizeHandler); childStyle.width = "50%"; getComputedStyle(this._child); childStyle.height = "50%"; getComputedStyle(this._child); childStyle.padding = "5px"; // Wait long enough to make sure only one resize event was fired. return allowTimeForAdditionalResizeEvents(); }) .done(() => { LiveUnit.Assert.areEqual(expectedChildResizeEvents, childResizedCounter, "Batched 'resize' events should cause the event handler to fire EXACTLY once."); complete(); }); } testParentElementResize(complete) { // Verifies that changes to the dimensions of the parent element trigger resize events for both the parent and the child element. // Test expects child element to be styled with percentage height and width and that both the child element and the parent element // each have their own _ElementResizeInstrument. var parentStyle = this._parent.style; var parentHandlerCounter = 0; var expectedParentHandlerCalls = 2; var parentResizedSignal: WinJS._Signal<any>; function parentResizeHandler(): void { parentHandlerCounter++; parentResizedSignal.complete(); } var childHandlerCounter = 0; var expectedChildHandlerCalls = 2; var childResizedSignal: WinJS._Signal<any>; function childResizeHandler(): void { childHandlerCounter++; childResizedSignal.complete(); } this._parentInstrument.addedToDom(); this._childInstrument.addedToDom(); WinJS.Promise .join([ awaitInitialResizeEvent(this._parentInstrument), awaitInitialResizeEvent(this._childInstrument) ]) .then(() => { this._parentInstrument.addEventListener(resizeEvent, parentResizeHandler); this._childInstrument.addEventListener(resizeEvent, childResizeHandler); parentResizedSignal = new WinJS._Signal(); childResizedSignal = new WinJS._Signal(); parentStyle.height = "50%"; return WinJS.Promise.join([ parentResizedSignal.promise, childResizedSignal.promise, ]); }) .then(() => { parentResizedSignal = new WinJS._Signal(); childResizedSignal = new WinJS._Signal(); parentStyle.width = "50%"; return WinJS.Promise.join([ parentResizedSignal.promise, childResizedSignal.promise, ]); }) .done(() => { LiveUnit.Assert.areEqual(expectedParentHandlerCalls, parentHandlerCounter, "Batched 'resize' events should cause the parent handler to fire EXACTLY once."); LiveUnit.Assert.areEqual(expectedChildHandlerCalls, childHandlerCounter, "Batched 'resize' events should cause the child handler to fire EXACTLY once."); complete(); }); } testDispose(complete) { function parentFailResizeHandler(): void { LiveUnit.Assert.fail("disposed parentIstrument should never fire resize events"); } function childFailResizeHandler(): void { LiveUnit.Assert.fail("disposed childInstrument should never fires resize events"); } // Test disposing parent instrument immediately after addedToDom is called, some browsers may still be loading the <object> element at this point and we want to // make sure that we don't still try to hook the <object>'s content window asyncronously once the <object> finishes loading, if its already been disposed. // Verify that the parent instrument never fires an initial resize event. this._parentInstrument.addEventListener(resizeEvent, parentFailResizeHandler); this._parentInstrument.addedToDom(); this._parentInstrument.dispose(); LiveUnit.Assert.isTrue(this._parentInstrument._disposed); // Test that by disposing the child instrument after it is ready, // it wont fire an initial resize event. new WinJS.Promise((c) => { this._childInstrument.addEventListener(readyEvent, c); this._childInstrument.addedToDom(); }) .then(() => { this._childInstrument.addEventListener(resizeEvent, childFailResizeHandler); this._childInstrument.dispose(); LiveUnit.Assert.isTrue(this._childInstrument._disposed); // Now that both Instruments have been disposed, resizing the parent or child element should no longer fire events this._parent.style.height = "10px"; this._child.style.height = "10px"; // Wait long enough to ensure events aren't being handled. return allowTimeForAdditionalResizeEvents(); }) .done(() => { // Disposing again should not cause any bad behavior this._parentInstrument.dispose(); this._childInstrument.dispose(); complete(); }); } testReAppendToDomAndResizeAsynchronously(complete) { // Make sure that removing and reappending an initialized _ElementResizeInstrument // Doesn't permanently stop our _ElementResizeInstrument from firing resize events. // This test is partially testing the browser to make sure that the "resize" listener // we've added to the <object> element's contentWindow doesn't become permanently // broken if it leaves and renters the DOM. // We understand that right now there is a period of time after the control has // been re-appended into the DOM before it will start responding to size change // events. The period of time varies depending on the browser, presumably this // is because the browser hasn't run layout yet. We expect that developers can call // forceLayout() on any controls using _ElementResizeInstruments to force the control // to respond to size changes during this period of time where resize events are not // fired when size changes are made immediately after appending it to the DOM. var childResizeSignal: WinJS._Signal<any>; function childResizeHandler() { childResizeSignal.complete(); } var parentResizeSignal: WinJS._Signal<any>; function parentResizeHandler() { parentResizeSignal.complete(); } var parent = this._parent; var parentInstrument = this._parentInstrument; var childInstrument = this._childInstrument; parentInstrument.addedToDom(); childInstrument.addedToDom(); WinJS.Promise .join([ awaitInitialResizeEvent(this._parentInstrument), awaitInitialResizeEvent(this._childInstrument) ]) .then(() => { parentInstrument.addEventListener(resizeEvent, parentResizeHandler); childInstrument.addEventListener(resizeEvent, childResizeHandler); // Test both instruments still fire "resize" after re-appending them to the // DOM and then asynchronously updating the width of the parent element. parentResizeSignal = new WinJS._Signal(); childResizeSignal = new WinJS._Signal(); this._element.removeChild(parent); return new WinJS.Promise((c) => { window.requestAnimationFrame(c); }); }) .then(() => { this._element.appendChild(parent); // Timeout long enough for the browser to acknowledge the element is back in the DOM. return WinJS.Promise.timeout(100); }) .then(() => { parent.style.width = "43%" return WinJS.Promise.join([ parentResizeSignal.promise, childResizeSignal.promise, ]); }) .done(() => { complete(); }); } testDisposeDoesntThrowAnException(complete) { // There is an issue in Safari and iOS where the <object> element's contentWindow and // contentDocument properties are no longer accessible and any previous stored references // to either object will have have lost their prototype chains. When we would try to unregister // the contentWindow "resize" handler a DOM exception would be thrown because frame // contentWindows in iOS and Safari don't have add and remove eventListener methods // while they are not in the DOM. https://bugs.webkit.org/show_bug.cgi?id=149251 // Make sure that disposing a fully loaded _ElementResizeInstrument while its no longer in the DOM, // doesn't throw an exception. Additionally, even if we were unable to unregister the event handler // from the contentWindow, make sure that re-appending a disposed _ElementResizeInstrument and // resizing it will not cause it to notify listeners of any resize events, since it has been disposed. function parentFailResizeHandler(): void { LiveUnit.Assert.fail("disposed parentIstrument should never fire resize events"); } var readyPromise = new WinJS.Promise((c) => { this._parentInstrument.addEventListener(readyEvent, c); this._parentInstrument.addedToDom(); }); readyPromise .then(() => { return awaitInitialResizeEvent(this._parentInstrument); }) .then(() => { this._element.removeChild(this._parent); try { this._parentInstrument.dispose(); } catch (e) { LiveUnit.Assert.fail("Disposing an _ElementResizeInstrument that is not in the DOM, should not throw an exception"); } this._parentInstrument.addEventListener(resizeEvent, parentFailResizeHandler); document.body.appendChild(this._parent); // Timeout long enough for the browser to acknowledge the element is back in the DOM. return WinJS.Promise.timeout(100); }).then(() => { this._parent.style.width = "101px"; return allowTimeForAdditionalResizeEvents(); }).done(() => { complete(); }); } } } LiveUnit.registerTestClass("CorsicaTests.ElementResizeInstrumentTests");
the_stack
import Ajv from "ajv"; import { FromSchema } from "index"; var ajv = new Ajv(); describe("AnyOf schemas", () => { describe("Boolean or String", () => { const anyOfSchema = { anyOf: [{ type: "boolean" }, { type: "string" }], } as const; type StringBoolOrNumber = FromSchema<typeof anyOfSchema>; let boolOrStringInstance: StringBoolOrNumber; it("accepts boolean or string value", () => { boolOrStringInstance = "string"; expect(ajv.validate(anyOfSchema, boolOrStringInstance)).toBe(true); boolOrStringInstance = true; expect(ajv.validate(anyOfSchema, boolOrStringInstance)).toBe(true); }); it("rejects other values", () => { // @ts-expect-error boolOrStringInstance = 42; expect(ajv.validate(anyOfSchema, boolOrStringInstance)).toBe(false); }); }); describe("Along Enum", () => { const enumSchema = { enum: ["apples", 42], anyOf: [{ type: "boolean" }, { type: "string" }, { type: "number" }], } as const; type Enum = FromSchema<typeof enumSchema>; let enumInstance: Enum; it("accepts enum values", () => { enumInstance = "apples"; expect(ajv.validate(enumSchema, enumInstance)).toBe(true); enumInstance = 42; expect(ajv.validate(enumSchema, enumInstance)).toBe(true); }); it("rejects other values", () => { // @ts-expect-error enumInstance = "tomatoes"; expect(ajv.validate(enumSchema, enumInstance)).toBe(false); // @ts-expect-error enumInstance = 43; expect(ajv.validate(enumSchema, enumInstance)).toBe(false); // @ts-expect-error enumInstance = true; expect(ajv.validate(enumSchema, enumInstance)).toBe(false); }); }); describe("Factored object properties", () => { describe("Open objects", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, required: ["bool"], anyOf: [ { properties: { num: { type: "number" } }, required: ["num"] }, { properties: { str: { type: "string" } } }, ], } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it("accepts objects matching #1", () => { objectInstance = { bool: true, num: 42 }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); it("accepts objects matching #2", () => { objectInstance = { bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); objectInstance = { bool: true, str: "string" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); objectInstance = { bool: true, num: "not a number" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); it("rejects objects matching neither", () => { // @ts-expect-error: Bool should be boolean objectInstance = { bool: "true" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); // @ts-expect-error: Bool is required objectInstance = { num: 42 }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); // @ts-expect-error: Bool is required objectInstance = { str: "string" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Open to open object (impossible)", () => { const objectSchema = { type: "object", properties: { str: { type: "string" } }, required: ["str"], anyOf: [{ additionalProperties: { type: "boolean" } }], } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it("rejects object not matching child", () => { // @ts-expect-error objectInstance = { str: "str" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it("rejects objects not matching parent", () => { // @ts-expect-error objectInstance = { str: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Closed (1) to open object", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [ { properties: { num: { type: "number" } }, required: ["num"], additionalProperties: false, }, { properties: { str: { type: "string" } } }, ], } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it("accepts objects matching #1", () => { objectInstance = { num: 42 }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); it("accepts objects matching #2", () => { objectInstance = {}; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); objectInstance = { bool: true, str: "string" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); }); describe("Closed (2) to open object", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [ { properties: { num: { type: "number" } }, required: ["num"], additionalProperties: false, }, { properties: { str: { type: "string" } }, additionalProperties: false, }, ], } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it("accepts objects matching #1", () => { objectInstance = { num: 42 }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); it("accepts objects matching #2", () => { objectInstance = {}; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); objectInstance = { str: "string" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); it("rejects objects matching neither", () => { // @ts-expect-error objectInstance = { num: 42, bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); // @ts-expect-error objectInstance = { str: "string", bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Closed to open object (impossible 1)", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [ { properties: { num: { type: "number" } }, required: ["num"], additionalProperties: false, }, ], required: ["bool"], } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it('rejects object matching child schema as parent requires "bool" prop', () => { // @ts-expect-error objectInstance = { num: 42 }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it("rejects object matching parent schema as child is closed", () => { // @ts-expect-error objectInstance = { num: 42, bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Closed to open object (impossible 2)", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [ { properties: { num: { type: "number" }, bool: { type: "string" } }, required: ["num"], additionalProperties: false, }, ], required: ["bool"], } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it("rejects non-boolean bool prop (required by parent)", () => { // @ts-expect-error objectInstance = { num: 42, bool: "string" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it("rejects non-string bool prop (required by child)", () => { // @ts-expect-error objectInstance = { num: 42, bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Open (1) to closed object", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [{ properties: { str: { type: "string" } } }], required: ["bool"], additionalProperties: false, } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it("accepts valid object", () => { objectInstance = { bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); it("rejects invalid object", () => { // @ts-expect-error: "bool" prop is required by parent objectInstance = { str: "str" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); // @ts-expect-error: "str" is not allowed as additional property objectInstance = { bool: true, str: "str" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Open (2) to closed object", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [ { properties: { str: { type: "string" } }, required: ["str"] }, { properties: { num: { type: "number" } } }, ], additionalProperties: false, } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it("accepts objects matching #2", () => { objectInstance = {}; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); objectInstance = { bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(true); }); it("rejects objects matching #1 as parent is closed", () => { // @ts-expect-error: "str" is not allowed as additionalProperty objectInstance = { str: "string" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); // @ts-expect-error: event with bool present objectInstance = { bool: true, str: "string" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it("rejects objects matching neither", () => { // @ts-expect-error: "num" is not allowed as additionalProperty objectInstance = { num: 42 }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); // @ts-expect-error: event with bool present objectInstance = { bool: true, num: 42 }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Open to closed object (impossible)", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [{ properties: { str: { type: "string" } }, required: ["str"] }], required: ["bool"], additionalProperties: false, } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it('rejects object having "str" property as parent is closed', () => { // @ts-expect-error objectInstance = { bool: true, str: "str" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it('rejects object not having "str" property as it is required by child', () => { // @ts-expect-error objectInstance = { bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it('rejects object not having "bool" property as it is required by parent', () => { // @ts-expect-error: Parent requires 'bool' property objectInstance = { str: "str" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); describe("Closed to closed object (impossible)", () => { const objectSchema = { type: "object", properties: { bool: { type: "boolean" } }, anyOf: [ { properties: { str: { type: "string" } }, additionalProperties: false, }, ], required: ["bool"], additionalProperties: false, } as const; type FactoredObj = FromSchema<typeof objectSchema>; let objectInstance: FactoredObj; it('rejects object with "bool" property as child is closed', () => { // @ts-expect-error objectInstance = { bool: true }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it('rejects object with "str" property as parent is closed', () => { // @ts-expect-error objectInstance = { str: "str" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); it("rejects object with both at the time", () => { // @ts-expect-error objectInstance = { bool: true, str: "str" }; expect(ajv.validate(objectSchema, objectInstance)).toBe(false); }); }); }); describe("Factored tuple properties", () => { describe("Open tuples", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], anyOf: [ { items: [{ const: "num" }, { type: "number" }] }, { items: [{ const: "bool" }, { type: "boolean" }] }, ], } as const; type Tuple = FromSchema<typeof tupleSchema>; let tupleInstance: Tuple; it("accepts tuples matching #1", () => { tupleInstance = ["num"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["num", 42]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("accepts tuples matching #2", () => { tupleInstance = ["bool"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["bool", true]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects tuples matching neither", () => { // @ts-expect-error: First item should be "num"/"bool" tupleInstance = ["not num/bool"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: Second item should be number tupleInstance = ["num", true]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: Second item should be bool tupleInstance = ["bool", 42]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Open tuples (2)", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], additionalItems: { type: "boolean" }, anyOf: [ { items: [{ const: "num" }, { type: "number" }] }, { items: [{ const: "bool" }, { type: "boolean" }] }, ], } as const; type Tuple = FromSchema<typeof tupleSchema>; let tupleInstance: Tuple; it("accepts tuples matching #1", () => { tupleInstance = ["num"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("accepts tuples matching #2", () => { tupleInstance = ["bool"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["bool", true]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects tuples not matching parent", () => { // @ts-expect-error: Second item cannot exist (should be bool AND number) tupleInstance = ["num", 42]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Open tuples (3)", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], additionalItems: { type: "boolean" }, anyOf: [ { items: [{ type: "string" }], additionalItems: { type: "number" }, }, ], } as const; type Tuple = FromSchema<typeof tupleSchema>; let tupleInstance: Tuple; it("accepts tuples matching parent and child", () => { tupleInstance = ["str"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects tuples with additional items as child and parent don't match", () => { // @ts-expect-error: Second item cannot exist (should be bool AND number) tupleInstance = ["num", 42]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: Second item cannot exist (should be bool AND number) tupleInstance = ["num", true]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Closed (1) to open tuple", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], anyOf: [ { items: [{ const: "stop" }], additionalItems: false }, { items: [{ const: "continue" }] }, ], } as const; type Tuple = FromSchema<typeof tupleSchema>; let tupleInstance: Tuple; it("accepts tuples matching #1", () => { tupleInstance = ["stop"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("accepts tuples matching #2", () => { tupleInstance = ["continue"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["continue", { any: "value" }]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects tuples matching neither", () => { // @ts-expect-error: First item should be "stop"/"continue" tupleInstance = ["invalid value"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: Second item is denied tupleInstance = ["stop", { any: "value" }]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Closed (2) to open tuple", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], anyOf: [ { items: [{ const: "num" }, { type: "number" }], additionalItems: false, minItems: 2, }, { items: [{ const: "bool" }, { type: "boolean" }], additionalItems: false, minItems: 1, }, ], } as const; type FactoredTuple = FromSchema<typeof tupleSchema>; let tupleInstance: FactoredTuple; it("accepts tuples matching #1", () => { tupleInstance = ["num", 42]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("accepts tuples matching #2", () => { tupleInstance = ["bool"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["bool", true]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects tuples matching neither", () => { // @ts-expect-error: Third item is denied tupleInstance = ["num", 42, "additional item"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: Third item is denied tupleInstance = ["bool", true, "additional item"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Closed to open tuple (impossible 1)", () => { const tupleSchema = { type: "array", items: [{ type: "number" }, { type: "number" }], minItems: 2, anyOf: [{ items: [{ type: "number" }], additionalItems: false }], } as const; type FactoredTuple = FromSchema<typeof tupleSchema>; let tupleInstance: FactoredTuple; it("rejects tuple matching child schema as parent requires 2 items", () => { // @ts-expect-error tupleInstance = [0]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); it("rejects tuple matching parent schema as child is closed", () => { // @ts-expect-error tupleInstance = [0, 1]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Closed to open tuple (impossible 2)", () => { const tupleSchema = { type: "array", items: [{ type: "string" }, { type: "boolean" }], minItems: 2, anyOf: [ { items: [{ type: "string" }, { type: "number" }], additionalItems: false, }, ], } as const; type FactoredTuple = FromSchema<typeof tupleSchema>; let tupleInstance: FactoredTuple; it("rejects non-boolean second item (required by parent)", () => { // @ts-expect-error tupleInstance = ["string", 42]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); it("rejects non-number second item (required by child)", () => { // @ts-expect-error tupleInstance = ["string", true]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Open (1) to closed tuple", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], minItems: 1, additionalItems: false, anyOf: [ { items: [{ const: "apple" }] }, { items: [{ enum: ["tomato", "banana"] }] }, ], } as const; type FactoredTuple = FromSchema<typeof tupleSchema>; let tupleInstance: FactoredTuple; it("accepts valid tuple", () => { tupleInstance = ["apple"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["tomato"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["banana"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects invalid tuple", () => { // @ts-expect-error: One item is required by parent tupleInstance = []; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: Additional items are denied tupleInstance = ["apple", "tomato"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Open (2) to closed tuple", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], additionalItems: false, anyOf: [ { items: [{ const: "several" }, { const: "items" }], minItems: 2 }, { items: [{ const: "only one" }] }, ], } as const; type FactoredTuple = FromSchema<typeof tupleSchema>; let tupleInstance: FactoredTuple; it("accepts tuples matching #2", () => { tupleInstance = []; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); tupleInstance = ["only one"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects tuples matching #1 as parent is closed", () => { // @ts-expect-error: Second item is not allowed as additionalProperty tupleInstance = ["several", "items"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: second item is missing tupleInstance = ["several"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Open (3) to closed tuple", () => { const tupleSchema = { type: "array", items: [{ type: "string" }, { type: "boolean" }], minItems: 2, additionalItems: false, anyOf: [{ items: [{ const: "can have additionalItems" }] }], } as const; type FactoredTuple = FromSchema<typeof tupleSchema>; let tupleInstance: FactoredTuple; it("accepts tuples matching parent and child", () => { tupleInstance = ["can have additionalItems", true]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); it("rejects invalid tuples", () => { // @ts-expect-error: Second item is required by parent tupleInstance = ["can have additionalItems"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); // @ts-expect-error: First item should be child's const tupleInstance = ["no child const"]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(false); }); }); describe("Open to closed tuple (impossible)", () => { const factoredTupleSchema = { type: "array", items: [{ type: "string" }, { type: "boolean" }], minItems: 2, additionalItems: false, anyOf: [ { items: [{ type: "string" }], additionalItems: { type: "number" } }, ], } as const; type FactoredTuple = FromSchema<typeof factoredTupleSchema>; let tupleInstance: FactoredTuple; it("rejects tuple having number second item as parent requires boolean", () => { // @ts-expect-error tupleInstance = ["str", 42]; expect(ajv.validate(factoredTupleSchema, tupleInstance)).toBe(false); }); it("rejects tuple having boolean second item as child requires number", () => { // @ts-expect-error tupleInstance = ["str", true]; expect(ajv.validate(factoredTupleSchema, tupleInstance)).toBe(false); }); it("rejects object not having second items as it is required by parent", () => { // @ts-expect-error tupleInstance = ["str"]; expect(ajv.validate(factoredTupleSchema, tupleInstance)).toBe(false); }); }); describe("Incorrect schema", () => { const tupleSchema = { type: "array", items: [{ type: "string" }], anyOf: [{ additionalItems: { type: "boolean" } }], } as const; type FactoredTuple = FromSchema<typeof tupleSchema>; let tupleInstance: FactoredTuple; it("accepts tuples with any additional items", () => { tupleInstance = [ "can have additionalItems", 'yes, because "items" is missing in anyOf schema', ]; expect(ajv.validate(tupleSchema, tupleInstance)).toBe(true); }); }); describe("Min/max items", () => { const factoredTupleSchema = { type: "array", items: [{ type: "string" }, { type: "number" }, { type: "boolean" }], anyOf: [{ minItems: 3 }, { maxItems: 1 }], } as const; type FactoredTuple = FromSchema<typeof factoredTupleSchema>; let factoredTupleInstance: FactoredTuple; it("accepts tuples with <= 1 items", () => { factoredTupleInstance = []; expect(ajv.validate(factoredTupleSchema, factoredTupleInstance)).toBe( true ); factoredTupleInstance = ["0"]; expect(ajv.validate(factoredTupleSchema, factoredTupleInstance)).toBe( true ); }); it("accepts tuples with >= 3 items", () => { factoredTupleInstance = ["0", 1, true]; expect(ajv.validate(factoredTupleSchema, factoredTupleInstance)).toBe( true ); factoredTupleInstance = ["0", 1, true, "any"]; expect(ajv.validate(factoredTupleSchema, factoredTupleInstance)).toBe( true ); }); it("rejects tuples with 2 items", () => { // @ts-expect-error: Tuples should not have 2 items factoredTupleInstance = ["0", 1]; expect(ajv.validate(factoredTupleSchema, factoredTupleInstance)).toBe( false ); }); }); }); });
the_stack
import Axios from "axios"; import express = require("express"); import passport = require("passport"); import { BearerStrategy, VerifyCallback, IBearerStrategyOption, ITokenPayload } from "passport-azure-ad"; import qs = require("qs"); import * as debug from "debug"; import { IRecording } from "../../model/IRecording"; const log = debug("msteams"); export const meetingService = (options: any): express.Router => { const router = express.Router(); const pass = new passport.Passport(); router.use(pass.initialize()); const fileUpload = require('express-fileupload'); router.use(fileUpload({ createParentPath: true })); const bearerStrategy = new BearerStrategy({ identityMetadata: "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration", clientID: process.env.TAB_APP_ID as string, audience: `api://${process.env.PUBLIC_HOSTNAME}/${process.env.TAB_APP_ID}` as string, loggingLevel: "warn", validateIssuer: false, passReqToCallback: false } as IBearerStrategyOption, (token: ITokenPayload, done: VerifyCallback) => { done(null, { tid: token.tid, name: token.name, upn: token.upn }, token); } ); pass.use(bearerStrategy); const exchangeForToken = (tid: string, token: string, scopes: string[]): Promise<string> => { return new Promise((resolve, reject) => { const url = `https://login.microsoftonline.com/${tid}/oauth2/v2.0/token`; const params = { client_id: process.env.TAB_APP_ID, client_secret: process.env.TAB_APP_SECRET, grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: token, requested_token_use: "on_behalf_of", scope: scopes.join(" ") }; Axios.post(url, qs.stringify(params), { headers: { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded" } }).then(result => { if (result.status !== 200) { reject(result); } else { resolve(result.data.access_token); } }).catch(err => { // error code 400 likely means you have not done an admin consent on the app reject(err); }); }); }; const uploadFile = async (file: File, accessToken: string): Promise<any> => { const apiUrl = `https://graph.microsoft.com/v1.0/sites/${process.env.SITEID}/drive/root:/${file.name}:/content` if (file.size <(4 * 1024 * 1024)) { const fileBuffer = file as any; return Axios.put(apiUrl, fileBuffer.data, { headers: { Authorization: `Bearer ${accessToken}` }}) .then(response => { log(response); return response.data; }).catch(err => { log(err); return null; }); } else { // File.size>4MB, refer to https://mmsharepoint.wordpress.com/2020/01/12/an-outlook-add-in-with-sharepoint-framework-spfx-storing-mail-with-microsoftgraph/ return null; } }; const getDriveItem = async (driveItemId: string, accessToken: string): Promise<any> => { const apiUrl = `https://graph.microsoft.com/v1.0/sites/${process.env.SITEID}/drive/items/${driveItemId}?$expand=listItem`; return Axios.get(apiUrl, { headers: { Authorization: `Bearer ${accessToken}` }}) .then((response) => { return response.data; }).catch(err => { log(err); return null; }); }; const getList = async (accessToken: string): Promise<any> => { const apiUrl = `https://graph.microsoft.com/v1.0/sites/${process.env.SITEID}/drive?$expand=list`; return Axios.get(apiUrl, { headers: { Authorization: `Bearer ${accessToken}` }}) .then((response) => { return response.data; }).catch(err => { log(err); return null; }); }; const updateDriveItem = async (itemID: string, listID: string, meetingID: string, userID: string, userName: string, accessToken: string): Promise<any> => { const apiUrl = `https://graph.microsoft.com/v1.0/sites/${process.env.SITEID}/lists/${listID}/items/${itemID}/fields`; const fieldValueSet = { MeetingID: meetingID, UserID: userID, UserDispName: userName }; return Axios.patch(apiUrl, fieldValueSet, { headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }}) .then(async (response) => { return response.data; }).catch(err => { log(err); return null; }); }; const getRecordingsPerMeeting = async (meetingID: string, accessToken: string): Promise<IRecording[]> => { const listResponse = await getList(accessToken); const requestUrl: string = `https://graph.microsoft.com/v1.0/sites/${process.env.SITEID}/lists/${listResponse.list.id}/items?$expand=fields($select=id,MeetingID,UserDispName,UserID),driveItem&$filter=fields/MeetingID eq '${meetingID}'`; const response = await Axios.get(requestUrl, { headers: { Authorization: `Bearer ${accessToken}`, }}); let recordings: IRecording[] = []; response.data.value.forEach(element => { recordings.push({ id: element.driveItem.id, name: element.driveItem.name, username: element.fields.UserDispName, userID: element.fields.UserID }); }); return recordings; }; router.post( "/upload", pass.authenticate("oauth-bearer", { session: false }), async (req: any, res: express.Response, next: express.NextFunction) => { const user: any = req.user; try { const accessToken = await exchangeForToken(user.tid, req.header("Authorization")!.replace("Bearer ", "") as string, ["https://graph.microsoft.com/sites.readwrite.all"]); const uploadResponse = await uploadFile(req.files.file, accessToken); const itemResponse = await getDriveItem(uploadResponse.id, accessToken); const listResponse = await getList(accessToken); const updateResponse = await updateDriveItem(itemResponse.listItem.id, listResponse.list.id, req.body.meetingID, req.body.userID, req.body.userName, accessToken); res.end("OK"); } catch (ex) { } }); router.get("/files/:meetingID", pass.authenticate("oauth-bearer", { session: false }), async (req: any, res: express.Response, next: express.NextFunction) => { const user: any = req.user; const meetingID = req.params.meetingID; try { const accessToken = await exchangeForToken(user.tid, req.header("Authorization")!.replace("Bearer ", "") as string, ["https://graph.microsoft.com/sites.readwrite.all"]); const recordings = await getRecordingsPerMeeting(meetingID, accessToken); res.json(recordings); } catch (err) { log(err); if (err.status) { res.status(err.status).send(err.message); } else { res.status(500).send(err); } } }); router.get("/audio/:driveItemID", pass.authenticate("oauth-bearer", { session: false }), async (req: any, res: express.Response, next: express.NextFunction) => { const user: any = req.user; const driveItemId = req.params.driveItemID; try { const accessToken = await exchangeForToken(user.tid, req.header("Authorization")!.replace("Bearer ", "") as string, ["https://graph.microsoft.com/sites.readwrite.all"]); const requestUrl: string = `https://graph.microsoft.com/v1.0/sites/${process.env.SITEID}/drive/items/${driveItemId}/content`; const response = await Axios.get(requestUrl, { responseType: 'arraybuffer', // no 'blob' as 'blob' only works in browser headers: { Authorization: `Bearer ${accessToken}`, }}); res.type("audio/webm"); res.end(response.data, "binary"); } catch (err) { log(err); if (err.status) { res.status(err.status).send(err.message); } else { res.status(500).send(err); } } }); router.post( "/token", pass.authenticate("oauth-bearer", { session: false }), async (req: express.Request, res: express.Response, next: express.NextFunction) => { const user: any = req.user; try { const accessToken = await exchangeForToken(user.tid, req.header("Authorization")!.replace("Bearer ", "") as string, ["https://graph.microsoft.com/user.read","https://graph.microsoft.com/user.readbasic.all"]); res.json({ access_token: accessToken}); } catch (err) { if (err.status) { res.status(err.status).send(err.message); } else { res.status(500).send(err); } } }); return router; }
the_stack
import * as net from 'net'; import * as uuid from 'uuid'; import * as sinon from 'sinon'; import { expect } from 'chai'; import { getEchoServerAndSocket, getInboundConnection, ITestSendArgs } from '../../fixtures/helpers'; import { setupSinonChai } from '../../fixtures/setup'; import { Connection } from '../../../src/esl/Connection'; import { ICallback } from '../../../src/utils'; import { Event } from '../../../src/esl/Event'; import { cmdReply } from '../../fixtures/data'; setupSinonChai(); describe('esl.Connection', function () { describe('Outbound Connection', function () { let testServer: net.Server; let testConnection: Connection; before(function (done) { getEchoServerAndSocket(function (err, result) { if (err || !result) return done(err); testServer = result.server; testConnection = Connection.createOutbound(result.socket); done(); }); }); it('Has the correct exports', function () { expect(Connection).to.be.a('function'); expect(testConnection).to.be.an.instanceof(Connection); testConnectionInstance(testConnection); }); after(function () { testConnection.disconnect(); testServer.close(); }); }); describe('Inbound Connection', function () { let testServer: net.Server; let testConnection: Connection; before(function (done) { getInboundConnection(function (err, result) { if (err || !result) return done(err); testServer = result.server; testConnection = result.connection; done(); }); }); it('Has the correct exports', function () { //is function expect(Connection).to.be.a('function'); //is instance expect(testConnection).to.be.an.instanceof(Connection); testConnectionInstance(testConnection); }); describe('.socketDescriptor()', function () { it('Returns null', function () { expect(testConnection.socketDescriptor()).to.be.null; }); }); describe('.connected()', function () { it('Returns true', function () { expect(testConnection.connected()).to.equal(true); }); }); describe('.getInfo()', function () { it('Returns null', function () { expect(testConnection.getInfo()).to.be.null; }); }); describe('.send()', function () { it('Write the correct data with one arg', function (done) { testConnectionSend( done, testConnection, ['send me'], 'send me\n\n', ); }); it('Writes the correct data with many args', function (done) { testConnectionSend( done, testConnection, ['send me', { header1: 'val1', header2: 'val2' }], 'send me\nheader1: val1\nheader2: val2\n\n', ); }); }); describe('.execute()', function () { const id0 = uuid.v4(); const id1 = uuid.v4(); it('Invokes the callback', function (done) { testChannelExecute(testConnection, 'playback', 'foo', id0, function (evt) { expect(evt.getHeader('Application')).to.equal('playback'); done(); }); }); it('Invokes the callback only once for the same session', function (done) { testChannelExecute(testConnection, 'hangup', '', id0, function (evt) { expect(evt.getHeader('Application')).to.equal('hangup'); done(); }); }); it('Invokes the callback again for a new session', function (done) { testChannelExecute(testConnection, 'hangup', '', id1, function (evt) { expect(evt.getHeader('Application')).to.equal('hangup'); done(); }); }); }); describe('.sendRecv()', function () { it('Calls callback when the data is returned', function (done) { testConnection.socket.once('data', function (buffer) { testConnection.socket.write(cmdReply()); testConnection.socket.write('\n'); }); testConnection.sendRecv('auth test_password', function (evt) { expect(evt.getHeader('Content-Type')).to.equal('command/reply'); expect(evt.getHeader('Reply-Text')).to.equal('+OK accepted'); expect(evt.getHeader('Modesl-Reply-OK')).to.equal('accepted'); done(); }); }); it('Fires `esl::event::command::reply`', function (done) { testConnection.socket.once('data', function () { testConnection.socket.write(cmdReply()); testConnection.socket.write('\n'); }); testConnection.once('esl::event::command::reply', function (evt) { expect(evt.getHeader('Content-Type')).to.equal('command/reply'); expect(evt.getHeader('Reply-Text')).to.equal('+OK accepted'); expect(evt.getHeader('Modesl-Reply-OK')).to.equal('accepted'); done(); }); testConnection.sendRecv('auth test_password'); }); }); describe('.api()', function () { it('Call the callback when `esl::event::api::response comes`', function (done) { const stub = function (buffer: Buffer) { const data = buffer.toString('utf8'); if (data === 'api originate\n\n') { testConnection.emit('esl::event::api::response', 'event'); } }; testConnection.socket.on('data', stub); testConnection.api('originate', function (response) { expect(response).to.be.equal('event'); testConnection.socket.off('data', stub); done(); }); }); it('Gets the correct response for each call if called twice immediately', function (done) { const stub = function (buffer: Buffer) { const data = buffer.toString('utf8'); if (data.indexOf('api originate1\n\n') !== -1) testConnection.emit('esl::event::api::response', 'originate1'); if (data.indexOf('api originate2\n\n') !== -1) testConnection.emit('esl::event::api::response', 'originate2'); }; testConnection.socket.on('data', stub); const testDone = function () { if (callback1.called && callback2.called) { testConnection.socket.off('data', stub); done(); } } const callback1 = sinon.spy(function (response) { expect(response).to.be.equal('originate1'); expect(callback2).to.not.be.called; testDone(); }); const callback2 = sinon.spy(function (response) { expect(response).to.be.equal('originate2'); expect(callback1).to.be.called; testDone(); }); testConnection.api('originate1', callback1); testConnection.api('originate2', callback2); }); it('Gets the correct response for each call if called twice delayed', function (done) { const stub = function (buffer: Buffer) { const data = buffer.toString('utf8'); if (data.indexOf('api originate1\n\n') !== -1) testConnection.emit('esl::event::api::response', 'originate1'); if (data.indexOf('api originate2\n\n') !== -1) testConnection.emit('esl::event::api::response', 'originate2'); }; testConnection.socket.on('data', stub); const testDone = function () { if (callback1.called && callback2.called) { testConnection.socket.off('data', stub); done(); } } const callback1 = sinon.spy(function (response) { expect(response).to.be.equal('originate1'); expect(callback2).to.not.be.called; testDone(); }); const callback2 = sinon.spy(function (response) { expect(response).to.be.equal('originate2'); expect(callback1).to.be.called; testDone(); }); testConnection.api('originate1', callback1); setTimeout(function () { testConnection.api('originate2', callback2); }, 20); }); }); describe('.bgapi()', function () { it('Calls the callback when `esl::event::BACKGROUND_JOB::<jobId>` comes', function (done) { const stub = function (buffer: Buffer) { const data = buffer.toString('utf8'); if (data === 'bgapi originate\nJob-UUID: jobid\n\n') testConnection.emit('esl::event::BACKGROUND_JOB::jobid', 'event'); }; testConnection.socket.on('data', stub); testConnection.bgapi('originate', '', 'jobid', function (response) { expect(response).to.be.equal('event'); testConnection.socket.off('data', stub); done(); }) }); it('Gets the correct response for each call if called twice', function (done) { const stub = function (buffer: Buffer) { const data = buffer.toString('utf8'); if (data.indexOf('bgapi originate1\nJob-UUID: jobid1\n\n') !== -1) { setTimeout(function () { testConnection.emit('esl::event::BACKGROUND_JOB::jobid1', 'originate1'); }, 20); } if (data.indexOf('bgapi originate2\nJob-UUID: jobid2\n\n') !== -1) testConnection.emit('esl::event::BACKGROUND_JOB::jobid2', 'originate2'); }; testConnection.socket.on('data', stub); const testDone = function () { if (callback1.called && callback2.called) { testConnection.socket.off('data', stub); done(); } } const callback1 = sinon.spy(function (response) { expect(response).to.be.equal('originate1'); expect(callback2).to.be.called; testDone(); }); const callback2 = sinon.spy(function (response) { expect(response).to.be.equal('originate2'); expect(callback1).to.not.be.called; testDone(); }); testConnection.bgapi('originate1', '', 'jobid1', callback1); testConnection.bgapi('originate2', '', 'jobid2', callback2); }); }); after(function () { testConnection.disconnect(); testServer.close(); }); }); }); function testConnectionInstance(conn: Connection) { // public statics expect(Connection.createInbound).to.be.a('function'); expect(Connection.createOutbound).to.be.a('function'); // public low-level functions expect(conn.socketDescriptor).to.be.a('function'); expect(conn.connected).to.be.a('function'); expect(conn.getInfo).to.be.a('function'); expect(conn.send).to.be.a('function'); expect(conn.sendRecv).to.be.a('function'); expect(conn.api).to.be.a('function'); expect(conn.bgapi).to.be.a('function'); expect(conn.sendEvent).to.be.a('function'); expect(conn.filter).to.be.a('function'); expect(conn.events).to.be.a('function'); expect(conn.execute).to.be.a('function'); expect(conn.executeAsync).to.be.a('function'); expect(conn.setAsyncExecute).to.be.a('function'); expect(conn.setEventLock).to.be.a('function'); expect(conn.disconnect).to.be.a('function'); // public high-level functions expect(conn.filterDelete).to.be.a('function'); expect(conn.auth).to.be.a('function'); expect(conn.subscribe).to.be.a('function'); expect(conn.show).to.be.a('function'); expect(conn.originate).to.be.a('function'); expect(conn.message).to.be.a('function'); // member defaults expect(conn.execAsync).to.equal(false); expect(conn.execLock).to.equal(false); expect(conn.authed).to.equal(false); // Not checked because it can race, and isn't super important to check here. // expect(conn.connecting).to.equal(false); } function testConnectionSend(done: Mocha.Done, conn: Connection, args: ITestSendArgs, expected: string) { conn.socket.once('data', function (data) { expect(data.toString('utf8')).to.equal(expected); done(null); }); conn.send.apply(conn, args); } function sendChannelExecuteResponse(conn: Connection, appUuid: string, appName: string, uniqueId: string) { // condensed output from FreeSWITCH to test relevant parts. const resp = [ 'Event-Name: CHANNEL_EXECUTE_COMPLETE', 'Unique-ID: ' + uniqueId, 'Application: ' + appName, 'Application-Response: _none_', 'Application-UUID: ' + appUuid, '', '', ].join('\n'); conn.socket.write('Content-Type: text/event-plain\n'); conn.socket.write('Content-Length: '); conn.socket.write(resp.length.toString()); conn.socket.write('\n\n'); conn.socket.write(resp); } function testChannelExecute(conn: Connection, appName: string, appArg: string, requestId: string, cb: ICallback<Event>) { conn.socket.once('data', function (data) { const str = data.toString('utf8'); const lines = str.split('\n'); expect(lines).to.contain(`sendmsg ${requestId}`); expect(lines).to.contain('call-command: execute'); expect(lines).to.contain(`execute-app-name: ${appName}`); expect(lines.some(x => x.includes('Event-UUID: '))).to.be.true; if (appArg) { expect(lines).to.contain(`execute-app-arg: ${appArg}`); } else { expect(lines).to.not.contain('execute-app-arg: '); expect(lines).to.not.contain('execute-app-arg: undefined'); expect(lines).to.not.contain('execute-app-arg: null'); expect(lines).to.not.contain('execute-app-arg: [object Object]'); } // first send an unrelated message that should not be picked up. const otherUuid = uuid.v4(); sendChannelExecuteResponse(conn, otherUuid, 'sleep', requestId); const match = /\nEvent-UUID: ([0-9a-f-]+)\n/.exec(str); const appUuid = match && match[1]; if (appUuid) sendChannelExecuteResponse(conn, appUuid, appName, requestId); }); conn.execute(appName, appArg, requestId, cb); }
the_stack
import { Component, NotifyPropertyChanges, INotifyPropertyChanged, ChildProperty, Property, Collection, append, extend, Event, EmitType, BaseEventArgs, EventHandler, closest, addClass, removeClass } from '@syncfusion/ej2-base'; import { ListBase, ListBaseOptions } from '@syncfusion/ej2-lists'; import { BreadcrumbModel, BreadcrumbItemModel } from './breadcrumb-model'; type obj = { [key: string]: Object }; const ICONRIGHT: string = 'e-icon-right'; const ITEMTEXTCLASS: string = 'e-breadcrumb-text'; const ICONCLASS: string = 'e-breadcrumb-icon'; /** * Defines the Breadcrumb overflow modes. */ export type BreadcrumbOverflowMode = 'Default' | 'Collapsed'; export class BreadcrumbItem extends ChildProperty<BreadcrumbItem> { /** * Specifies the text content of the Breadcrumb item. * * @default '' */ @Property('') public text: string; /** * Specifies the Url of the Breadcrumb item that will be activated when clicked. * * @default '' */ @Property('') public url: string; /** * Defines a class/multiple classes separated by a space for the item that is used to include an icon. * * @default null */ @Property(null) public iconCss: string; } /** * Interface for item click event. */ export interface BreadcrumbClickEventArgs extends BaseEventArgs { /** * Specifies the item's element. */ element: HTMLElement; /** * Specifies the Breadcrumb item. */ item: BreadcrumbItemModel; /** * Specifies the item click event. */ event: Event; } /** * Interface for before item render event. */ export interface BreadcrumbBeforeItemRenderEventArgs extends BaseEventArgs { /** * Specifies the item's element. */ element: HTMLElement; /** * Specifies the Breadcrumb item. */ item: BreadcrumbItemModel; } /** * Breadcrumb is a graphical user interface that helps to identify or highlight the current location within a hierarchical structure of websites. * The aim is to make the user aware of their current position in a hierarchy of website links. * ```html * <nav id='breadcrumb'></nav> * ``` * ```typescript * <script> * var breadcrumbObj = new Breadcrumb({ items: [{ text: 'Home', url: '/' }, { text: 'Index', url: './index.html }]}); * breadcrumbObj.appendTo("#breadcrumb"); * </script> * ``` */ @NotifyPropertyChanges export class Breadcrumb extends Component<HTMLElement> implements INotifyPropertyChanged { private isExpanded: boolean; private startIndex: number; private endIndex: number; private _maxItems: number; /** * Defines the Url based on which the Breadcrumb items are generated. * * @default '' */ @Property('') public url: string; /** * Defines the list of Breadcrumb items. * * @default [] */ @Collection<BreadcrumbItemModel>([], BreadcrumbItem) public items: BreadcrumbItemModel[]; /** * Specifies the Url of the active Breadcrumb item. * * @default '' */ @Property('') public activeItem: string; /** * Specifies an integer to enable overflow behavior when the Breadcrumb items count exceeds and it is based on the overflowMode property. * * @default 0 */ @Property(0) public maxItems: number; /** * Specifies the overflow mode of the Breadcrumb item when it exceeds maxItems count. The possible values are, * - Default: Specified maxItems count will be visible and the remaining items will be hidden. While clicking on the previous item, the hidden item will become visible. * - Collapsed: Only the first and last items will be visible, and the remaining items will be hidden in the collapsed icon. When the collapsed icon is clicked, all items become visible. * * @default 'Default' */ @Property('Default') public overflowMode: BreadcrumbOverflowMode; /** * Defines class/multiple classes separated by a space in the Breadcrumb element. * * @default '' */ @Property('') public cssClass: string; /** * Specifies the width for the Breadcrumb component container element. If the Breadcrumb items overflow, the browsers horizontal scroll will be activated based on the device. * * @default '' */ @Property('') public width: string; /** * Specifies the template for Breadcrumb item. * * @default null */ @Property(null) public itemTemplate: string; /** * Specifies the separator template for Breadcrumb. * * @default '/' */ @Property('/') public separatorTemplate: string; /** * Enable or disable the item's navigation, when set to false, each item navigation will be prevented. * * @default true */ @Property(true) public enableNavigation: boolean; /** * Enable or disable the active item navigation, when set to true, active item will be navigable. * * @default false */ @Property(false) public enableActiveItemNavigation: boolean; /** * Overrides the global culture and localization value for this component. Default global culture is 'en-US'. * * @default '' * @private * @aspIgnore */ @Property('') public locale: string; /** * Triggers while rendering each breadcrumb item. * * @event beforeItemRender */ @Event() public beforeItemRender: EmitType<BreadcrumbBeforeItemRenderEventArgs>; /** * Triggers while clicking the breadcrumb item. * * @event itemClick */ @Event() public itemClick: EmitType<BreadcrumbClickEventArgs>; /** * Triggers once the component rendering is completed. * * @event created */ @Event() public created: EmitType<Event>; /** * Constructor for creating the widget. * * @private * @param {BreadcrumbModel} options - Specifies the Breadcrumb model. * @param {string | HTMLElement} element - Specifies the element. */ public constructor(options?: BreadcrumbModel, element?: string | HTMLElement) { super(options, <string | HTMLElement>element); } /** * @private * @returns {void} */ protected preRender(): void { // pre render code } /** * Initialize the control rendering. * * @private * @returns {void} */ protected render(): void { this.initialize(); this.renderItems(this.items); this.wireEvents(); } private initialize(): void { this._maxItems = this.maxItems; this.element.setAttribute('aria-label', 'breadcrumb'); if (this.cssClass) { addClass([this.element], this.cssClass.split(' ')); } this.setWidth(); this.initItems(); this.initPvtProps(); } private initPvtProps(): void { if (this.overflowMode === 'Default' && this._maxItems > 0) { this.startIndex = this.items.length - (this._maxItems - 1); this.endIndex = this.items.length - 1; } } private setWidth(): void { if (this.width) { this.element.style.width = this.width; } } private initItems(): void { if (!this.items.length) { let baseUri: string; let uri: string[]; const items: BreadcrumbItemModel[] = []; if (this.url) { const url: URL = new URL(this.url); baseUri = url.origin + '/'; uri = url.href.split(baseUri)[1].split('/'); } else { baseUri = window.location.origin + '/'; uri = window.location.href.split(baseUri)[1].split('/'); } items.push({ iconCss: 'e-icons e-home', url: baseUri }); for (let i: number = 0; i < uri.length; i++) { items.push({ text: uri[i], url: baseUri + uri[i] }); baseUri += uri[i] + '/'; } this.setProperties({ items: items }, true); } } private renderItems(items: BreadcrumbItemModel[]): void { let item: BreadcrumbItemModel[] | object[]; let isSingleLevel: boolean; const isIconRight: boolean = this.element.classList.contains(ICONRIGHT); const itemsLength: number = items.length; if (itemsLength) { let isActiveItem: boolean; let isLastItem: boolean; let j: number = 0; const len: number = (itemsLength * 2) - 1; const ol: HTMLElement = this.createElement('ol'); const showIcon: boolean = this.hasField(items, 'iconCss'); const isDisabled: boolean = this.element.classList.contains('e-disabled'); const isCollasped: boolean = (this.overflowMode === 'Collapsed' && this._maxItems > 0 && itemsLength > this.maxItems && !this.isExpanded); const isDefaultOverflowMode: boolean = (this.overflowMode === 'Default' && this._maxItems > 0); const listBaseOptions: ListBaseOptions = { moduleName: this.getModuleName(), showIcon: showIcon, itemNavigable: true, itemCreated: (args: { curData: BreadcrumbItemModel, item: HTMLElement, fields: obj }): void => { const isLastItem: boolean = (args.curData as { isLastItem: boolean }).isLastItem; if ((args.curData as { isEmptyUrl: boolean }).isEmptyUrl) { args.item.children[0].removeAttribute('href'); if (!isLastItem || (isLastItem && this.enableActiveItemNavigation)) { args.item.children[0].setAttribute('tabindex', '0'); EventHandler.add(args.item.children[0], 'keydown', this.keyDownHandler, this); } } if (isLastItem && args.item.children.length && !this.itemTemplate) { delete (args.curData as { isLastItem: boolean }).isLastItem; args.item.innerHTML = this.createElement('span', { className: ITEMTEXTCLASS, innerHTML: args.item.children[0].innerHTML }).outerHTML; } if (args.curData.iconCss && !args.curData.text && !this.itemTemplate) { args.item.classList.add('e-icon-item'); } if (isDefaultOverflowMode) { args.item.setAttribute('item-index', j.toString()); } if (args.item.querySelector('.' + ITEMTEXTCLASS)) { EventHandler.add(args.item.querySelector('.' + ITEMTEXTCLASS), 'focus', () => { args.item.classList.add('e-focus'); }, this); EventHandler.add(args.item.querySelector('.' + ITEMTEXTCLASS), 'focusout', () => { args.item.classList.remove('e-focus'); }, this); } const eventArgs: BreadcrumbBeforeItemRenderEventArgs = { item: extend({}, (args.curData as { properties: object }).properties ? (args.curData as { properties: object }).properties : args.curData), element: args.item }; this.trigger('beforeItemRender', eventArgs); const containsRightIcon: boolean = (isIconRight || eventArgs.element.classList.contains(ICONRIGHT)); if (containsRightIcon && args.curData.iconCss && !this.itemTemplate) { args.item.querySelector('.e-anchor-wrap').append(args.item.querySelector('.' + ICONCLASS)); } if (isDisabled || eventArgs.element.classList.contains('e-disabled')) { args.item.setAttribute('aria-disabled', 'true'); } if (!this.itemTemplate) { this.beforeItemRenderChanges(args.curData, eventArgs.item, args.item, containsRightIcon); } } }; for (let i: number = 0; i < len; (i % 2 && j++), i++) { isActiveItem = (this.activeItem && this.activeItem === items[j].url); if (isCollasped && i > 1 && i < len - 2) { continue; } else if (isDefaultOverflowMode && ((j < this.startIndex || j > this.endIndex) && (i % 2 ? j !== this.startIndex - 1 : true)) && j !== 0) { continue; } if (i % 2) { // separator item listBaseOptions.template = this.separatorTemplate ? this.separatorTemplate : '/'; listBaseOptions.itemClass = 'e-breadcrumb-separator'; isSingleLevel = false; item = [{ previousItem: (item as []).pop(), nextItem: items[j] }]; } else { // list item listBaseOptions.itemClass = ''; if (this.itemTemplate) { listBaseOptions.template = this.itemTemplate; isSingleLevel = false; } else { isSingleLevel = true; } item = [extend({}, (items[j] as { properties: object }).properties ? (items[j] as { properties: object }).properties : items[j])]; if (!(item as BreadcrumbItemModel[])[0].url && !this.itemTemplate) { item = [extend({}, (item as BreadcrumbItemModel[])[0], { isEmptyUrl: true, url: '#' })]; } isLastItem = isDefaultOverflowMode && (j === this.endIndex); if ((((i === len - 1 || isLastItem) && !this.itemTemplate) || isActiveItem) && !this.enableActiveItemNavigation) { (item[0] as { isLastItem: boolean }).isLastItem = true; } } append(ListBase.createList(this.createElement, item as { [key: string]: Object; }[], listBaseOptions, isSingleLevel, this) .childNodes, ol); if (isCollasped && i === 1) { const li: Element = this.createElement('li', { className: 'e-icons e-breadcrumb-collapsed', attrs: { 'tabindex': '0' } }); EventHandler.add(li, 'keyup', this.expandHandler, this); ol.append(li); } if (isActiveItem || isLastItem) { break; } } if ((this as unknown as { isReact: boolean }).isReact) { this.renderReactTemplates(); } this.element.append(ol); this.calculateMaxItems(); } } private calculateMaxItems(): void { if (!this._maxItems) { if (this.overflowMode === 'Default' || this.overflowMode === 'Collapsed') { const width: number = this.element.offsetWidth; let liWidth: number = (this.element.children[0].children[0] as HTMLElement).offsetWidth; const liElems: HTMLElement[] = [].slice.call(this.element.children[0].children).reverse(); for (let i: number = 0; i < liElems.length; i++) { if (liWidth > width) { this._maxItems = Math.ceil((i - 1) / 2) + 1; this.initPvtProps(); return this.reRenderItems(); } else { liWidth += liElems[i].offsetWidth; } } } } } private hasField(items: BreadcrumbItemModel[], field: string): boolean { for (let i: number = 0, len: number = items.length; i < len; i++) { if ((<obj>items[i])[field]) { return true; } } return false; } private beforeItemRenderChanges(prevItem: BreadcrumbItemModel, currItem: BreadcrumbItemModel, elem: Element, isRightIcon: boolean) : void { const wrapElem: Element = elem.querySelector('.e-anchor-wrap'); if (currItem.text !== prevItem.text) { wrapElem.childNodes.forEach((child: Element) => { if (child.nodeType === Node.TEXT_NODE) { child.textContent = currItem.text; } }); } if (currItem.iconCss !== prevItem.iconCss) { const iconElem: Element = elem.querySelector('.' + ICONCLASS); if (iconElem) { if (currItem.iconCss) { removeClass([iconElem], prevItem.iconCss.split(' ')); addClass([iconElem], currItem.iconCss.split(' ')); } else { iconElem.remove(); } } else if (currItem.iconCss) { const iconElem: Element = this.createElement('span', { className: ICONCLASS + ' ' + currItem.iconCss }); if (isRightIcon) { append([iconElem], wrapElem); } else { wrapElem.insertBefore(iconElem, wrapElem.childNodes[0]); } } } if (currItem.url !== prevItem.url && this.enableNavigation) { const anchor: Element = elem.querySelector('a.' + ITEMTEXTCLASS); if (anchor) { if (currItem.url) { anchor.setAttribute('href', currItem.url); } else { anchor.removeAttribute('href'); } } } } private reRenderItems(): void { this.element.innerHTML = ''; this.renderItems(this.items); } private clickHandler(e: MouseEvent): void { const li: Element = closest(e.target as Element, '.e-breadcrumb-item'); if (li && (closest(e.target as Element, '.' + ITEMTEXTCLASS) || this.itemTemplate)) { let idx: number = [].slice.call(li.parentElement.children).indexOf(li); idx = Math.floor(idx / 2); if (this.overflowMode === 'Default' && this._maxItems > 0 && this.endIndex !== 0) { idx = parseInt(li.getAttribute('item-index'), 10); if (this.startIndex > 1) { this.startIndex -= (this.endIndex - idx); } this.endIndex = idx; this.reRenderItems(); } this.trigger('itemClick', { element: li, item: this.items[idx], event: e }); if (this.items[idx].url) { this.activeItem = this.items[idx].url; this.dataBind(); } } if (!this.enableNavigation) { e.preventDefault(); } if ((e.target as Element).classList.contains('e-breadcrumb-collapsed')) { this.isExpanded = true; this.reRenderItems(); } } private resize(): void { this._maxItems = this.maxItems; this.initPvtProps(); this.reRenderItems(); } private expandHandler(e: KeyboardEvent): void { if (e.key === 'Enter') { this.isExpanded = true; this.reRenderItems(); } } private keyDownHandler(e: KeyboardEvent): void { if (e.key === 'Enter') { this.clickHandler(e as unknown as MouseEvent); } } /** * Called internally if any of the property value changed. * * @private * @param {BreadcrumbModel} newProp - Specifies the new properties. * @param {BreadcrumbModel} oldProp - Specifies the old properties. * @returns {void} */ public onPropertyChanged(newProp: BreadcrumbModel, oldProp: BreadcrumbModel): void { for (const prop of Object.keys(newProp)) { switch (prop) { case 'activeItem': case 'items': case 'enableActiveItemNavigation': this.reRenderItems(); break; case 'overflowMode': case 'maxItems': this.initPvtProps(); this.reRenderItems(); break; case 'url': this.initItems(); this.reRenderItems(); break; case 'width': this.setWidth(); this._maxItems = this.maxItems; this.initPvtProps(); this.reRenderItems(); break; case 'cssClass': if (oldProp.cssClass) { removeClass([this.element], oldProp.cssClass.split(' ')); } if (newProp.cssClass) { addClass([this.element], newProp.cssClass.split(' ')); } if ((oldProp.cssClass && oldProp.cssClass.indexOf(ICONRIGHT) > -1) && !(newProp.cssClass && newProp.cssClass.indexOf(ICONRIGHT) > -1) || !(oldProp.cssClass && oldProp.cssClass.indexOf(ICONRIGHT) > -1) && (newProp.cssClass && newProp.cssClass.indexOf(ICONRIGHT) > -1)) { this.reRenderItems(); } break; } } } private wireEvents(): void { EventHandler.add(this.element, 'click', this.clickHandler, this); window.addEventListener('resize', this.resize.bind(this)); } private unWireEvents(): void { EventHandler.remove(this.element, 'click', this.clickHandler); window.removeEventListener('resize', this.resize.bind(this)); } /** * Get the properties to be maintained in the persisted state. * * @returns {string} - Persist data */ protected getPersistData(): string { return this.addOnPersist(['activeItem']); } /** * Get module name. * * @private * @returns {string} - Module Name */ protected getModuleName(): string { return 'breadcrumb'; } /** * Destroys the widget. * * @returns {void} */ public destroy(): void { this.unWireEvents(); this.element.innerHTML = ''; if (this.cssClass) { removeClass([this.element], this.cssClass.split(' ')); } } }
the_stack
import WebSocket from 'ws'; import chalk from 'chalk'; import util from 'util'; import { az } from '../../core/utils'; import createGitHubRepo from '../github/repo'; import { loginWithGitHub } from '../github/login-github'; type AzureBlobStorageItem = { name: string, contentLength: number, contentType: string, lastModified: string; url: string; }; type WsRequest = { method: 'LOGINAZURE' | 'LOGINGITHUB' | 'GET' | 'POST' | 'DELETE' | 'PUT' | 'STATUS'; url: string; body: { [key: string]: string }; requestId: string; } type WsResponse = { requestId: string; statusCode: number; body: { [key: string]: string }; time: number; } const KeyVault = { ConnectionString: { Storage: '', Database: '' as string | undefined, } }; export function sendWebSocketResponse(ws: WebSocket, requestId: string, body: Object | null, statusCode: number = 200) { const response = { requestId, body, statusCode, time: Date.now(), } as WsResponse; ws.send(JSON.stringify(response)); console.log(``); console.log(`Response:`); console.log(util.inspect(response, { depth: 4, colors: true })); } export async function processWebSocketRequest(ws: WebSocket, message: WebSocket.Data) { const request = JSON.parse(String(message)); let { method, url = '/', requestId, body } = request as WsRequest; // /accounts/${subscriptionId}/projects/${resourceId}/storages/${storageId} const [_, _subscriptionLabel, subscriptionId, resourceType, resourceId, providerType, storageId] = url.split('/'); let projectName = (body?.projectName)?.replace(/\s+/g, ''); // some resources require that name values must be less than 24 characters with no whitespace let projectNameUnique = `${projectName}${(Math.random() + 1).toString(36).substring(2)}`.substr(0, 24); // if resourceId is provided then use it as project name if (resourceId) { projectName = resourceId; } if (storageId) { projectNameUnique = storageId; } const location = 'westeurope'; console.log(``); console.log(`Request:`); console.log(request); console.log(`Parameters:`); console.log({ projectName, projectNameUnique, location, subscriptionId, resourceType, resourceId, providerType }); switch (method) { case 'POST': if (resourceType === 'projects') { try { sendWebSocketResponse(ws, requestId, { resource: 'GITHUB' }, 202); try { var { html_url, default_branch } = await createGitHubRepo({ token: body.gitHubToken, projectName, }) sendWebSocketResponse(ws, requestId, { resource: 'GITHUB' }, 200); } catch (error) { console.error(chalk.red(error)); return sendWebSocketResponse(ws, requestId, { resource: 'GITHUB', error }, 500); } //====== const resourceGroup = createProject({ ws, requestId, projectName, projectNameUnique, location }); await Promise.all([resourceGroup]); //====== const swa = createSwa({ ws, requestId, projectName, projectNameUnique, location, html_url, default_branch, gitHubToken: body.gitHubToken }); const storage = createStorage({ ws, requestId, projectName, projectNameUnique, subscriptionId, location }); const databse = createDatabase({ ws, requestId, projectName, projectNameUnique, subscriptionId }); await Promise.all([swa, storage, databse]); console.log(`Database connection string: ${KeyVault.ConnectionString.Database}`); if (KeyVault.ConnectionString.Database) { await updateSwaWithDatabaseConnectionStrings({ connectionStrings: KeyVault.ConnectionString.Database, projectNameUnique }); console.log('updated SWA with connection string'); } // end operation sendWebSocketResponse(ws, requestId, { projectName: projectNameUnique }, 201); } catch (error) { console.error(chalk.red(error)); return sendWebSocketResponse(ws, requestId, { error }, 500); } } break; case 'GET': if (resourceType === 'projects') { // GET /accounts/${accountId}/projects/${projectId} if (resourceId) { if (!providerType) { // TODO: list all resource groups } // GET /accounts/${accountId}/projects/${projectId}/storages else if (providerType === 'storages') { return await listStorage({ ws, requestId, projectNameUnique, projectName }); } } // GET /accounts/${accountId}/projects/ else { sendWebSocketResponse(ws, requestId, null, 202); let resourceGroupsList = await az<AzureResourceGroup[]>( `group list --subscription "${subscriptionId}" --query "[].{name:name, id:id, location:location, tags:tags}"` ); resourceGroupsList = resourceGroupsList.filter((a, _b) => (a.tags && a.tags["x-created-by"] === "hexa")); sendWebSocketResponse(ws, requestId, resourceGroupsList); } } else { sendWebSocketResponse(ws, requestId, { error: `resorce type not implemented "${resourceType}"` }, 501); } break; case 'LOGINAZURE': sendWebSocketResponse(ws, requestId, null, 202); const subscriptionsList = await az<AzureSubscription[]>(`login --query "[].{name:name, state:state, id:id, user:user}"`); sendWebSocketResponse(ws, requestId, subscriptionsList); break; case 'LOGINGITHUB': let token; try { token = await loginWithGitHub((oauthCallbaclUrl: string) => { sendWebSocketResponse(ws, requestId, { url: oauthCallbaclUrl }, 200); }); } catch (error) { sendWebSocketResponse(ws, requestId, null, 500); console.error(chalk.red(error)); } if (token) { sendWebSocketResponse(ws, requestId, { token }, 200); } else { sendWebSocketResponse(ws, requestId, null, 404); } break; case 'DELETE': if (resourceType === 'projects') { try { sendWebSocketResponse(ws, requestId, null, 202); await az<void>( `group delete \ --name "${projectName}" \ --subscription "${subscriptionId}" \ --yes` ); sendWebSocketResponse(ws, requestId, null, 200); } catch (error) { sendWebSocketResponse(ws, requestId, { error }, 500); } } break; default: sendWebSocketResponse(ws, requestId, { error: 'method not allowed' }, 405); } } async function createProject({ ws, requestId, projectName, projectNameUnique, location }: any) { try { sendWebSocketResponse(ws, requestId, { resource: 'PROJECT' }, 202); await az<AzureResourceGroup>( `group create \ --location "${location}" \ --name "${projectName}" \ --tag "x-created-by=hexa" \ --tag "x-project-name="${projectNameUnique}" \ --query "{name:name, id:id, location:location}"` ); sendWebSocketResponse(ws, requestId, { resource: 'PROJECT', }, 200); } catch (error) { console.error(chalk.red(error)); return sendWebSocketResponse(ws, requestId, { resource: 'PROJECT', error }, 500); } } async function createSwa({ ws, requestId, projectName, projectNameUnique, location, html_url, default_branch, gitHubToken }: any) { try { sendWebSocketResponse(ws, requestId, { resource: 'SWA' }, 202); const swa = await az<AzureStaticWebApps>( `staticwebapp create \ --name "${projectNameUnique}" \ --resource-group "${projectName}" \ --source "${html_url}" \ --location "${location}" \ --branch "${default_branch}" \ --output-location "./" \ --api-location "api" \ --app-location "./" \ --token "${gitHubToken}" \ --tag "x-created-by=hexa" \ --sku "free" \ --debug \ --query "{name:name, id:id, url:defaultHostname}"`, ); sendWebSocketResponse(ws, requestId, { resource: 'SWA', url: swa.url }, 200); } catch (error) { console.error(chalk.red(error)); return sendWebSocketResponse(ws, requestId, { resource: 'SWA', error }, 500); } } async function getStorageConnectionString({ projectNameUnique }: any) { return await az<{ connectionString: string }>( `storage account show-connection-string \ --name "${projectNameUnique}" ` ); } async function createStorage({ ws, location, requestId, projectName, projectNameUnique, subscriptionId }: any) { try { sendWebSocketResponse(ws, requestId, { resource: 'STORAGE', }, 202); await az<AzureStorage>( `storage account create \ --location "${location}" \ --name "${projectNameUnique}" \ --subscription "${subscriptionId}" \ --resource-group "${projectName}" \ --kind "StorageV2" \ --tag "x-created-by=hexa" \ --query "{name:name, id:id, location:location}"` ); const storageConnectionString = await getStorageConnectionString({ projectNameUnique }); KeyVault.ConnectionString.Storage = storageConnectionString.connectionString; await az<AzureStorage>( `storage container create \ --resource-group "${projectName}" \ --name "${projectNameUnique}" \ --public-access "blob" \ --connection-string "${storageConnectionString.connectionString}"` ); sendWebSocketResponse(ws, requestId, { resource: 'STORAGE', }, 200); } catch (error) { console.error(chalk.red(error)); return sendWebSocketResponse(ws, requestId, { resource: 'STORAGE', error }, 500); } } async function createDatabase({ ws, requestId, projectName, projectNameUnique }: any) { try { sendWebSocketResponse(ws, requestId, { resource: 'DATABASE', }, 202); // TODO: enable free tier for non-Internal subscriptions // --enable-free-tier \ await az<DatabaseInstance>( `cosmosdb create \ --name "${projectNameUnique}" \ --resource-group "${projectName}" \ --kind "MongoDB" \ --server-version "4.0" \ --default-consistency-level "Eventual" \ --tag "x-created-by=hexa" \ --enable-multiple-write-locations false \ --enable-automatic-failover false \ --query "{id: id, name: name, tags: tags, endpoint: documentEndpoint}"` ); await az<void>( `cosmosdb mongodb database create \ --name "${projectNameUnique}" \ --account-name "${projectNameUnique}" \ --resource-group "${projectName}"` ); // fetch connection strings const connectionStrings = await az<{ connectionStrings: Array<{ connectionString: string, description: string }> }>( `cosmosdb keys list \ --name "${projectNameUnique}" \ --resource-group "${projectName}" \ --type "connection-strings"` ); KeyVault.ConnectionString.Database = connectionStrings.connectionStrings.pop()?.connectionString; sendWebSocketResponse(ws, requestId, { resource: 'DATABASE', connectionString: KeyVault.ConnectionString.Database }, 200); } catch (error) { console.error(chalk.red(error)); return sendWebSocketResponse(ws, requestId, { resource: 'DATABASE', error }, 500); } } async function updateSwaWithDatabaseConnectionStrings({ projectNameUnique, databaseConnectionString }: any) { console.log(`TODO: az staticwebapp appsettings set doesn not support updating app setting right now!`); console.log({ projectNameUnique, databaseConnectionString }); return Promise.resolve(); // return await az<void>( // `staticwebapp appsettings set \ // --name "${projectNameUnique}" \ // --setting-names 'COSMOSDB_CONNECTION_STRING="${databaseConnectionString}"'` // ); } async function listStorage({ ws, requestId, projectName, projectNameUnique }: any) { try { sendWebSocketResponse(ws, requestId, { resource: 'STORAGE', }, 202); const storageConnectionString = await getStorageConnectionString({ projectName, projectNameUnique }); let blobs = await az<Array<AzureBlobStorageItem>>( `storage blob list \ --account-name "${projectNameUnique}" \ --container-name "${projectNameUnique}" \ --connection-string "${storageConnectionString.connectionString}" \ --query "[].{name: name, contentLength: properties.contentLength, lastModified: properties.lastModified, contentType: properties.contentSettings.contentType}" `); blobs = blobs.map((blob: AzureBlobStorageItem) => { return { ...blob, url: `https://${projectNameUnique}.blob.core.windows.net/${projectNameUnique}/${blob.name}` } }); return sendWebSocketResponse(ws, requestId, { resource: 'STORAGE', blobs }, 200); } catch (error) { console.error(chalk.red(error)); return sendWebSocketResponse(ws, requestId, { resource: 'STORAGE', error }, 500); } }
the_stack
"use strict"; import { IOptions as GlobOptions } from "glob"; import * as path from "path"; import { ModuleSpecifier } from "../modules/EyeglassModule"; import { Options as SassOptions, SassImplementation } from "./SassImplementation"; import { URI } from "./URI"; import merge = require("lodash.merge"); import type { Importer, FunctionDeclarations } from "node-sass"; export const DEFAULT_EYEGLASS_COMPAT = "^2.0"; export interface AssetSourceOptions { /** * The namespace of this asset source. */ name?: string; /** * The httpPrefix of this source relative to the httpPrefix of all assets. * If not provided, the namespace of this source is used. */ httpPrefix?: string; /** * The directory of this asset source. */ directory: string; /** * Options for globbing files within the directory. */ globOpts?: GlobOptions; /** * Pattern for globbing files within the directory. * Defaults to "**\/*" */ pattern?: string; } export interface AssetOptions { /** * A list of asset sources. */ sources?: Array<AssetSourceOptions>; /** * The httpPrefix for all assets relative to the project's httpRoot. */ httpPrefix?: string; /** * A http prefix directory that assets urls will be relative to. * This would usually be set to the directory from which the CSS file being * rendered is served. * */ relativeTo?: string; } export interface Engines { /** * If not provided, eyeglass will require `node-sass` at the version it * currently depends. */ sass?: SassImplementation; [engine: string]: unknown; } export interface EyeglassConfig extends Required<EyeglassSpecificOptions<never>> { engines: Required<Engines>; } export interface BuildCache { get(key: string): number | string | undefined; set(key: string, value: number | string): void; } export interface EyeglassSpecificOptions<ExtraSandboxTypes = true | string> { /** * Where to find assets for the eyeglass project. */ assets?: AssetOptions; /** * Implementations provided to eyeglass that can be used by eyeglass itself * or by custom functions in an eyeglass module. */ engines?: Engines; /** * Manually declare an eyeglass modules for sass libraries that do not * declare themselves to be eyeglass modules. */ modules?: Array<ModuleSpecifier>; /** * Whether to only import a sass file once per css output file. * Defaults to true. */ enableImportOnce?: boolean; /** * Whether to install assets using symlinks or file copies. * Setting this to true is good for performance. * Defaults to false. */ installWithSymlinks?: boolean; /** * Whether to normalize paths on windows. * Defaults to true or to the value of the environment variable * `EYEGLASS_NORMALIZE_PATHS`. */ normalizePaths?: boolean; /** * Directory from which sass files are imported for this project. */ root?: string; /** * The directory in the URL from which css files are served for this project. */ httpRoot?: string; /** * Directory where eyeglass should store cache information during and across builds. * This will be created if it does not exist. */ cacheDir?: string; /** * Directory where files are output once built. */ buildDir?: string; /** * Whether to raise an error if the same eyeglass module is a dependency * more than once with incompatible semantic versions. */ strictModuleVersions?: boolean | "warn"; /** * Default to false. * * Whether to disable the strict dependency check that ensures * that Sass files in an eyeglass eyeglass module can only import sass files * from the eyeglass modules that it depends on directly. * * When true, a Sass file will be able to import from any eyeglass * module that is found in the module tree. * * This is not recommended, but may be necessary when working with manually * declared modules which currently lack a well-defined mechanism for * declaring dependencies on other manual modules. */ disableStrictDependencyCheck?: boolean; /** * When strictModuleVersions checking is enabled, * this asserts that the modules installed are compatible with the * version of eyeglass specified, in contradiction to those module's * own declaration of the version of eyeglass that they say they need. * This is helpful when eyeglass major releases occur and eyeglass modules * that you depend on haven't yet been updated, but appear to work regardless. * * The value can be any semver dependency specifier. For instance, if * eyeglass 3.0 is released, you can set this to "^3.0.0" and any eyeglass * 3.x release will be assumed ok but a 4.0 release will cause things to * break again. */ assertEyeglassCompatibility?: string; /** * Whether to cache eyeglass modules across the entire javascript process. */ useGlobalModuleCache?: boolean; /** * Ignore deprecations that started being issued at or below this version. */ ignoreDeprecations?: string; /** * Whether to allow filesystem reads and if so, from which directories. * * `false` - allows reads from the entire filesystem (insecure). * * `true` - only allows reads from the `root` directory. * * `<string>` - a directory from which reads are allowed. * * `Array<string>` - A list of directories from which to allow access. * * An empty list disables filesystem access (default). */ fsSandbox?: ExtraSandboxTypes | false | Array<string>; /** * The buildCache is provided by the caller to allow eyeglass to cache * information about files including file contents repeated disk access to * common files. The cache can be a Map, or some memory-capped cache like * `lru-cache`. This cache will only have strings or numbers placed into it. * * The cache should be cleared by the caller whenever file changes may have * occurred (usually between builds of a long-running watcher). */ buildCache?: BuildCache; } export interface ForbiddenOptions { /** @deprecated Since 0.8. */ root?: string; /** @deprecated Since 0.8 */ httpRoot?: string; /** @deprecated Since 0.8 */ cacheDir?: string; /** @deprecated Since 0.8 */ buildDir?: string; /** @deprecated Since 0.8 */ strictModuleVersions?: boolean; } export interface ForbiddenAssetOptions { /** @deprecated Since 0.8 */ assetsHttpPrefix?: string; /** @deprecated Since 0.8 */ assetsRelativeTo?: string; } export interface EyeglassOptions { eyeglass?: EyeglassSpecificOptions; assetsCache?: (cacheKey: string, lazyValue: () => string) => void; } export type Options = (SassOptions & EyeglassOptions); export type Config = SassOptions & { eyeglass: EyeglassConfig; assetsCache?: (cacheKey: string, lazyValue: () => string) => string; }; /* eslint-disable-next-line no-unused-vars */ export default class implements Config { file?: string; data?: string; importer?: Importer | Array<Importer>; functions?: FunctionDeclarations; includePaths?: Array<string>; indentedSyntax?: boolean; indentType?: string; indentWidth?: number; linefeed?: string; omitSourceMapUrl?: boolean; outFile?: string; outputStyle?: "compact" | "compressed" | "expanded" | "nested"; precision?: number; sourceComments?: boolean; sourceMap?: boolean | string; sourceMapContents?: boolean; sourceMapEmbed?: boolean; sourceMapRoot?: string; eyeglass: EyeglassConfig; assetsCache?: (cacheKey: string, lazyValue: () => string) => string; constructor(options: Options) { let config = getSassOptions(options) this.eyeglass = config.eyeglass; // this makes the compiler happy. merge(this, config); } } function includePathsFromEnv(): Array<string> { return normalizeIncludePaths(process.env.SASS_PATH, process.cwd()); } function forbidEyeglassOptionsFromSassOptions(sassOptions: ForbiddenOptions & SassOptions, eyeglassOptions: EyeglassSpecificOptions): void { // migrates the following properties from sassOptions to eyeglassOptions const forbiddenOptions: Array<keyof ForbiddenOptions> = [ "root", "cacheDir", "buildDir", "httpRoot", "strictModuleVersions" ]; forbiddenOptions.forEach(function(option) { if (eyeglassOptions[option] === undefined && sassOptions[option] !== undefined) { throw new Error(["`" + option + "` must be passed into the eyeglass options rather than the sass options:", "var options = eyeglass({", " /* sassOptions */", " ...", " eyeglass: {", " " + option + ": ...", " }", "});" ].join("\n ")); } }); } function forbidAssetOption<FromOpt extends "assetsHttpPrefix" | "assetsRelativeTo">( sassOptions: ForbiddenAssetOptions, eyeglassOptions: EyeglassSpecificOptions, fromOption: FromOpt, toOption: typeof fromOption extends "assetsHttpPrefix" ? "httpPrefix" : "relativeTo" ): void { if ((eyeglassOptions.assets === undefined || (eyeglassOptions.assets && eyeglassOptions.assets[toOption] === undefined)) && sassOptions[fromOption] !== undefined) { throw new Error([`\`${fromOption }\` has been renamed to \`${toOption}\` and must be passed into the eyeglass asset options rather than the sass options:`, "var options = eyeglass({", " /* sassOptions */", " ...", " eyeglass: {", " assets: {", ` ${toOption}: ...`, " }", " }", "});" ].join("\n ")); } } function forbidAssetOptionsFromSassOptions(sassOptions: SassOptions & ForbiddenAssetOptions, eyeglassOptions: EyeglassSpecificOptions): void { // errors on the following legacy properties if passed into sassOptions instead of eyeglassOptions forbidAssetOption(sassOptions, eyeglassOptions, "assetsHttpPrefix", "httpPrefix"); forbidAssetOption(sassOptions, eyeglassOptions, "assetsRelativeTo", "relativeTo"); } function defaultSassOptions(options: SassOptions): SassOptions { defaultValue(options, "includePaths", () => includePathsFromEnv()); return options; } function requireSass(): SassImplementation { let sass: SassImplementation; try { sass = require("node-sass") } catch (e) { try { sass = require("sass"); } catch (e) { throw new Error("A sass engine was not provided and neither `sass` nor `node-sass` were found in the current project.") } } return sass; } export function resolveConfig(options: Partial<EyeglassSpecificOptions>): EyeglassConfig { // default root dir defaultValue(options, "root", () => process.cwd()); // default cache dir defaultValue(options, "cacheDir", () => path.join(options.root!, ".eyeglass_cache")); // default engines defaultValue(options, "engines", () => {return {};}); defaultValue(options.engines!, "sass", () => requireSass()); // default assets defaultValue(options, "assets", () => {return {};}); // default httpRoot defaultValue(options, "httpRoot", () => "/"); // default enableImportOnce defaultValue(options, "enableImportOnce", () => true); // use global module caching by default defaultValue(options, "useGlobalModuleCache", () => true); // There's no eyeglass module API changes in eyeglass 2.x so we default to silencing these warnings. defaultValue(options, "assertEyeglassCompatibility", () => DEFAULT_EYEGLASS_COMPAT); // Use a simple cache that just lasts for this one file if no buildCache is provided. defaultValue(options, "buildCache", () => new Map()); // Strict dependency checks are enabled by default. defaultValue(options, "disableStrictDependencyCheck", () => false); options.fsSandbox = normalizeFsSandbox(options.fsSandbox, options.root!); return options as EyeglassConfig; } function normalizeFsSandbox(sandboxOption: Partial<EyeglassSpecificOptions>["fsSandbox"], root: string): EyeglassConfig["fsSandbox"] { let fsSandbox: false | Array<string>; if (typeof sandboxOption === "undefined") { // default to no fs access fsSandbox = []; } else if (sandboxOption === true) { // support simple enabling of the sandbox. fsSandbox = [root]; } else if (typeof sandboxOption === "string") { // support simple strings instead of requiring a list for even a single dir. fsSandbox = [sandboxOption]; } else { fsSandbox = sandboxOption; } return fsSandbox; } function normalizeIncludePaths( includePaths: string | Array<string> | undefined, baseDir: string ): Array<string> { if (!includePaths) { return []; } // in some cases includePaths is a path delimited string if (typeof includePaths === "string") { includePaths = includePaths.split(path.delimiter); } // filter out empty paths includePaths = includePaths.filter((dir) => !!dir); // make all relative include paths absolute return includePaths.map((dir) => path.resolve(baseDir, URI.system(dir))); } function normalizeSassOptions(sassOptions: SassOptions, eyeglassOptions: EyeglassConfig): Config { sassOptions.includePaths = normalizeIncludePaths(sassOptions.includePaths, eyeglassOptions.root); return Object.assign(sassOptions, {eyeglass: eyeglassOptions}); } const FORBIDDEN_OPTIONS = new Set<keyof (ForbiddenAssetOptions & ForbiddenOptions)>([ "root", "httpRoot", "cacheDir", "buildDir", "strictModuleVersions", "assetsHttpPrefix", "assetsRelativeTo", ]); function hasForbiddenOptions(options: Options): options is ForbiddenAssetOptions & SassOptions { for (let key in options) { if ((FORBIDDEN_OPTIONS as Set<string>).has(key)) { return true; } } return false; } function getSassOptions( options: Options | undefined, ): Config { let sassOptions: Options = options || {}; let eyeglassOptions: EyeglassSpecificOptions = {}; merge(eyeglassOptions, sassOptions.eyeglass); // determine whether or not we should normalize URI path separators // @see URI if (eyeglassOptions.normalizePaths !== undefined) { // TODO: make the code read the config from options which is defaulted from the env var process.env.EYEGLASS_NORMALIZE_PATHS = `${eyeglassOptions.normalizePaths}`; } if (hasForbiddenOptions(sassOptions)) { // forbid legacy eyeglassOptions within sassOptions forbidEyeglassOptionsFromSassOptions(sassOptions, eyeglassOptions); forbidAssetOptionsFromSassOptions(sassOptions, eyeglassOptions); } defaultSassOptions(sassOptions); resolveConfig(eyeglassOptions); return normalizeSassOptions(sassOptions, resolveConfig(eyeglassOptions)); } function defaultValue< T extends object, K extends keyof T, V extends () => T[K] >(obj: T, key: K, value: V): void { if (obj[key] === undefined) { obj[key] = value(); } }
the_stack
import * as t from 'io-ts'; import { RTTI_Extension, IExtension } from './RTTI_Extension'; import { RTTI_id } from '../Scalar/RTTI_id'; import { RTTI_Element, IElement } from './RTTI_Element'; import { RTTI_integer } from '../Scalar/RTTI_integer'; import { RTTI_Address, IAddress } from './RTTI_Address'; import { RTTI_Age, IAge } from './RTTI_Age'; import { RTTI_Annotation, IAnnotation } from './RTTI_Annotation'; import { RTTI_Attachment, IAttachment } from './RTTI_Attachment'; import { RTTI_CodeableConcept, ICodeableConcept } from './RTTI_CodeableConcept'; import { RTTI_Coding, ICoding } from './RTTI_Coding'; import { RTTI_ContactPoint, IContactPoint } from './RTTI_ContactPoint'; import { RTTI_Count, ICount } from './RTTI_Count'; import { RTTI_Distance, IDistance } from './RTTI_Distance'; import { RTTI_Duration, IDuration } from './RTTI_Duration'; import { RTTI_HumanName, IHumanName } from './RTTI_HumanName'; import { RTTI_Identifier, IIdentifier } from './RTTI_Identifier'; import { RTTI_Money, IMoney } from './RTTI_Money'; import { RTTI_Period, IPeriod } from './RTTI_Period'; import { RTTI_Quantity, IQuantity } from './RTTI_Quantity'; import { RTTI_Range, IRange } from './RTTI_Range'; import { RTTI_Ratio, IRatio } from './RTTI_Ratio'; import { RTTI_Reference, IReference } from './RTTI_Reference'; import { RTTI_SampledData, ISampledData } from './RTTI_SampledData'; import { RTTI_Signature, ISignature } from './RTTI_Signature'; import { RTTI_Timing, ITiming } from './RTTI_Timing'; import { RTTI_ContactDetail, IContactDetail } from './RTTI_ContactDetail'; import { RTTI_Contributor, IContributor } from './RTTI_Contributor'; import { RTTI_DataRequirement, IDataRequirement } from './RTTI_DataRequirement'; import { RTTI_Expression, IExpression } from './RTTI_Expression'; import { RTTI_ParameterDefinition, IParameterDefinition } from './RTTI_ParameterDefinition'; import { RTTI_RelatedArtifact, IRelatedArtifact } from './RTTI_RelatedArtifact'; import { RTTI_TriggerDefinition, ITriggerDefinition } from './RTTI_TriggerDefinition'; import { RTTI_UsageContext, IUsageContext } from './RTTI_UsageContext'; import { RTTI_Dosage, IDosage } from './RTTI_Dosage'; export enum StructureMap_SourceListModeKind { _first = 'first', _notFirst = 'not_first', _last = 'last', _notLast = 'not_last', _onlyOne = 'only_one' } import { createEnumType } from '../../EnumType'; export interface IStructureMap_Source { /** * Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. */ id?: string; /** * May be used to represent additional information that is not part of the basic definition of the element. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. */ extension?: IExtension[]; /** * May be used to represent additional information that is not part of the basic definition of the element and that modifies the understanding of the element in which it is contained and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions. Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself). */ modifierExtension?: IExtension[]; /** * Type or variable this rule applies to. */ context?: string; /** * Extensions for context */ _context?: IElement; /** * Specified minimum cardinality for the element. This is optional; if present, it acts an implicit check on the input content. */ min?: number; /** * Extensions for min */ _min?: IElement; /** * Specified maximum cardinality for the element - a number or a "*". This is optional; if present, it acts an implicit check on the input content (* just serves as documentation; it's the default value). */ max?: string; /** * Extensions for max */ _max?: IElement; /** * Specified type for the element. This works as a condition on the mapping - use for polymorphic elements. */ type?: string; /** * Extensions for type */ _type?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueBase64Binary?: string; /** * Extensions for defaultValueBase64Binary */ _defaultValueBase64Binary?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueBoolean?: boolean; /** * Extensions for defaultValueBoolean */ _defaultValueBoolean?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueCanonical?: string; /** * Extensions for defaultValueCanonical */ _defaultValueCanonical?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueCode?: string; /** * Extensions for defaultValueCode */ _defaultValueCode?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueDate?: string; /** * Extensions for defaultValueDate */ _defaultValueDate?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueDateTime?: string; /** * Extensions for defaultValueDateTime */ _defaultValueDateTime?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueDecimal?: number; /** * Extensions for defaultValueDecimal */ _defaultValueDecimal?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueId?: string; /** * Extensions for defaultValueId */ _defaultValueId?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueInstant?: string; /** * Extensions for defaultValueInstant */ _defaultValueInstant?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueInteger?: number; /** * Extensions for defaultValueInteger */ _defaultValueInteger?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueMarkdown?: string; /** * Extensions for defaultValueMarkdown */ _defaultValueMarkdown?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueOid?: string; /** * Extensions for defaultValueOid */ _defaultValueOid?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValuePositiveInt?: number; /** * Extensions for defaultValuePositiveInt */ _defaultValuePositiveInt?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueString?: string; /** * Extensions for defaultValueString */ _defaultValueString?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueTime?: string; /** * Extensions for defaultValueTime */ _defaultValueTime?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueUnsignedInt?: number; /** * Extensions for defaultValueUnsignedInt */ _defaultValueUnsignedInt?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueUri?: string; /** * Extensions for defaultValueUri */ _defaultValueUri?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueUrl?: string; /** * Extensions for defaultValueUrl */ _defaultValueUrl?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueUuid?: string; /** * Extensions for defaultValueUuid */ _defaultValueUuid?: IElement; /** * A value to use if there is no existing value in the source object. */ defaultValueAddress?: IAddress; /** * A value to use if there is no existing value in the source object. */ defaultValueAge?: IAge; /** * A value to use if there is no existing value in the source object. */ defaultValueAnnotation?: IAnnotation; /** * A value to use if there is no existing value in the source object. */ defaultValueAttachment?: IAttachment; /** * A value to use if there is no existing value in the source object. */ defaultValueCodeableConcept?: ICodeableConcept; /** * A value to use if there is no existing value in the source object. */ defaultValueCoding?: ICoding; /** * A value to use if there is no existing value in the source object. */ defaultValueContactPoint?: IContactPoint; /** * A value to use if there is no existing value in the source object. */ defaultValueCount?: ICount; /** * A value to use if there is no existing value in the source object. */ defaultValueDistance?: IDistance; /** * A value to use if there is no existing value in the source object. */ defaultValueDuration?: IDuration; /** * A value to use if there is no existing value in the source object. */ defaultValueHumanName?: IHumanName; /** * A value to use if there is no existing value in the source object. */ defaultValueIdentifier?: IIdentifier; /** * A value to use if there is no existing value in the source object. */ defaultValueMoney?: IMoney; /** * A value to use if there is no existing value in the source object. */ defaultValuePeriod?: IPeriod; /** * A value to use if there is no existing value in the source object. */ defaultValueQuantity?: IQuantity; /** * A value to use if there is no existing value in the source object. */ defaultValueRange?: IRange; /** * A value to use if there is no existing value in the source object. */ defaultValueRatio?: IRatio; /** * A value to use if there is no existing value in the source object. */ defaultValueReference?: IReference; /** * A value to use if there is no existing value in the source object. */ defaultValueSampledData?: ISampledData; /** * A value to use if there is no existing value in the source object. */ defaultValueSignature?: ISignature; /** * A value to use if there is no existing value in the source object. */ defaultValueTiming?: ITiming; /** * A value to use if there is no existing value in the source object. */ defaultValueContactDetail?: IContactDetail; /** * A value to use if there is no existing value in the source object. */ defaultValueContributor?: IContributor; /** * A value to use if there is no existing value in the source object. */ defaultValueDataRequirement?: IDataRequirement; /** * A value to use if there is no existing value in the source object. */ defaultValueExpression?: IExpression; /** * A value to use if there is no existing value in the source object. */ defaultValueParameterDefinition?: IParameterDefinition; /** * A value to use if there is no existing value in the source object. */ defaultValueRelatedArtifact?: IRelatedArtifact; /** * A value to use if there is no existing value in the source object. */ defaultValueTriggerDefinition?: ITriggerDefinition; /** * A value to use if there is no existing value in the source object. */ defaultValueUsageContext?: IUsageContext; /** * A value to use if there is no existing value in the source object. */ defaultValueDosage?: IDosage; /** * Optional field for this source. */ element?: string; /** * Extensions for element */ _element?: IElement; /** * How to handle the list mode for this element. */ listMode?: StructureMap_SourceListModeKind; /** * Extensions for listMode */ _listMode?: IElement; /** * Named context for field, if a field is specified. */ variable?: string; /** * Extensions for variable */ _variable?: IElement; /** * FHIRPath expression - must be true or the rule does not apply. */ condition?: string; /** * Extensions for condition */ _condition?: IElement; /** * FHIRPath expression - must be true or the mapping engine throws an error instead of completing. */ check?: string; /** * Extensions for check */ _check?: IElement; /** * A FHIRPath expression which specifies a message to put in the transform log when content matching the source rule is found. */ logMessage?: string; /** * Extensions for logMessage */ _logMessage?: IElement; } export const RTTI_StructureMap_Source: t.Type< IStructureMap_Source > = t.recursion('IStructureMap_Source', () => t.partial({ id: t.string, extension: t.array(RTTI_Extension), modifierExtension: t.array(RTTI_Extension), context: RTTI_id, _context: RTTI_Element, min: RTTI_integer, _min: RTTI_Element, max: t.string, _max: RTTI_Element, type: t.string, _type: RTTI_Element, defaultValueBase64Binary: t.string, _defaultValueBase64Binary: RTTI_Element, defaultValueBoolean: t.boolean, _defaultValueBoolean: RTTI_Element, defaultValueCanonical: t.string, _defaultValueCanonical: RTTI_Element, defaultValueCode: t.string, _defaultValueCode: RTTI_Element, defaultValueDate: t.string, _defaultValueDate: RTTI_Element, defaultValueDateTime: t.string, _defaultValueDateTime: RTTI_Element, defaultValueDecimal: t.number, _defaultValueDecimal: RTTI_Element, defaultValueId: t.string, _defaultValueId: RTTI_Element, defaultValueInstant: t.string, _defaultValueInstant: RTTI_Element, defaultValueInteger: t.number, _defaultValueInteger: RTTI_Element, defaultValueMarkdown: t.string, _defaultValueMarkdown: RTTI_Element, defaultValueOid: t.string, _defaultValueOid: RTTI_Element, defaultValuePositiveInt: t.number, _defaultValuePositiveInt: RTTI_Element, defaultValueString: t.string, _defaultValueString: RTTI_Element, defaultValueTime: t.string, _defaultValueTime: RTTI_Element, defaultValueUnsignedInt: t.number, _defaultValueUnsignedInt: RTTI_Element, defaultValueUri: t.string, _defaultValueUri: RTTI_Element, defaultValueUrl: t.string, _defaultValueUrl: RTTI_Element, defaultValueUuid: t.string, _defaultValueUuid: RTTI_Element, defaultValueAddress: RTTI_Address, defaultValueAge: RTTI_Age, defaultValueAnnotation: RTTI_Annotation, defaultValueAttachment: RTTI_Attachment, defaultValueCodeableConcept: RTTI_CodeableConcept, defaultValueCoding: RTTI_Coding, defaultValueContactPoint: RTTI_ContactPoint, defaultValueCount: RTTI_Count, defaultValueDistance: RTTI_Distance, defaultValueDuration: RTTI_Duration, defaultValueHumanName: RTTI_HumanName, defaultValueIdentifier: RTTI_Identifier, defaultValueMoney: RTTI_Money, defaultValuePeriod: RTTI_Period, defaultValueQuantity: RTTI_Quantity, defaultValueRange: RTTI_Range, defaultValueRatio: RTTI_Ratio, defaultValueReference: RTTI_Reference, defaultValueSampledData: RTTI_SampledData, defaultValueSignature: RTTI_Signature, defaultValueTiming: RTTI_Timing, defaultValueContactDetail: RTTI_ContactDetail, defaultValueContributor: RTTI_Contributor, defaultValueDataRequirement: RTTI_DataRequirement, defaultValueExpression: RTTI_Expression, defaultValueParameterDefinition: RTTI_ParameterDefinition, defaultValueRelatedArtifact: RTTI_RelatedArtifact, defaultValueTriggerDefinition: RTTI_TriggerDefinition, defaultValueUsageContext: RTTI_UsageContext, defaultValueDosage: RTTI_Dosage, element: t.string, _element: RTTI_Element, listMode: createEnumType<StructureMap_SourceListModeKind>( StructureMap_SourceListModeKind, 'StructureMap_SourceListModeKind' ), _listMode: RTTI_Element, variable: RTTI_id, _variable: RTTI_Element, condition: t.string, _condition: RTTI_Element, check: t.string, _check: RTTI_Element, logMessage: t.string, _logMessage: RTTI_Element }) );
the_stack
import {event as d3event, mouse as d3mouse} from "d3-selection"; import {Histogram2DSerialization, IViewSerialization} from "../datasetView"; import { IColumnDescription, kindIsString, RemoteObjectId, kindIsNumeric, Groups, RangeFilterArrayDescription, } from "../javaBridge"; import {Receiver, RpcRequest} from "../rpc"; import {BaseReceiver, TableTargetAPI} from "../modules"; import {CDFPlot} from "../ui/cdfPlot"; import {IDataView} from "../ui/dataview"; import {FullPage, PageTitle} from "../ui/fullPage"; import {Histogram2DPlot} from "../ui/histogram2DPlot"; import {HistogramLegendPlot} from "../ui/histogramLegendPlot"; import {SubMenu, TopMenu} from "../ui/menu"; import {HtmlPlottingSurface} from "../ui/plottingSurface"; import {TextOverlay} from "../ui/textOverlay"; import {ChartOptions, DragEventKind, HtmlString, Resolution} from "../ui/ui"; import { add, assert, assertNever, Converters, Exporter, Heatmap, ICancellable, optionToBoolean, Pair, PartialResult, percentString, reorder, significantDigits, } from "../util"; import {AxisData} from "./axisData"; import {HistogramViewBase} from "./histogramViewBase"; import {NewTargetReceiver, DataRangesReceiver} from "./dataRangesReceiver"; import {Histogram2DBarsPlot} from "../ui/histogram2DBarsPlot"; import {Histogram2DBase} from "../ui/histogram2DBase"; import {Dialog, FieldKind, saveAs} from "../ui/dialog"; import {TableMeta} from "../ui/receiver"; /** * This class is responsible for rendering a 2D histogram. * This is a histogram where each bar is divided further into sub-bars. */ export class Histogram2DView extends HistogramViewBase<Pair<Groups<Groups<number>>, Groups<number>>> { protected yAxisData: AxisData; protected xPoints: number; protected yPoints: number; protected relative: boolean; // true when bars are normalized to 100% protected stacked: boolean; protected plot: Histogram2DBase; protected legendPlot: HistogramLegendPlot; protected legendSurface: HtmlPlottingSurface; protected viewMenu: SubMenu; protected readonly defaultProvenance = "From 2D histogram"; constructor(remoteObjectId: RemoteObjectId, meta: TableMeta, protected samplingRate: number, page: FullPage) { super(remoteObjectId, meta, page, "2DHistogram"); this.viewMenu = new SubMenu([{ text: "refresh", action: () => { this.refresh(); }, help: "Redraw this view", }, { text: "table", action: () => this.showTable([this.xAxisData.description, this.yAxisData.description], this.defaultProvenance), help: "Show the data underlying this plot in a tabular view. ", }, { text: "exact", action: () => { this.exactHistogram(); }, help: "Draw this histogram without approximations.", }, { text: "# buckets...", action: () => this.chooseBuckets(), help: "Change the number of buckets used for drawing the histogram.", }, { text: "swap axes", action: () => { this.swapAxes(); }, help: "Redraw this histogram by swapping the X and Y axes.", }, { text: "quartiles", action: () => { this.showQuartiles(); }, help: "Plot this data as a vector of quartiles view.", }, { text: "stacked/parallel", action: () => { this.toggleStacked(); }, help: "Plot this data either as stacked bars or as parallel bars.", }, { text: "heatmap", action: () => { this.doHeatmap(); }, help: "Plot this data as a heatmap view.", }, { text: "group by...", action: () => { this.trellis(); }, help: "Group data by a third column.", }, { text: "relative/absolute", action: () => this.toggleNormalize(), help: "In an absolute plot the Y axis represents the size for a bucket. " + "In a relative plot all bars are normalized to 100% on the Y axis.", }]); this.menu = new TopMenu( [ this.exportMenu(), { text: "View", help: "Change the way the data is displayed.", subMenu: this.viewMenu }, page.dataset!.combineMenu(this, page.pageId), ]); this.relative = false; this.stacked = true; this.page.setMenu(this.menu); if (this.samplingRate >= 1) { const submenu = this.menu.getSubmenu("View"); submenu!.enable("exact", false); } } public cdf(): Groups<number> { return this.data.second; } public histograms(): Groups<Groups<number>> { return this.data.first; } private showQuartiles(): void { const qhr = new DataRangesReceiver(this, this.page, null, this.meta, [this.xPoints], [this.xAxisData.description, this.yAxisData.description], null, this.defaultProvenance, { reusePage: false, chartKind: "QuartileVector" }); qhr.run([this.xAxisData.dataRange]); qhr.onCompleted(); } protected createNewSurfaces(keepColorMap: boolean): void { if (this.legendSurface != null) this.legendSurface.destroy(); if (this.surface != null) this.surface.destroy(); assert(this.chartDiv != null); this.legendSurface = new HtmlPlottingSurface(this.chartDiv, this.page, { height: Resolution.legendSpaceHeight }); if (keepColorMap) { this.legendPlot.setSurface(this.legendSurface); } else { this.legendPlot = new HistogramLegendPlot(this.legendSurface, (xl, xr) => this.selectionCompleted(xl, xr, true)); } this.surface = new HtmlPlottingSurface(this.chartDiv, this.page, {}); if (this.stacked) { this.plot = new Histogram2DPlot(this.surface); this.cdfPlot = new CDFPlot(this.surface); } else { this.plot = new Histogram2DBarsPlot(this.surface); } } public getAxisData(event: DragEventKind): AxisData | null { switch (event) { case "Title": case "GAxis": return null; case "XAxis": return this.xAxisData; case "YAxis": if (this.relative) return null; const missing = this.histograms().perMissing.perBucket.reduce(add); const range = { min: 0, max: this.plot.maxYAxis != null ? this.plot.maxYAxis : this.plot.max, presentCount: this.meta.rowCount - missing, missingCount: missing }; return new AxisData({ kind: "None", name: "" }, range, this.yAxisData.bucketCount); default: assertNever(event); } return null; } public updateView(data: Pair<Groups<Groups<number>>, Groups<number>>, maxYAxis: number | null, keepColorMap: boolean): void { this.viewMenu.enable("relative/absolute", this.stacked); this.createNewSurfaces(keepColorMap); if (data == null) { this.page.reportError("No data to display"); return; } this.data = data; this.xPoints = this.histograms().perBucket.length; this.yPoints = this.histograms().perBucket[0].perBucket.length; if (this.yPoints === 0) { this.page.reportError("No data to display"); return; } const bucketCount = this.xPoints; const canvas = this.surface!.getCanvas(); // Must setup legend before drawing the data to have the colormap const missingShown = this.histograms().perBucket.map(b => b.perMissing).reduce(add); if (!keepColorMap) this.legendPlot.setData(this.yAxisData, missingShown > 0); this.legendPlot.draw(); const heatmap: Pair<Groups<Groups<number>>, Groups<Groups<number>> | null> = {first: this.histograms(), second: null}; this.plot.setData(heatmap, this.xAxisData, this.samplingRate, this.relative, this.meta.schema, this.legendPlot.colorMap, maxYAxis, this.meta.rowCount); this.plot.draw(); const discrete = kindIsString(this.xAxisData.description.kind) || this.xAxisData.description.kind === "Integer"; if (this.stacked) { this.cdfPlot.setData(this.cdf().perBucket, discrete); this.cdfPlot.draw(); } this.setupMouse(); if (this.stacked) this.cdfDot = canvas .append("circle") .attr("r", Resolution.mouseDotRadius) .attr("fill", "blue"); let pointFields; if (this.stacked) { pointFields = [this.xAxisData.getName()!, this.yAxisData.getName()!, "bucket", "y", "count", "%", "cdf"]; } else { pointFields = ["bucket", this.yAxisData.getName()!, "y", "count"]; } assert(this.surface != null); assert(this.summary != null); this.pointDescription = new TextOverlay(this.surface.getChart(), this.surface.getActualChartSize(), pointFields, 40); this.pointDescription.show(false); this.standardSummary(); this.summary.set("buckets", bucketCount); this.summary.set("colors", this.yPoints); if (this.samplingRate < 1.0) this.summary.set("sampling rate", this.samplingRate); this.summary.setString("bar width", new HtmlString(this.xAxisData.barWidth())); this.addTimeSummary(); this.summary.display(); } public serialize(): IViewSerialization { // noinspection UnnecessaryLocalVariableJS const result: Histogram2DSerialization = { ...super.serialize(), samplingRate: this.samplingRate, relative: this.relative, stacked: this.stacked, columnDescription0: this.xAxisData.description, columnDescription1: this.yAxisData.description, xBucketCount: this.xPoints, yBucketCount: this.yPoints, xRange: this.xAxisData.dataRange, yRange: this.yAxisData.dataRange }; return result; } public static reconstruct(ser: Histogram2DSerialization, page: FullPage): IDataView | null { const samplingRate: number = ser.samplingRate; const cd0: IColumnDescription = ser.columnDescription0; const cd1: IColumnDescription = ser.columnDescription1; const xPoints: number = ser.xBucketCount; const yPoints: number = ser.yBucketCount; const args = this.validateSerialization(ser); if (args == null || cd0 == null || cd1 == null || samplingRate == null || xPoints == null || yPoints == null || ser.xRange == null || ser.yRange == null || ser.stacked == null) return null; const hv = new Histogram2DView(ser.remoteObjectId, args, samplingRate, page); hv.setAxes(new AxisData(cd0, ser.xRange, ser.xBucketCount), new AxisData(cd1, ser.yRange, ser.yBucketCount), ser.relative, ser.stacked); hv.xPoints = xPoints; hv.yPoints = yPoints; return hv; } public setAxes(xAxisData: AxisData, yAxisData: AxisData, relative: boolean, stacked: boolean): void { this.relative = relative; this.stacked = stacked; this.xAxisData = xAxisData; this.yAxisData = yAxisData; this.viewMenu.enable("quartiles", kindIsNumeric(this.yAxisData.description.kind)); this.viewMenu.enable("stacked/parallel", kindIsString(this.yAxisData.description.kind) || this.yAxisData.description.kind === "Integer" ) } public trellis(): void { const columns: string[] = this.getSchema().namesExcluding( [this.xAxisData.description.name, this.yAxisData.description.name]); this.chooseTrellis(columns); } protected showTrellis(colName: string): void { const groupBy = this.getSchema().find(colName)!; const cds: IColumnDescription[] = [ this.xAxisData.description, this.yAxisData.description, groupBy]; const rr = this.createDataQuantilesRequest(cds, this.page, "Trellis2DHistogram"); rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta, [0, 0, 0], cds, null, this.defaultProvenance,{ reusePage: false, relative: this.relative, chartKind: "Trellis2DHistogram", exact: this.samplingRate >= 1.0 })); } protected toggleStacked(): void { if (this.stacked) { // Let's see if we have enough room const bars = this.xPoints * (this.yAxisData.bucketCount + 1); // 1 for missing data if (bars * 3 > this.plot.getChartWidth()) { this.page.reportError("Not enough space to plot " + bars + " bars; " + " consider changing the number of buckets"); return; } } this.stacked = !this.stacked; this.resize(); } protected toggleNormalize(): void { this.relative = !this.relative; if (this.relative && this.samplingRate < 1) { // We cannot use sampling when we display relative views. this.exactHistogram(); } else { this.refresh(); } } public doHeatmap(): void { const cds = [this.xAxisData.description, this.yAxisData.description]; const rr = this.createDataQuantilesRequest(cds, this.page, "Heatmap"); rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta, [0, 0], cds, null, this.defaultProvenance, { reusePage: false, chartKind: "Heatmap", exact: true })); } public export(): void { const lines: string[] = Exporter.histogram2DAsCsv(this.histograms(), this.getSchema(), [this.xAxisData, this.yAxisData]); const fileName = "histogram2d.csv"; saveAs(fileName, lines.join("\n")); } protected getCombineRenderer(title: PageTitle): (page: FullPage, operation: ICancellable<RemoteObjectId>) => BaseReceiver { return (page: FullPage, operation: ICancellable<RemoteObjectId>) => { return new NewTargetReceiver(title, [this.xAxisData.description, this.yAxisData.description], this.meta, [0, 0], page, operation, this.dataset, { exact: this.samplingRate >= 1, chartKind: "2DHistogram", relative: this.relative, reusePage: false, stacked: this.stacked }); }; } public swapAxes(): void { if (this == null) return; const cds = [this.yAxisData.description, this.xAxisData.description]; const rr = this.createDataQuantilesRequest(cds, this.page, "2DHistogram"); rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta, [0, 0], cds, null, "swapped axes", { reusePage: true, relative: this.relative, chartKind: "2DHistogram", exact: this.samplingRate >= 1.0, stacked: this.stacked })); } public exactHistogram(): void { if (this == null) return; const cds = [this.xAxisData.description, this.yAxisData.description]; const rr = this.createDataQuantilesRequest(cds, this.page, "2DHistogram"); rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta, [this.xPoints, this.yPoints], cds, this.page.title, "requested exact computation", { reusePage: true, relative: this.relative, chartKind: "2DHistogram", exact: true, stacked: this.stacked })); } public changeBuckets(xBuckets: number | null, yBuckets: number | null): void { if (xBuckets == null || yBuckets == null) return; const cds = [this.xAxisData.description, this.yAxisData.description]; const rr = this.createDataQuantilesRequest(cds, this.page, "2DHistogram"); rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta, [xBuckets, yBuckets], cds, null, "changed buckets", { reusePage: true, relative: this.relative, chartKind: "2DHistogram", exact: true, stacked: this.stacked })); } protected replaceAxis(pageId: string, eventKind: DragEventKind): void { if (this.data == null) return; const sourceRange = this.getSourceAxisRange(pageId, eventKind); if (sourceRange == null) return; if (eventKind === "XAxis") { const receiver = new DataRangesReceiver(this, this.page, null, this.meta, [0, 0], // any number of buckets [this.xAxisData.description, this.yAxisData.description], this.page.title, Converters.eventToString(pageId, eventKind), { chartKind: "2DHistogram", exact: this.samplingRate >= 1, relative: this.relative, reusePage: true, stacked: this.stacked }); receiver.run([sourceRange, this.yAxisData.dataRange]); receiver.finished(); } else if (eventKind === "YAxis") { this.relative = false; // We cannot drag a relative Y axis. this.updateView(this.data, sourceRange.max!, true); } } public chooseBuckets(): void { if (this == null) return; const dialog = new Dialog("Set buckets", "Change the number of buckets."); let input = dialog.addTextField( "x_buckets", "Number of X buckets:", FieldKind.Integer, this.xPoints.toString(), "Buckets on " + this.xAxisData.description.name); input.min = "1"; input.max = Resolution.maxBuckets(this.page.getWidthInPixels()).toString(); input.value = this.xPoints.toString(); input.required = true; input = dialog.addTextField( "y_buckets", "Number of Y buckets:", FieldKind.Integer, this.yPoints.toString(), "Buckets on " + this.yAxisData.description.name); input.min = "1"; input.max = Resolution.max2DBucketCount.toString(); input.value = this.yPoints.toString(); input.required = true; dialog.setAction(() => this.changeBuckets( dialog.getFieldValueAsInt("x_buckets"), dialog.getFieldValueAsInt("y_buckets"))); dialog.show(); } public resize(): void { if (this.data == null) return; this.updateView(this.data, this.plot.maxYAxis, true); } public refresh(): void { const cds = [this.xAxisData.description, this.yAxisData.description]; const ranges = [this.xAxisData.dataRange, this.yAxisData.dataRange]; const receiver = new DataRangesReceiver(this, this.page, null, this.meta, [this.xAxisData.bucketCount, this.yAxisData.bucketCount], cds, this.page.title, null,{ chartKind: "2DHistogram", exact: this.samplingRate >= 1, relative: this.relative, reusePage: true, stacked: this.stacked }); receiver.run(ranges); receiver.finished(); } public onMouseEnter(): void { super.onMouseEnter(); if (this.stacked) this.cdfDot.attr("visibility", "visible"); } public onMouseLeave(): void { if (this.stacked) this.cdfDot.attr("visibility", "hidden"); super.onMouseLeave(); } /** * Handles mouse movements in the canvas area only. */ public onMouseMove(): void { assert(this.surface != null); const position = d3mouse(this.surface.getChart().node()); // note: this position is within the chart const mouseX = position[0]; const mouseY = position[1]; const xs = this.xAxisData.invert(position[0]); // Use the plot scale, not the yData to invert. That's the // one which is used to draw the axis. const y = this.plot.getYScale().invert(mouseY); let ys = significantDigits(y); if (this.relative) ys += "%"; let count = ""; let colorIndex = null; let bucket = ""; let value = ""; let pointInfo; if (this.stacked) { let box = null; if (mouseY >= 0 && mouseY < this.surface.getChartHeight()) box = (this.plot as Histogram2DPlot).getBoxInfo(mouseX, y); let perc = 0; if (box != null) { count = significantDigits(box.count); colorIndex = box.yIndex; value = this.yAxisData.bucketDescription(colorIndex, 20); perc = (box.count === 0) ? 0 : box.count / box.countBelow; bucket = this.xAxisData.bucketDescription(box.xIndex, 20); } const pos = this.cdfPlot.getY(mouseX); this.cdfDot.attr("cx", mouseX + this.surface.leftMargin); this.cdfDot.attr("cy", (1 - pos) * this.surface.getChartHeight() + this.surface.topMargin); const cdf = percentString(pos); pointInfo = [xs, value, bucket, ys, count, percentString(perc), cdf]; } else { let barInfo = null; if (mouseY >= 0 && mouseY < this.surface.getChartHeight()) barInfo = (this.plot as Histogram2DBarsPlot).getBarInfo(mouseX, y); if (barInfo != null) { if (barInfo.count != null) // This is null in the space between buckets. count = significantDigits(barInfo.count); colorIndex = barInfo.colorIndex; value = this.yAxisData.bucketDescription(colorIndex, 20); bucket = this.xAxisData.bucketDescription(barInfo.bucketIndex, 20); } pointInfo = [bucket, value, ys, count]; } this.pointDescription!.update(pointInfo, mouseX, mouseY); this.legendPlot.showBorder(colorIndex); } // Round x to align a bucket boundary. x is a coordinate within the canvas. private bucketIndex(x: number): number { const bucketWidth = this.plot.getChartWidth() / this.xPoints; const index = Math.floor((x - this.surface!.leftMargin) / bucketWidth); if (index < 0) return 0; if (index >= this.xPoints) return this.xPoints - 1; return index; } // Returns bucket left margin in canvas. private bucketLeftMargin(index: number): number { const bucketWidth = this.plot.getChartWidth() / this.xPoints; return index * bucketWidth + this.surface!.leftMargin; } protected dragMove(): boolean { if (!super.dragMove() || this.selectionOrigin == null) return false; if (this.stacked) return true; // Mark all buckets that are selected const position = d3mouse(this.surface!.getCanvas().node()); const x = position[0]; const start = this.bucketIndex(this.selectionOrigin.x); const end = this.bucketIndex(x); const order = reorder(start, end); const left = this.bucketLeftMargin(order[0]); const right = this.bucketLeftMargin(order[1] + 1); this.selectionRectangle .attr("x", left) .attr("width", right - left); return true; } protected dragEnd(): boolean { if (!super.dragEnd() || this.selectionOrigin == null) return false; const position = d3mouse(this.surface!.getCanvas().node()); let x = position[0]; if (this.stacked) { this.selectionCompleted(this.selectionOrigin.x, x, false); } else { const start = this.bucketIndex(this.selectionOrigin.x); const end = this.bucketIndex(x); const order = reorder(start, end); const left = this.bucketLeftMargin(order[0]); const right = this.bucketLeftMargin(order[1] + 1); this.selectionCompleted(left, right, false); } return true; } /** * * xl and xr are coordinates of the mouse position within the * canvas or legend rectangle respectively. */ protected selectionCompleted(xl: number, xr: number, inLegend: boolean): void { const shiftPressed = d3event.sourceEvent.shiftKey; let selectedAxis: AxisData; assert(this.surface != null); if (inLegend) { selectedAxis = this.yAxisData; } else { xl -= this.surface.leftMargin; xr -= this.surface.leftMargin; selectedAxis = this.xAxisData; } if (inLegend && shiftPressed) { let min = this.yPoints * xl / this.legendPlot.width; let max = this.yPoints * xr / this.legendPlot.width; [min, max] = reorder(min, max); min = Math.max(0, Math.floor(min)); max = Math.min(this.yPoints, Math.ceil(max)); this.legendPlot.emphasizeRange(min, max); const heatmap = Heatmap.create(this.data.first); const filter = heatmap.bucketsInRange(min, max); const count = filter.sum(); assert(this.summary != null); this.summary.set("colors selected", max - min); this.summary.set("points selected", count); this.summary.display(); this.resize(); return; } const filter = selectedAxis.getFilter(xl, xr); const fa: RangeFilterArrayDescription = { filters: [filter], complement: d3event.sourceEvent.ctrlKey } const rr = this.createFilterRequest(fa); const renderer = new NewTargetReceiver( new PageTitle(this.page.title.format, Converters.filterArrayDescription(fa)), [this.xAxisData.description, this.yAxisData.description], this.meta, [inLegend ? this.xPoints : 0, this.yPoints], this.page, rr, this.dataset, { exact: this.samplingRate >= 1.0, chartKind: "2DHistogram", reusePage: false, relative: this.relative, stacked: this.stacked }); rr.invoke(renderer); } } /** * Receives partial results and renders a 2D histogram. * The 2D histogram data and the Heatmap data use the same data structure. */ export class Histogram2DReceiver extends Receiver<Pair<Groups<Groups<number>>, Groups<number>>> { protected view: Histogram2DView; constructor(title: PageTitle, page: FullPage, protected remoteObject: TableTargetAPI, protected meta: TableMeta, protected axes: AxisData[], protected samplingRate: number, operation: RpcRequest<Pair<Groups<Groups<number>>, Groups<number>>>, protected options: ChartOptions) { super(options.reusePage ? page : page.dataset!.newPage(title, page), operation, "histogram"); this.view = new Histogram2DView( this.remoteObject.getRemoteObjectId()!, meta, samplingRate, this.page); this.view.setAxes(axes[0], axes[1], optionToBoolean(options.relative), optionToBoolean(options.stacked)); } public onNext(value: PartialResult<Pair<Groups<Groups<number>>, Groups<number>>>): void { super.onNext(value); if (value == null) return; this.view.updateView(value.data, null, false); } public onCompleted(): void { super.onCompleted(); this.view.updateCompleted(this.elapsedMilliseconds()); } }
the_stack
export namespace MindConnectApiModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError"; constructor(public field: string, msg?: string) { super(msg); this.name = "RequiredError"; } } /** * * @export * @interface Ingestion */ export interface Ingestion { /** * Timeseries data for each timestamp * @type {Array<IngestionTimeseries>} * @memberof Ingestion */ timeseries?: Array<IngestionTimeseries>; } /** * * @export * @interface IngestionTimeseries */ export interface IngestionTimeseries { /** * Timestamp of the data point * @type {string} * @memberof IngestionTimeseries */ timestamp: string; /** * List of datapoint(s) * @type {Array<IngestionValues>} * @memberof IngestionTimeseries */ values: Array<IngestionValues>; } /** * * @export * @interface IngestionValues */ export interface IngestionValues { /** * Unique identifier of the data point * @type {string} * @memberof IngestionValues */ dataPointId: string; /** * Timeseries data value for a given data point id * @type {string} * @memberof IngestionValues */ value: string; /** * Data Quality Code * @type {string} * @memberof IngestionValues */ qualityCode: string; } /** * * @export * @interface Badrequest */ export interface Badrequest { /** * * @type {string} * @memberof Badrequest */ id?: string; /** * * @type {string} * @memberof Badrequest */ message?: string; } /** * * @export * @interface Conflict */ export interface Conflict { /** * * @type {string} * @memberof Conflict */ id?: string; /** * * @type {string} * @memberof Conflict */ message?: string; } /** * * @export * @interface DiagnosticActivation */ export interface DiagnosticActivation { /** * Unique identifier of diagnostic activation resource * @type {string} * @memberof DiagnosticActivation */ id?: string; /** * Unique identifier of the agent * @type {string} * @memberof DiagnosticActivation */ agentId: string; /** * Status of the activation * @type {string} * @memberof DiagnosticActivation */ status?: DiagnosticActivation.StatusEnum; } /** * @export * @namespace DiagnosticActivation */ export namespace DiagnosticActivation { /** * @export * @enum {string} */ export enum StatusEnum { ACTIVE = <any>"ACTIVE", INACTIVE = <any>"INACTIVE", } } /** * * @export * @interface DiagnosticActivationStatus */ export interface DiagnosticActivationStatus { /** * Status of the activation * @type {string} * @memberof DiagnosticActivationStatus */ status?: DiagnosticActivationStatus.StatusEnum; } /** * @export * @namespace DiagnosticActivationStatus */ export namespace DiagnosticActivationStatus { /** * @export * @enum {string} */ export enum StatusEnum { ACTIVE = <any>"ACTIVE", INACTIVE = <any>"INACTIVE", } } /** * * @export * @interface DiagnosticInformation */ export interface DiagnosticInformation { /** * * @type {string} * @memberof DiagnosticInformation */ agentId?: string; /** * * @type {string} * @memberof DiagnosticInformation */ correlationId?: string; /** * * @type {string} * @memberof DiagnosticInformation */ severity?: DiagnosticInformation.SeverityEnum; /** * * @type {string} * @memberof DiagnosticInformation */ message?: string; /** * Source of diagnostic information. * @type {string} * @memberof DiagnosticInformation */ source?: string; /** * State of diagnostic information. * @type {string} * @memberof DiagnosticInformation */ state?: DiagnosticInformation.StateEnum; /** * Diagnostic information creation date. * @type {Date} * @memberof DiagnosticInformation */ timestamp?: Date; } /** * @export * @namespace DiagnosticInformation */ export namespace DiagnosticInformation { /** * @export * @enum {string} */ export enum SeverityEnum { INFO = <any>"INFO", WARN = <any>"WARN", ERROR = <any>"ERROR", } /** * @export * @enum {string} */ export enum StateEnum { ACCEPTED = <any>"ACCEPTED", RETRYING = <any>"RETRYING", DROPPED = <any>"DROPPED", PROCESSING = <any>"PROCESSING", FINISHED = <any>"FINISHED", } } /** * * @export * @interface DiagnosticInformationMessage */ export interface DiagnosticInformationMessage { /** * * @type {string} * @memberof DiagnosticInformationMessage */ correlationId?: string; /** * * @type {string} * @memberof DiagnosticInformationMessage */ severity?: DiagnosticInformationMessage.SeverityEnum; /** * * @type {string} * @memberof DiagnosticInformationMessage */ message?: string; /** * Source of diagnostic information. * @type {string} * @memberof DiagnosticInformationMessage */ source?: string; /** * State of diagnostic information. * @type {string} * @memberof DiagnosticInformationMessage */ state?: DiagnosticInformationMessage.StateEnum; /** * Diagnostic information creation date. * @type {Date} * @memberof DiagnosticInformationMessage */ timestamp?: Date; } /** * @export * @namespace DiagnosticInformationMessage */ export namespace DiagnosticInformationMessage { /** * @export * @enum {string} */ export enum SeverityEnum { INFO = <any>"INFO", WARN = <any>"WARN", ERROR = <any>"ERROR", } /** * @export * @enum {string} */ export enum StateEnum { ACCEPTED = <any>"ACCEPTED", RETRYING = <any>"RETRYING", DROPPED = <any>"DROPPED", PROCESSING = <any>"PROCESSING", FINISHED = <any>"FINISHED", } } /** * * @export * @interface Error */ export interface Error { /** * * @type {string} * @memberof Error */ id?: string; /** * * @type {string} * @memberof Error */ message?: string; } /** * * @export * @interface Forbidden */ export interface Forbidden { /** * * @type {string} * @memberof Forbidden */ id?: string; /** * * @type {string} * @memberof Forbidden */ message?: string; } /** * * @export * @interface Mapping */ export interface Mapping { /** * Unique identifier of the mapping resource * @type {string} * @memberof Mapping */ id?: string; /** * Unique identifier of the agent * @type {string} * @memberof Mapping */ agentId: string; /** * Unique identifier of the data point * @type {string} * @memberof Mapping */ dataPointId: string; /** * Unit of the data point * @type {string} * @memberof Mapping */ dataPointUnit?: string; /** * Type of the data point * @type {string} * @memberof Mapping */ dataPointType?: Mapping.DataPointTypeEnum; /** * Unique identifier of the entity * @type {string} * @memberof Mapping */ entityId: string; /** * * @type {string} * @memberof Mapping */ propertySetName: string; /** * * @type {string} * @memberof Mapping */ propertyName: string; /** * * @type {string} * @memberof Mapping */ propertyUnit?: string; /** * * @type {string} * @memberof Mapping */ propertyType?: Mapping.PropertyTypeEnum; /** * * @type {boolean} * @memberof Mapping */ qualityEnabled?: boolean; /** * Identifies auto deleting mapping or keeping mapping. * @type {boolean} * @memberof Mapping */ keepMapping?: boolean; /** * * @type {any} * @memberof Mapping */ validity?: any; } /** * @export * @namespace Mapping */ export namespace Mapping { /** * @export * @enum {string} */ export enum DataPointTypeEnum { INT = <any>"INT", LONG = <any>"LONG", DOUBLE = <any>"DOUBLE", BOOLEAN = <any>"BOOLEAN", STRING = <any>"STRING", BIGSTRING = <any>"BIG_STRING", TIMESTAMP = <any>"TIMESTAMP", } /** * @export * @enum {string} */ export enum PropertyTypeEnum { INT = <any>"INT", LONG = <any>"LONG", DOUBLE = <any>"DOUBLE", BOOLEAN = <any>"BOOLEAN", STRING = <any>"STRING", BIGSTRING = <any>"BIG_STRING", TIMESTAMP = <any>"TIMESTAMP", } } /** * * @export * @interface Notfound */ export interface Notfound { /** * * @type {string} * @memberof Notfound */ id?: string; /** * * @type {string} * @memberof Notfound */ message?: string; } /** * * @export * @interface Order */ export interface Order { /** * The order the property shall be sorted for. * @type {string} * @memberof Order */ direction?: Order.DirectionEnum; /** * The property to order for. * @type {string} * @memberof Order */ property?: string; /** * Whether or not the sort will be case sensitive. * @type {boolean} * @memberof Order */ ignoreCase?: boolean; /** * * @type {string} * @memberof Order */ nullHandling?: Order.NullHandlingEnum; /** * Whether sorting for this property shall be descending. * @type {boolean} * @memberof Order */ descending?: boolean; /** * Whether sorting for this property shall be ascending. * @type {boolean} * @memberof Order */ ascending?: boolean; } /** * @export * @namespace Order */ export namespace Order { /** * @export * @enum {string} */ export enum DirectionEnum { ASC = <any>"ASC", DESC = <any>"DESC", } /** * @export * @enum {string} */ export enum NullHandlingEnum { NATIVE = <any>"NATIVE", NULLSFIRST = <any>"NULLS_FIRST", NULLSLAST = <any>"NULLS_LAST", } } /** * * @export * @interface PagedDiagnosticActivation */ export interface PagedDiagnosticActivation { /** * * @type {Array<DiagnosticActivation>} * @memberof PagedDiagnosticActivation */ content: Array<DiagnosticActivation>; /** * Whether the current item is the last one. * @type {boolean} * @memberof PagedDiagnosticActivation */ last: boolean; /** * The number of total pages. * @type {number} * @memberof PagedDiagnosticActivation */ totalPages: number; /** * The total amount of elements. * @type {number} * @memberof PagedDiagnosticActivation */ totalElements: number; /** * The number of elements currently on this page. * @type {number} * @memberof PagedDiagnosticActivation */ numberOfElements: number; /** * Whether the current item is the first one. * @type {boolean} * @memberof PagedDiagnosticActivation */ first: boolean; /** * The sorting parameters for the page. * @type {Array<Order>} * @memberof PagedDiagnosticActivation */ sort: Array<Order>; /** * The size of the page. * @type {number} * @memberof PagedDiagnosticActivation */ size: number; /** * The number of the current item. * @type {number} * @memberof PagedDiagnosticActivation */ number: number; } /** * * @export * @interface PagedDiagnosticInformation */ export interface PagedDiagnosticInformation { /** * * @type {Array<DiagnosticInformation>} * @memberof PagedDiagnosticInformation */ content: Array<DiagnosticInformation>; /** * Whether the current item is the last one. * @type {boolean} * @memberof PagedDiagnosticInformation */ last: boolean; /** * The number of total pages. * @type {number} * @memberof PagedDiagnosticInformation */ totalPages: number; /** * The total amount of elements. * @type {number} * @memberof PagedDiagnosticInformation */ totalElements: number; /** * The number of elements currently on this page. * @type {number} * @memberof PagedDiagnosticInformation */ numberOfElements: number; /** * Whether the current item is the first one. * @type {boolean} * @memberof PagedDiagnosticInformation */ first: boolean; /** * The sorting parameters for the page. * @type {Array<Order>} * @memberof PagedDiagnosticInformation */ sort: Array<Order>; /** * The size of the page. * @type {number} * @memberof PagedDiagnosticInformation */ size: number; /** * The number of the current item. * @type {number} * @memberof PagedDiagnosticInformation */ number: number; } /** * * @export * @interface PagedDiagnosticInformationMessages */ export interface PagedDiagnosticInformationMessages { /** * * @type {Array<DiagnosticInformationMessage>} * @memberof PagedDiagnosticInformationMessages */ content: Array<DiagnosticInformationMessage>; /** * Whether the current item is the last one. * @type {boolean} * @memberof PagedDiagnosticInformationMessages */ last: boolean; /** * The number of total pages. * @type {number} * @memberof PagedDiagnosticInformationMessages */ totalPages: number; /** * The total amount of elements. * @type {number} * @memberof PagedDiagnosticInformationMessages */ totalElements: number; /** * The number of elements currently on this page. * @type {number} * @memberof PagedDiagnosticInformationMessages */ numberOfElements: number; /** * Whether the current item is the first one. * @type {boolean} * @memberof PagedDiagnosticInformationMessages */ first: boolean; /** * The sorting parameters for the page. * @type {Array<Order>} * @memberof PagedDiagnosticInformationMessages */ sort: Array<Order>; /** * The size of the page. * @type {number} * @memberof PagedDiagnosticInformationMessages */ size: number; /** * The number of the current item. * @type {number} * @memberof PagedDiagnosticInformationMessages */ number: number; } /** * * @export * @interface PagedMapping */ export interface PagedMapping { /** * * @type {Array<Mapping>} * @memberof PagedMapping */ content: Array<Mapping>; /** * Whether the current item is the last one. * @type {boolean} * @memberof PagedMapping */ last: boolean; /** * The number of total pages. * @type {number} * @memberof PagedMapping */ totalPages: number; /** * The total amount of elements. * @type {number} * @memberof PagedMapping */ totalElements: number; /** * The number of elements currently on this page. * @type {number} * @memberof PagedMapping */ numberOfElements: number; /** * Whether the current item is the first one. * @type {boolean} * @memberof PagedMapping */ first: boolean; /** * The sorting parameters for the page. * @type {Array<Order>} * @memberof PagedMapping */ sort: Array<Order>; /** * The size of the page. * @type {number} * @memberof PagedMapping */ size: number; /** * The number of the current item. * @type {number} * @memberof PagedMapping */ number: number; } /** * * @export * @interface PagedRecoverableRecords */ export interface PagedRecoverableRecords { /** * * @type {Array<RecoverableRecords>} * @memberof PagedRecoverableRecords */ content: Array<RecoverableRecords>; /** * Whether the current item is the last one. * @type {boolean} * @memberof PagedRecoverableRecords */ last: boolean; /** * The number of total pages. * @type {number} * @memberof PagedRecoverableRecords */ totalPages: number; /** * The total amount of elements. * @type {number} * @memberof PagedRecoverableRecords */ totalElements: number; /** * The number of elements currently on this page. * @type {number} * @memberof PagedRecoverableRecords */ numberOfElements: number; /** * Whether the current item is the first one. * @type {boolean} * @memberof PagedRecoverableRecords */ first: boolean; /** * The sorting parameters for the page. * @type {Array<Order>} * @memberof PagedRecoverableRecords */ sort: Array<Order>; /** * The size of the page. * @type {number} * @memberof PagedRecoverableRecords */ size: number; /** * The number of the current item. * @type {number} * @memberof PagedRecoverableRecords */ number: number; } /** * * @export * @interface PayLoadTooLarge */ export interface PayLoadTooLarge { /** * * @type {string} * @memberof PayLoadTooLarge */ id?: string; /** * * @type {string} * @memberof PayLoadTooLarge */ message?: string; } /** * * @export * @interface RecoverableRecords */ export interface RecoverableRecords { /** * Unique identifier of the record * @type {string} * @memberof RecoverableRecords */ id?: string; /** * Unique identifier of the record * @type {string} * @memberof RecoverableRecords */ correlationId?: string; /** * agentId * @type {string} * @memberof RecoverableRecords */ agentId?: string; /** * Ingestion date of the data. * @type {Date} * @memberof RecoverableRecords */ requestTime?: Date; /** * Drop reason of data * @type {string} * @memberof RecoverableRecords */ dropReason?: string; } /** * * @export * @interface Unauthorized */ export interface Unauthorized { /** * * @type {string} * @memberof Unauthorized */ id?: string; /** * * @type {string} * @memberof Unauthorized */ message?: string; } /** * * @export * @interface Validity */ export interface Validity { /** * * @type {string} * @memberof Validity */ status: Validity.StatusEnum; /** * * @type {Array<string>} * @memberof Validity */ reasons: Array<Validity.ReasonsEnum>; } /** * @export * @namespace Validity */ export namespace Validity { /** * @export * @enum {string} */ export enum StatusEnum { VALID = <any>"VALID", INVALID = <any>"INVALID", } /** * @export * @enum {string} */ export enum ReasonsEnum { MISSINGDATAPOINT = <any>"MISSING_DATAPOINT", MISSINGPROPERTY = <any>"MISSING_PROPERTY", INVALIDTYPE = <any>"INVALID_TYPE", INVALIDUNIT = <any>"INVALID_UNIT", } } }
the_stack
import { appendStmt, applyBind, applyConstructor, applyFunction, applyPredicate, applyTypeDecl, ArgExpr, argMatches, ArgStmtDecl, autoLabelStmt, cascadingDelete, domainToSubType, matchSignatures, nullaryTypeCons, } from "analysis/SubstanceAnalysis"; import { prettyStmt, prettySubstance } from "compiler/Substance"; import consola, { LogLevel } from "consola"; import { dummyIdentifier } from "engine/EngineUtils"; import { Map } from "immutable"; import { cloneDeep, compact, range, times, without } from "lodash"; import { createChoice } from "pandemonium/choice"; import { createRandom } from "pandemonium/random"; import seedrandom from "seedrandom"; import { Add, addMutation, appendStmtCtx, checkAddStmt, checkAddStmts, checkChangeExprType, checkChangeStmtType, checkDeleteStmt, checkReplaceExprName, checkSwapExprArgs, checkSwapStmtArgs, Delete, deleteMutation, executeMutations, Mutation, MutationGroup, removeStmtCtx, showMutations, } from "synthesis/Mutation"; import { Identifier } from "types/ast"; import { Arg, ConstructorDecl, DomainStmt, Env, FunctionDecl, PredicateDecl, Type, TypeConstructor, TypeDecl, } from "types/domain"; import { ApplyConstructor, ApplyFunction, ApplyPredicate, Bind, Decl, SubExpr, SubPredArg, SubProg, SubRes, SubStmt, TypeConsApp, } from "types/substance"; import { checkReplaceStmtName } from "./Mutation"; type RandomFunction = (min: number, max: number) => number; const log = consola .create({ level: LogLevel.Info }) .withScope("Substance Synthesizer"); //#region Synthesizer setting types type All = "*"; type ArgOption = "existing" | "generated" | "mixed"; type ArgReuse = "distinct" | "repeated"; type MatchSetting = string[] | All; export interface DeclTypes { type: MatchSetting; predicate: MatchSetting; constructor: MatchSetting; function: MatchSetting; } export interface SynthesizerSetting { mutationCount: [number, number]; argOption: ArgOption; argReuse: ArgReuse; weights: { type: number; predicate: number; constructor: number; }; add: DeclTypes; delete: DeclTypes; edit: DeclTypes; } //#endregion //#region Synthesis context export interface SynthesisContext { names: Map<string, number>; declaredIDs: Map<string, Identifier[]>; env: Env; } export interface SynthesizedSubstance { prog: SubProg; ops: Mutation[]; } interface IDList { ids: Identifier[]; } export const initContext = (env: Env): SynthesisContext => { const ctx: SynthesisContext = { names: Map<string, number>(), declaredIDs: Map<string, Identifier[]>(), env, }; return env.varIDs.reduce((c, id) => { const type = env.vars.get(id.value); // TODO: enforce the existence of var types return addID(c, type!.name.value, id); }, ctx); }; const filterContext = ( ctx: SynthesisContext, setting: DeclTypes ): SynthesisContext => { return { ...ctx, env: { ...ctx.env, types: filterBySetting(ctx.env.types, setting.type), functions: filterBySetting(ctx.env.functions, setting.function), predicates: filterBySetting(ctx.env.predicates, setting.predicate), constructors: filterBySetting(ctx.env.constructors, setting.constructor), }, }; }; const showEnv = (env: Env): string => [ `types: ${[...env.types.keys()]}`, `predicates: ${[...env.predicates.keys()]}`, `functions: ${[...env.functions.keys()]}`, `constructors: ${[...env.constructors.keys()]}`, ].join("\n"); const getDecls = ( ctx: SynthesisContext, type: DomainStmt["tag"] ): Map<string, DomainStmt> => { const { env } = ctx; switch (type) { case "TypeDecl": return env.types; case "ConstructorDecl": return env.constructors; case "FunctionDecl": return env.functions; case "PredicateDecl": return env.predicates; case undefined: return Map<string, DomainStmt>(); } throw new Error(`${type} is not found in the environment`); }; const nonEmptyDecls = (ctx: SynthesisContext): DomainStmt["tag"][] => declTypes.filter((type) => !getDecls(ctx, type).isEmpty()); /** * Add a newly declared ID. * * NOTE: this should be called whenever we add a `Decl` * statement from list of statements to keep them in sync. * @param typeStr the type associated with the ID * @param id the identifier that is being removed */ export const addID = ( ctx: SynthesisContext, typeStr: string, id: Identifier ): SynthesisContext => { const ids = ctx.declaredIDs.get(typeStr); if (ids) { return { ...ctx, declaredIDs: ctx.declaredIDs.set(typeStr, [...ids, id]), }; } else { return { ...ctx, declaredIDs: ctx.declaredIDs.set(typeStr, [id]), }; } }; /** * Remove a declared ID. * * NOTE: this should be called whenever we delete a `Decl` * statement from list of statements to keep them in sync. * @param typeStr the type associated with the ID * @param id the identifier that is being removed */ export const removeID = ( ctx: SynthesisContext, typeStr: string, id: Identifier ): SynthesisContext => { const ids = ctx.declaredIDs.get(typeStr); if (ids) { // keep all IDs that aren't id const newIDs = ids.filter((otherID) => otherID.value !== id.value); return { ...ctx, declaredIDs: ctx.declaredIDs.set(typeStr, newIDs), }; } else { log.warn(`Could not find any IDs for ${typeStr} ${id.value}`); return ctx; } }; const findIDs = ( ctx: SynthesisContext, typeStr: string, excludeList?: Identifier[] ): Identifier[] => { const possibleIDs = ctx.declaredIDs.get(typeStr); if (possibleIDs) { const candidates = possibleIDs.filter((id) => excludeList ? !excludeList.includes(id) : true ); return candidates; } else return []; }; const autoLabel = (prog: SubProg): SubProg => appendStmt(prog, autoLabelStmt); //#endregion //#region Main synthesizer interface WithStmts<T> { res: T; stmts: SubStmt[]; } export interface WithContext<T> { res: T; ctx: SynthesisContext; } export class Synthesizer { env: Env; template: SubProg; setting: SynthesizerSetting; names: Map<string, number>; currentProg: SubProg; currentMutations: Mutation[]; private choice: <T>(array: Array<T>) => T; private random: RandomFunction; constructor( env: Env, setting: SynthesizerSetting, subRes?: SubRes, seed = "synthesizerSeed" ) { // If there is a template substance program, load in the relevant info if (subRes) { const [subEnv, env] = subRes; this.env = env; this.template = cloneDeep(subEnv.ast); log.debug(`Loaded template:\n${prettySubstance(this.template)}`); } else { this.env = env; this.template = { tag: "SubProg", statements: [], children: [], nodeType: "SyntheticSubstance", }; } // initialize the current program as the template this.currentProg = cloneDeep(this.template); this.setting = setting; this.currentMutations = []; // use the seed to create random generation functions const rng = seedrandom(seed); this.choice = createChoice(rng); this.random = createRandom(rng); // keep track of all generated names this.names = Map<string, number>(); } generateID = ( ctx: SynthesisContext, typeName: Identifier ): WithContext<Identifier> => { const typeStr = typeName.value; const prefix = typeStr[0].toLowerCase(); // find the appropriate index for the generated ID let index; const lastIndex = this.names.get(prefix); if (lastIndex !== undefined) { this.names = this.names.set(prefix, lastIndex + 1); index = lastIndex + 1; } else { this.names = this.names.set(prefix, 0); index = 0; } const id: Identifier = dummyIdentifier( `${prefix}${index}`, "SyntheticSubstance" ); // return both the ID and the context with ID added return { res: id, ctx: addID(ctx, typeStr, id), }; }; reset = (): void => { this.currentProg = cloneDeep(this.template); this.names = Map<string, number>(); this.currentMutations = []; }; showMutations = (): string => showMutations(this.currentMutations); updateProg = (prog: SubProg): void => { this.currentProg = prog; }; getTemplate = (): SubProg | undefined => this.template ? appendStmt(this.template, autoLabelStmt) : undefined; /** * Top-level function for generating multiple Substance programs. * @param numProgs number of Substance programs to generate * @returns an array of Substance programs and some metadata (e.g. mutation operation record) */ generateSubstances = (numProgs: number): SynthesizedSubstance[] => times(numProgs, (n: number) => { const sub = this.generateSubstance(); // DEBUG: report results log.info( `Synthesized program #${n}\n${prettySubstance(this.currentProg)}` ); log.info("Operations:\n", this.showMutations()); log.info("----------"); // reset synthesizer after generating each Substance diagram this.reset(); return sub; }); generateSubstance = (): SynthesizedSubstance => { const numStmts = this.random(...this.setting.mutationCount); range(numStmts).reduce( (ctx: SynthesisContext, n: number): SynthesisContext => { const newCtx = this.mutateProgram(ctx); log.debug( `Mutation #${n} done. The program so far:\n${prettySubstance( this.currentProg )}` ); return newCtx; }, initContext(this.env) ); // add autolabel statement this.updateProg(autoLabel(this.currentProg)); return { prog: this.currentProg, ops: this.currentMutations, }; }; /** * Find a list of possible mutations for the current Substance program stored in the context, and execute one of the mutations. */ mutateProgram = (ctx: SynthesisContext): SynthesisContext => { const addCtx = filterContext(ctx, this.setting.add); const addOps = this.enumerateAdd(addCtx); const deleteCtx = filterContext(ctx, this.setting.delete); const deleteOps = this.enumerateDelete(deleteCtx); const editCtx = filterContext(ctx, this.setting.edit); const editOps = this.enumerateUpdate(editCtx); const mutations: MutationGroup[] = [addOps, deleteOps, ...editOps].filter( (ops) => ops.length > 0 ); log.debug(`Possible mutations: ${mutations.map(showMutations).join("\n")}`); const mutationGroup: MutationGroup = this.choice(mutations); log.debug(`Picked mutation group: ${showMutations(mutationGroup)}`); // TODO: check if the ctx used is correct const { res: prog, ctx: newCtx } = executeMutations( mutationGroup, this.currentProg, ctx ); this.currentMutations.push(...mutationGroup); this.updateProg(prog); return newCtx; }; generateArgStmt = ( decl: ArgStmtDecl, ctx: SynthesisContext ): WithStmts<Bind | ApplyPredicate> => { switch (decl.tag) { case "PredicateDecl": return this.generatePredicate(decl, ctx); case "FunctionDecl": return this.generateFunction(decl, ctx); case "ConstructorDecl": return this.generateConstructor(decl, ctx); } }; findMutations = (stmt: SubStmt, ctx: SynthesisContext): MutationGroup[] => { log.debug(`Finding mutations for ${prettyStmt(stmt)}`); const ops: (Mutation | undefined)[] = [ checkSwapStmtArgs(stmt, (p: ApplyPredicate) => { const indices = range(0, p.args.length); const elem1 = this.choice(indices); const elem2 = this.choice(without(indices, elem1)); return [elem1, elem2]; }), checkSwapExprArgs(stmt, (f: ArgExpr) => { const indices = range(0, f.args.length); const elem1 = this.choice(indices); const elem2 = this.choice(without(indices, elem1)); return [elem1, elem2]; }), checkReplaceStmtName(stmt, (p: ApplyPredicate) => { const matchingNames: string[] = matchSignatures(p, this.env).map( (decl) => decl.name.value ); const options = without(matchingNames, p.name.value); if (options.length > 0) { return this.choice(options); } else return undefined; }), checkReplaceExprName(stmt, (e: ArgExpr) => { const matchingNames: string[] = matchSignatures(e, this.env).map( (decl) => decl.name.value ); const options = without(matchingNames, e.name.value); if (options.length > 0) { return this.choice(options); } else return undefined; }), checkChangeStmtType( stmt, ctx, (oldStmt: ApplyPredicate, ctx: SynthesisContext) => { const options = argMatches(oldStmt, this.env); if (options.length > 0) { const pick = this.choice(options); const { res, stmts } = this.generateArgStmt(pick, ctx); const deleteOp: Delete = deleteMutation(oldStmt); const addOps: Add[] = stmts.map(addMutation); return { newStmt: res, additionalMutations: [deleteOp, ...addOps], }; } else return undefined; } ), checkChangeExprType( stmt, ctx, (oldStmt: Bind, oldExpr: ArgExpr, ctx: SynthesisContext) => { const options = argMatches(oldStmt, ctx.env); if (options.length > 0) { const pick = this.choice(options); const { res, stmts } = this.generateArgStmt(pick, ctx); let toDelete: SubStmt[]; // remove old statement if ( res.tag === "Bind" && res.variable.type !== oldStmt.variable.type ) { // old bind was replaced by a bind with diff type toDelete = cascadingDelete(oldStmt, this.currentProg); // remove refs to the old bind } else { toDelete = [oldStmt]; } const deleteOps: Delete[] = toDelete.map(deleteMutation); const addOps: Add[] = stmts.map(addMutation); return { newStmt: res, additionalMutations: [...deleteOps, ...addOps], }; } else return undefined; } ), ]; const mutations = compact(ops); log.debug( `Available mutations for ${prettyStmt(stmt)}:\n${showMutations( mutations )}` ); return mutations.map((m) => [m]); }; /** * Pick a random statement in the Substance program and enumerate all the applicable mutations. * @returns a list of mutation groups, each representing a series of `Update` mutations */ enumerateUpdate = (ctx: SynthesisContext): MutationGroup[] => { log.debug(`Picking a statement to edit...`); // pick a kind of statement to edit const chosenType = this.choice(nonEmptyDecls(ctx)); // get all possible types within this kind const candidates = [...getDecls(ctx, chosenType).keys()]; // choose a name const chosenName = this.choice(candidates); log.debug( `Chosen name is ${chosenName}, candidates ${candidates}, chosen type ${chosenType}` ); const stmt = this.findStmt(chosenType, chosenName); if (stmt !== undefined) { // find all available edit mutations for the given statement const mutations = this.findMutations(stmt, ctx); log.debug( `Possible update mutations for ${prettyStmt( stmt )} are:\n${mutations.map(showMutations).join("\n")}` ); return mutations; } else return []; }; /** * From the configuration, pick one Substance construct to generate, and return the new construct along with all other related constructs as a group of `Add` mutations. * @returns a group of `Add` mutations */ enumerateAdd = (ctx: SynthesisContext): MutationGroup => { const chosenType = this.choice(nonEmptyDecls(ctx)); let possibleOps: MutationGroup | undefined; log.debug(`Adding statement of ${chosenType} type`); if (chosenType === "TypeDecl") { const op = checkAddStmt( this.currentProg, ctx, (ctx: SynthesisContext) => { const type: TypeDecl = this.choice( ctx.env.types.toArray().map(([, b]) => b) ); return this.generateDecl(type, ctx); } ); possibleOps = op ? [op] : undefined; } else if (chosenType === "PredicateDecl") { possibleOps = checkAddStmts( this.currentProg, ctx, (ctx: SynthesisContext) => { const pred = this.choice( ctx.env.predicates.toArray().map(([, b]) => b) ); const { res, stmts } = this.generatePredicate(pred, ctx); return [...stmts, res]; } ); } else if (chosenType === "FunctionDecl") { possibleOps = checkAddStmts( this.currentProg, ctx, (ctx: SynthesisContext) => { const func = this.choice( ctx.env.functions.toArray().map(([, b]) => b) ); const { res, stmts } = this.generateFunction(func, ctx); return [...stmts, res]; } ); } else if (chosenType === "ConstructorDecl") { possibleOps = checkAddStmts( this.currentProg, ctx, (ctx: SynthesisContext) => { const cons = this.choice( ctx.env.constructors.toArray().map(([, b]) => b) ); const { res, stmts } = this.generateConstructor(cons, ctx); return [...stmts, res]; } ); } if (possibleOps) { log.debug(`Found mutations for add:\n${showMutations(possibleOps)}`); return possibleOps; } else return []; }; /** * From the configuration, pick one Substance statement to delete, and return one or more `Delete` mutations depending on if there will be cascading delete. * @returns a group of `Delete` mutations */ enumerateDelete = (ctx: SynthesisContext): MutationGroup => { log.debug("Deleting statement"); const chosenType = this.choice(nonEmptyDecls(ctx)); const candidates = [...getDecls(ctx, chosenType).keys()]; const chosenName = this.choice(candidates); const stmt = this.findStmt(chosenType, chosenName); let possibleOps: Mutation[] = []; if (stmt) { if (stmt.tag === "Bind" || stmt.tag === "Decl") { // if statement returns value, delete all refs to value cascadingDelete(stmt, this.currentProg).forEach((s) => { const del = checkDeleteStmt(this.currentProg, s); if (del) { possibleOps.push(del); } }); } else { const del = checkDeleteStmt(this.currentProg, stmt); possibleOps = del ? [del] : []; } } if (possibleOps) { log.debug(`Found mutations for delete:\n${showMutations(possibleOps)}`); return possibleOps; } else return []; }; // TODO: add an option to distinguish between edited vs original statements? findStmt = ( stmtType: DomainStmt["tag"], name: string ): SubStmt | undefined => { const stmts = this.currentProg.statements.filter((s) => { const subType = domainToSubType(stmtType); if (s.tag === "Bind") { const expr = s.expr; return expr.tag === subType && expr.name.value === name; } else if (s.tag === "Decl") { return s.tag === subType && s.type.name.value === name; } else { return s.tag === subType && s.name.value === name; } }); if (stmts.length > 0) { const stmt = this.choice(stmts); return stmt; } else { log.debug( `Warning: cannot find a ${stmtType} statement with name ${name}.` ); log.debug(`Available statements:\n${prettySubstance(this.currentProg)}`); return undefined; } }; generateDecl = (type: TypeDecl, ctx: SynthesisContext): Decl => { const typeCons = applyTypeDecl(type); const { res: name } = this.generateID(ctx, typeCons.name); const stmt: Decl = { tag: "Decl", nodeType: "SyntheticSubstance", children: [], type: typeCons, name, }; return stmt; }; generateDeclFromType = ( typeCons: TypeConsApp, ctx: SynthesisContext ): Decl => { const { res: name } = this.generateID(ctx, typeCons.name); const stmt: Decl = { tag: "Decl", nodeType: "SyntheticSubstance", children: [], type: typeCons, name, }; return stmt; }; generatePredicate = ( pred: PredicateDecl, ctx: SynthesisContext ): WithStmts<ApplyPredicate> => { const { res, stmts }: WithStmts<SubPredArg[]> = this.generatePredArgs( pred.args, ctx ); const p: ApplyPredicate = applyPredicate(pred, res); return { res: p, stmts }; }; generateFunction = ( func: FunctionDecl, ctx: SynthesisContext ): WithStmts<Bind> => { const { res: args, stmts: decls }: WithStmts<SubExpr[]> = this.generateArgs( func.args, ctx ); const rhs: ApplyFunction = applyFunction(func, args); // find the `TypeDecl` for the output type const outputType = func.output.type as TypeConstructor; // NOTE: the below will bypass the config and generate a new decl using the output type, search first in `ctx` to follow the config more strictly. // TODO: choose between generating vs. reusing const lhsDecl: Decl = this.generateDeclFromType( nullaryTypeCons(outputType.name), ctx ); const lhs: Identifier = lhsDecl.name; const stmt: Bind = applyBind(lhs, rhs); return { res: stmt, stmts: [...decls, lhsDecl] }; }; generateConstructor = ( cons: ConstructorDecl, ctx: SynthesisContext ): WithStmts<Bind> => { const { res: args, stmts: decls }: WithStmts<SubExpr[]> = this.generateArgs( cons.args, ctx ); const rhs: ApplyConstructor = applyConstructor(cons, args); const outputType = cons.output.type as TypeConstructor; // NOTE: the below will bypass the config and generate a new decl using the output type, search first in `ctx` to follow the config more strictly. const lhsDecl: Decl = this.generateDeclFromType( nullaryTypeCons(outputType.name), ctx ); const lhs: Identifier = lhsDecl.name; const stmt: Bind = applyBind(lhs, rhs); return { res: stmt, stmts: [...decls, lhsDecl] }; }; generateArgs = (args: Arg[], ctx: SynthesisContext): WithStmts<SubExpr[]> => { const resWithCtx: WithStmts<SubExpr[]> & IDList = args.reduce( ({ res, stmts, ids }: WithStmts<SubExpr[]> & IDList, arg) => { const { res: newArg, stmts: newStmts, ids: usedIDs } = this.generateArg( arg, ctx, this.setting.argOption, this.setting.argReuse, ids ); return { res: [...res, newArg], stmts: [...stmts, ...newStmts], ids: [...ids, ...usedIDs], }; }, { res: [], stmts: [], ids: [] } ); return { res: resWithCtx.res, stmts: resWithCtx.stmts, }; }; generateArg = ( arg: Arg, ctx: SynthesisContext, option: ArgOption, reuseOption: ArgReuse, usedIDs: Identifier[] ): WithStmts<SubExpr> & IDList => { const argType: Type = arg.type; if (argType.tag === "TypeConstructor") { switch (option) { case "existing": { // TODO: clean up the logic const possibleIDs = reuseOption === "distinct" ? findIDs(ctx, argType.name.value, usedIDs) : findIDs(ctx, argType.name.value); const existingID = this.choice(possibleIDs); log.debug( `generating an argument with possbilities ${possibleIDs.map( (i) => i.value )}` ); if (!existingID) { log.debug( `no existing ID found for ${argType.name.value}, generating a new value instead` ); return this.generateArg( arg, ctx, "generated", reuseOption, usedIDs ); } else { return { res: existingID, stmts: [], ids: [...usedIDs, existingID], }; } } case "generated": const argTypeDecl = ctx.env.types.get(argType.name.value); if (argTypeDecl) { const decl = this.generateDecl(argTypeDecl, ctx); return { res: decl.name, stmts: [decl], ids: [...usedIDs, decl.name], }; } else { throw new Error( `${argType.name.value} not found in the candidate list` ); } case "mixed": return this.generateArg( arg, ctx, this.choice(["existing", "generated"]), reuseOption, usedIDs ); } } else { throw new Error(`${argType.tag} not supported for argument generation`); } }; generatePredArgs = ( args: Arg[], ctx: SynthesisContext ): WithStmts<SubPredArg[]> => { const resWithCtx = args.reduce( ({ res, stmts, ids }: WithStmts<SubPredArg[]> & IDList, arg) => { const { res: newArg, stmts: newStmts, ids: usedIDs, } = this.generatePredArg( arg, ctx, this.setting.argOption, this.setting.argReuse, ids ); return { res: [...res, newArg], stmts: [...stmts, ...newStmts], ids: [...ids, ...usedIDs], }; }, { res: [], stmts: [], ids: [], } ); return { res: resWithCtx.res, stmts: resWithCtx.stmts, }; }; generatePredArg = ( arg: Arg, ctx: SynthesisContext, option: ArgOption, reuseOption: ArgReuse, usedIDs: Identifier[] ): WithStmts<SubPredArg> & IDList => { const argType: Type = arg.type; if (argType.tag === "Prop") { const pred = this.choice(ctx.env.predicates.toArray().map(([, b]) => b)); const { res, stmts } = this.generatePredicate(pred, ctx); return { res, stmts, ids: usedIDs }; } else { return this.generateArg(arg, ctx, option, reuseOption, usedIDs); } }; } //#endregion //#region Helpers const declTypes: DomainStmt["tag"][] = [ "ConstructorDecl", "FunctionDecl", "TypeDecl", "PredicateDecl", ]; const filterBySetting = <T>( decls: Map<string, T>, setting: MatchSetting ): Map<string, T> => { if (setting === "*") { return decls; } else { return decls.filter((_, key) => setting.includes(key)); } }; //#endregion
the_stack
import { BindingsPlugin, DOMException, ExecutionContext, FetchError, FetchEvent, Request, Response, ScheduledController, ScheduledEvent, ServiceWorkerGlobalScope, kAddModuleFetchListener, kDispatchFetch, kDispatchScheduled, } from "@miniflare/core"; import { NoOpLog } from "@miniflare/shared"; import { TestLog, getObjectProperties, isWithin, triggerPromise, useMiniflare, useServer, } from "@miniflare/shared-test"; import anyTest, { TestInterface, ThrowsExpectation } from "ava"; interface Context { log: TestLog; globalScope: ServiceWorkerGlobalScope; } const test = anyTest as TestInterface<Context>; test.beforeEach((t) => { const log = new TestLog(); const globalScope = new ServiceWorkerGlobalScope(log, {}, { KEY: "value" }); t.context = { log, globalScope }; }); test("ServiceWorkerGlobalScope: includes sandbox in globals", (t) => { const globalScope = new ServiceWorkerGlobalScope( new NoOpLog(), { sand: "box" }, {}, false ); t.is((globalScope as any).sand, "box"); }); test("ServiceWorkerGlobalScope: includes environment in globals if modules disabled", (t) => { let globalScope = new ServiceWorkerGlobalScope( new NoOpLog(), {}, { env: "ironment" }, false ); t.is((globalScope as any).env, "ironment"); globalScope = new ServiceWorkerGlobalScope( new NoOpLog(), {}, { env: "ironment" }, true ); t.throws(() => (globalScope as any).env, { instanceOf: ReferenceError, message: /^env is not defined\.\nAttempted to access binding using global in modules/, }); }); test("ServiceWorkerGlobalScope: addEventListener: disabled if modules enabled", (t) => { const globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}, true); t.throws(() => globalScope.addEventListener("fetch", () => {}), { instanceOf: TypeError, message: "Global addEventListener() cannot be used in modules. Instead, event " + "handlers should be declared as exports on the root module.", }); }); test("ServiceWorkerGlobalScope: removeEventListener: disabled if modules enabled", (t) => { const globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}, true); t.throws(() => globalScope.removeEventListener("fetch", () => {}), { instanceOf: TypeError, message: "Global removeEventListener() cannot be used in modules. Instead, event " + "handlers should be declared as exports on the root module.", }); }); test("ServiceWorkerGlobalScope: dispatchEvent: disabled if modules enabled", (t) => { const globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}, true); const event = new FetchEvent("fetch", { request: new Request("http://localhost"), }); t.throws(() => globalScope.dispatchEvent(event), { instanceOf: TypeError, message: "Global dispatchEvent() cannot be used in modules. Instead, event " + "handlers should be declared as exports on the root module.", }); }); test("ServiceWorkerGlobalScope: hides implementation details", (t) => { const { globalScope } = t.context; t.deepEqual(getObjectProperties(globalScope), [ "KEY", // binding "addEventListener", "dispatchEvent", "global", "removeEventListener", "self", ]); }); test("MiniflareCore: includes global self-references", async (t) => { t.plan(2); const mf = useMiniflare( { BindingsPlugin }, { globals: { t }, script: "t.is(global, globalThis); t.is(self, global);", } ); await mf.getPlugins(); }); test("MiniflareCore: adds fetch event listener", async (t) => { const script = `(${(() => { const sandbox = globalThis as any; sandbox.addEventListener("fetch", (e: FetchEvent) => { e.respondWith(new sandbox.Response(e.request.url)); }); }).toString()})()`; const mf = useMiniflare({}, { script }); const res = await mf.dispatchFetch(new Request("http://localhost:8787/")); t.is(await res.text(), "http://localhost:8787/"); }); test("MiniflareCore: adds scheduled event listener", async (t) => { const script = `(${(() => { const sandbox = globalThis as any; sandbox.addEventListener("scheduled", (e: ScheduledEvent) => { e.waitUntil(Promise.resolve(e.scheduledTime)); e.waitUntil(Promise.resolve(e.cron)); }); }).toString()})()`; const mf = useMiniflare({}, { script }); const res = await mf.dispatchScheduled(1000, "30 * * * *"); t.is(res[0], 1000); t.is(res[1], "30 * * * *"); }); test("MiniflareCore: adds module fetch event listener", async (t) => { const script = `export default { thisTest: "that", fetch(request, env, ctx) { ctx.waitUntil(Promise.resolve(env.KEY)); ctx.waitUntil(this.thisTest); return new Response(request.url); } }`; const mf = useMiniflare( { BindingsPlugin }, { modules: true, script, bindings: { KEY: "value" } } ); const res = await mf.dispatchFetch(new Request("http://localhost:8787/")); t.is(await res.text(), "http://localhost:8787/"); t.deepEqual(await res.waitUntil(), ["value", "that"]); }); test("MiniflareCore: adds module scheduled event listener", async (t) => { const script = `export default { thisTest: "that", scheduled(controller, env, ctx) { ctx.waitUntil(Promise.resolve(controller.scheduledTime)); ctx.waitUntil(Promise.resolve(controller.cron)); ctx.waitUntil(Promise.resolve(env.KEY)); ctx.waitUntil(this.thisTest); return "returned"; } }`; let mf = useMiniflare( { BindingsPlugin }, { modules: true, script, bindings: { KEY: "value" } } ); let res = await mf.dispatchScheduled(1000, "30 * * * *"); t.deepEqual(res, [1000, "30 * * * *", "value", "that", "returned"]); // Check returned value is only waitUntil'ed if it's defined mf = useMiniflare( { BindingsPlugin }, { modules: true, script: `export default { scheduled(controller, env, ctx) { ctx.waitUntil(42); }}`, } ); res = await mf.dispatchScheduled(1000, "30 * * * *"); t.deepEqual(res, [42]); }); test("kDispatchFetch: dispatches event", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.respondWith(new Response(e.request.url)); }); const res = await globalScope[kDispatchFetch]( new Request("http://localhost:8787/") ); t.is(await res.text(), "http://localhost:8787/"); }); test("kDispatchFetch: dispatches event with promise response", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.respondWith(Promise.resolve(new Response(e.request.url))); }); const res = await globalScope[kDispatchFetch]( new Request("http://localhost:8787/") ); t.is(await res.text(), "http://localhost:8787/"); }); test("kDispatchFetch: stops calling listeners after first response", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.waitUntil(Promise.resolve(1)); e.waitUntil(Promise.resolve(2)); }); globalScope.addEventListener("fetch", (e) => { e.waitUntil(Promise.resolve(3)); e.respondWith(new Response(e.request.url)); }); globalScope.addEventListener("fetch", (e) => { e.waitUntil(Promise.resolve(4)); }); const res = await globalScope[kDispatchFetch]( new Request("http://localhost:8787/") ); t.is(await res.text(), "http://localhost:8787/"); t.deepEqual(await res.waitUntil(), [1, 2, 3]); }); test("kDispatchFetch: stops calling listeners after first error", async (t) => { t.plan(3); const { globalScope } = t.context; globalScope.addEventListener("fetch", () => { t.pass(); }); globalScope.addEventListener("fetch", () => { t.pass(); if (1 === 1) throw new TypeError("test"); }); globalScope.addEventListener("fetch", () => { t.fail(); }); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: TypeError, message: "test" } ); }); test("kDispatchFetch: passes through to upstream on no response", async (t) => { const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http; const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.waitUntil(Promise.resolve(1)); }); const res = await globalScope[kDispatchFetch](new Request(upstream), true); t.is(await res.text(), "upstream"); t.deepEqual(await res.waitUntil(), [1]); }); test("kDispatchFetch: passes through to upstream on error", async (t) => { const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http; const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.waitUntil(Promise.resolve(1)); e.passThroughOnException(); if (1 === 1) throw new Error("test"); e.respondWith(new Response(e.request.url)); }); const res = await globalScope[kDispatchFetch](new Request(upstream), true); t.is(await res.text(), "upstream"); t.deepEqual(await res.waitUntil(), [1]); }); test("kDispatchFetch: passes through to upstream on async error", async (t) => { const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http; const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.waitUntil(Promise.resolve(1)); e.passThroughOnException(); e.respondWith(Promise.reject(new Error("test"))); }); const res = await globalScope[kDispatchFetch](new Request(upstream), true); t.is(await res.text(), "upstream"); t.deepEqual(await res.waitUntil(), [1]); }); test("kDispatchFetch: throws error if no pass through on listener error", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { if (1 === 1) throw new Error("test"); e.respondWith(new Response(e.request.url)); }); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: Error, message: "test" } ); }); test("kDispatchFetch: throws error if pass through with no upstream", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.passThroughOnException(); if (1 === 1) throw new Error("test"); e.respondWith(new Response(e.request.url)); }); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_NO_UPSTREAM", message: "No upstream to pass-through to specified.\nMake sure you've set the `upstream` option.", } ); }); test("kDispatchFetch: throws error if respondWith called multiple times", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("fetch", (e) => { e.respondWith(new Response("body1")); e.respondWith(new Response("body2")); }); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: DOMException, name: "InvalidStateError", message: "FetchEvent.respondWith() has already been called; it can only be called once.", } ); }); test("kDispatchFetch: throws error if respondWith called after response sent", async (t) => { t.plan(2); const { globalScope } = t.context; const [trigger, promise] = triggerPromise<void>(); globalScope.addEventListener("fetch", async (e) => { await promise; t.throws(() => e.respondWith(new Response("body")), { instanceOf: DOMException, name: "InvalidStateError", message: "Too late to call FetchEvent.respondWith(). It must be called synchronously in the event handler.", }); }); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_NO_RESPONSE" } ); trigger(); }); test("kDispatchFetch: throws error if response is not a Response", async (t) => { // Check suggestion with regular service worker handler let globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}); globalScope.addEventListener("fetch", (e) => { e.respondWith(Promise.resolve({} as any)); }); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_RESPONSE_TYPE", message: "Fetch handler didn't respond with a Response object.\n" + "Make sure you're calling `event.respondWith()` with a `Response` or " + "`Promise<Response>` in your handler.", } ); // Check suggestion with module handler globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}, true); globalScope[kAddModuleFetchListener](async () => ({} as any)); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_RESPONSE_TYPE", message: "Fetch handler didn't respond with a Response object.\n" + "Make sure you're returning a `Response` in your handler.", } ); }); test("kDispatchFetch: throws error if fetch handler doesn't respond", async (t) => { // Check suggestion with regular service worker handler let globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}); globalScope.addEventListener("fetch", () => {}); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_NO_RESPONSE", message: "No fetch handler responded and no upstream to proxy to specified.\n" + "Make sure you're calling `event.respondWith()` with a `Response` or " + "`Promise<Response>` in your handler.", } ); // Check suggestion with module handler globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}, true); globalScope[kAddModuleFetchListener]((async () => {}) as any); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_NO_RESPONSE", message: "No fetch handler responded and no upstream to proxy to specified.\n" + "Make sure you're returning a `Response` in your handler.", } ); }); test("kDispatchFetch: throws error if fetch handler undefined", async (t) => { // Check suggestion with regular service worker handler let globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_NO_HANDLER", message: "No fetch handler defined and no upstream to proxy to specified.\n" + 'Make sure you\'re calling addEventListener("fetch", ...).', } ); // Check suggestion with module handler globalScope = new ServiceWorkerGlobalScope(new NoOpLog(), {}, {}, true); await t.throwsAsync( () => globalScope[kDispatchFetch](new Request("http://localhost:8787/")), { instanceOf: FetchError, code: "ERR_NO_HANDLER", message: "No fetch handler defined and no upstream to proxy to specified.\n" + "Make sure you're exporting a default object containing a `fetch` " + "function property.", } ); }); test("kDispatchScheduled: dispatches event", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("scheduled", (e) => { e.waitUntil(Promise.resolve(1)); e.waitUntil(Promise.resolve(2)); }); globalScope.addEventListener("scheduled", (e) => { e.waitUntil(Promise.resolve(3)); e.waitUntil(Promise.resolve(e.scheduledTime)); e.waitUntil(Promise.resolve(e.cron)); }); const res = await globalScope[kDispatchScheduled](1000, "30 * * * *"); t.deepEqual(res, [1, 2, 3, 1000, "30 * * * *"]); }); test("kDispatchScheduled: defaults to current time and empty cron if none specified", async (t) => { const { globalScope } = t.context; globalScope.addEventListener("scheduled", (e) => { e.waitUntil(Promise.resolve(e.scheduledTime)); e.waitUntil(Promise.resolve(e.cron)); }); const [scheduledTime, cron] = await globalScope[kDispatchScheduled](); isWithin(t, 10000, Date.now(), scheduledTime); t.is(cron, ""); }); test("kDispatchScheduled: stops calling listeners after first error", async (t) => { t.plan(3); const { globalScope } = t.context; globalScope.addEventListener("scheduled", () => { t.pass(); }); globalScope.addEventListener("scheduled", () => { t.pass(); if (1 === 1) throw new TypeError("test"); }); globalScope.addEventListener("scheduled", () => { t.fail(); }); await t.throwsAsync(() => globalScope[kDispatchScheduled](), { instanceOf: TypeError, message: "test", }); }); const illegalInvocationExpectation: ThrowsExpectation = { instanceOf: TypeError, message: "Illegal invocation", }; test("FetchEvent: hides implementation details", (t) => { const event = new FetchEvent("fetch", { request: new Request("http://localhost:8787"), }); t.deepEqual(getObjectProperties(event), [ "isTrusted", "passThroughOnException", "request", "respondWith", "waitUntil", ]); }); test("FetchEvent: methods throw if this is incorrectly bound", (t) => { const { respondWith, passThroughOnException, waitUntil } = new FetchEvent( "fetch", { request: new Request("http://localhost:8787") } ); t.throws(() => respondWith(new Response()), illegalInvocationExpectation); t.throws(() => passThroughOnException(), illegalInvocationExpectation); t.throws(() => waitUntil(Promise.resolve()), illegalInvocationExpectation); }); test("ScheduledEvent: hides implementation details", (t) => { const event = new ScheduledEvent("scheduled", { scheduledTime: 1000, cron: "30 * * * *", }); t.deepEqual(getObjectProperties(event), [ "cron", "isTrusted", "scheduledTime", "waitUntil", ]); }); test("ScheduledEvent: methods throw if this is incorrectly bound", (t) => { const { waitUntil } = new ScheduledEvent("scheduled", { scheduledTime: 1000, cron: "30 * * * *", }); t.throws(() => waitUntil(Promise.resolve()), illegalInvocationExpectation); }); test("ExecutionContext: hides implementation details", (t) => { const event = new FetchEvent("fetch", { request: new Request("http://localhost:8787"), }); const ctx = new ExecutionContext(event); t.deepEqual(getObjectProperties(ctx), [ "passThroughOnException", "waitUntil", ]); }); test("ExecutionContext: methods throw if this is incorrectly bound", (t) => { const event = new FetchEvent("fetch", { request: new Request("http://localhost:8787"), }); const { passThroughOnException, waitUntil } = new ExecutionContext(event); t.throws(() => passThroughOnException(), illegalInvocationExpectation); t.throws(() => waitUntil(Promise.resolve()), illegalInvocationExpectation); }); test("ScheduledController: hides implementation details", (t) => { const controller = new ScheduledController(1000, "30 * * * *"); t.deepEqual(getObjectProperties(controller), ["cron", "scheduledTime"]); });
the_stack
import { add, all, always, and, append, concat, cons, dec, filter, find, fill, findBy, findOf, first, flip, get, greaterThan, has, identity, inc, includes, includesi, into, Lens, lessThan, map, matching, maxBy, maxOf, minBy, minOf, mod, not, or, prepend, productOf, push, rest, returns, set, some, sub, sumOf, toggle, unshift, updateAll, valueOr } from "shades"; // prettier-ignore interface Settings { permissions: 'visible' | 'private'; lastLogin: Date; } interface Post { title: string; description: string; likes: number; } interface User { name: string; posts: Post[]; goldMember: boolean; friends: User[]; settings: Settings; bestFriend?: User; } declare const users: User[]; declare const user: User; declare const byName: { [name: string]: User }; // Virtual Lens const toString: Lens<boolean, string> = { get: b => b.toString(), mod: f => b => !!f(b.toString()) }; get("goldMember", toString)(user); // $ExpectType string mod("goldMember", toString)(s => s.toUpperCase())(user); // $ExpectType User mod("freinds", toString)(s => s.toUpperCase())(user); // $ExpectError into("a")({ a: 10 }); // $ExpectType number into("b")({ a: 10 }); // $ExpectError into({ a: 10 })({ a: 10 }); // $ExpectType boolean into({ a: 10 })({ b: 10 }); // $ExpectError into((x: number) => x + 1)(10); // $ExpectType number users[0].posts.reduce(maxOf("likes")); // $ExpectType Post users[0].posts.reduce(maxOf("title")); // $ExpectError users[0].posts.reduce(maxOf("farts")); // $ExpectError users.reduce(maxOf(user => user.name.length)); // $ExpectType User users.reduce(maxOf(user => user.name)); // $ExpectError users.reduce(findOf("name")); // $ExpectType User users.reduce(findOf({ name: "butt" })); // $ExpectType User users.reduce(findOf({ butt: "name" })); // $ExpectError users.reduce(findOf(user => user.name)); // $ExpectType User users.reduce(findOf(user => user.butt)); // $ExpectError users.map(findOf(user => user.butt)); // $ExpectError users[0].posts.reduce(sumOf("likes"), 0); // $ExpectType number users[0].posts.reduce(sumOf("title"), 0); // $ExpectError users[0].posts.reduce(sumOf("farts"), 0); // $ExpectError users.reduce(sumOf(user => user.name.length), 0); // $ExpectType number users.reduce(sumOf(user => user.name), 0); // $ExpectError users[0].posts.reduce(productOf("likes"), 1); // $ExpectType number users[0].posts.reduce(productOf("title"), 1); // $ExpectError users[0].posts.reduce(productOf("farts"), 1); // $ExpectError users.reduce(productOf(user => user.name.length), 1); // $ExpectType number users.reduce(productOf(user => user.name), 1); // $ExpectError identity(10); // $ExpectType 10 identity("butts"); // $ExpectType "butts" flip(always); // $ExpectType <A>(b: any) => (a: A) => A always(10)(map); // $ExpectType number always("10")(map); // $ExpectType string always(10); // $ExpectType (b: any) => number declare function notFn1(a: number): string; declare function notFn4(a: number, b: string, c: boolean, d: number): string; not(notFn1); // $ExpectType Fn1<number, boolean> not(notFn4); // $ExpectType Fn4<number, string, boolean, number, boolean> not("name")(users[0]); // $ExpectType boolean not("butt")(users[0]); // $ExpectError declare function andFn1(a: number): number; declare function andFn2(a: number, b: string): number; declare function andFn3(a: number, b: string, c: boolean): number; declare function andFn3Bad(a: number, b: string, c: boolean): boolean; and(andFn3, andFn3, andFn3); // $ExpectType Fn3<number, string, boolean, number> and(andFn1, andFn2, andFn3); // $ExpectType Fn3<number, string, boolean, number> and(andFn1, andFn2, identity); // $ExpectType Fn2<number, string, number> and(andFn1); // $ExpectType Fn1<number, number> and(andFn1, andFn2, andFn3Bad); // $ExpectError declare function orFn1(a: number): number; declare function orFn2(a: number, b: string): number; declare function orFn3(a: number, b: string, c: boolean): number; declare function orFn3Bad(a: number, b: string, c: boolean): boolean; or(orFn3, orFn3, orFn3); // $ExpectType Fn3<number, string, boolean, number> or(orFn1, orFn2, orFn3); // $ExpectType Fn3<number, string, boolean, number> or(orFn1, orFn2, identity); // $ExpectType Fn2<number, string, number> or(orFn1); // $ExpectType Fn1<number, number> or(orFn1, orFn2, orFn3Bad); // $ExpectError fill({ a: 10 })({ a: undefined, b: 5 }).a; // $ExpectType number fill({ a: 10 })({}).a; // $ExpectType number // 'bestFriend' is an optional `User` property on the `User` object get("bestFriend", "name")(user); // $ExpectType ErrorCannotLensIntoOptionalKey<User | undefined, "name"> const friendsWithMyself = fill({ bestFriend: user })(user); get("bestFriend", "name")(friendsWithMyself); // $ExpectType string get("bestFriend", "bestFriend", "name")(user); // $ExpectType ErrorCannotLensIntoOptionalKey<ErrorCannotLensIntoOptionalKey<User | undefined, "bestFriend">, "name"> const deepFriendsWithMyself = fill({ bestFriend: friendsWithMyself })(user); get("bestFriend", "bestFriend", "name")(deepFriendsWithMyself); // $ExpectType string has({ a: 1 }); // $ExpectType (obj: HasPattern<{ a: number; }>) => boolean has({ a: false }); // $ExpectType (obj: HasPattern<{ a: boolean; }>) => boolean has({ a: 1 })({ a: 10 }); // $ExpectType boolean has({ a: 1 })({ a: false }); // $ExpectError has({ a: (n: number) => n > 10 })({ a: 5 }); // $ExpectType boolean has({ a: (n: number) => n > 10 })({ a: false }); // $ExpectError greaterThan(2); // $ExpectType (b: number) => boolean greaterThan("a"); // $ExpectType (b: string) => boolean greaterThan("a")("b"); // $ExpectType boolean greaterThan("a")(1); // $ExpectError greaterThan({ a: 1 }); // $ExpectError lessThan(2); // $ExpectType (b: number) => boolean lessThan("a"); // $ExpectType (b: string) => boolean lessThan("a")("b"); // $ExpectType boolean lessThan("a")(1); // $ExpectError lessThan({ a: 1 }); // $ExpectError toggle(false); // $ExpectType boolean toggle("a"); // $ExpectError returns(10)(() => 10); // $ExpectType boolean returns(10)(() => "hi"); // $ExpectError declare const getID: { ID(): string; }; has({ ID: returns("blah") })(getID); // $ExpectType boolean has({ ID: returns(10) })(getID); // $ExpectError add(1)(3); // $ExpectType number add(1)("s"); // $ExpectError sub(1)(3); // $ExpectType number sub(1)("s"); // $ExpectError inc(1); // $ExpectType number inc(""); // $ExpectError dec(1); // $ExpectType number dec(""); // $ExpectError includes("hello")("hello"); // $ExpectType boolean includes("hello")(false); // $ExpectError includesi("hello")("hello"); // $ExpectType boolean includesi("hello")(false); // $ExpectError get("name")(user); // $ExpectType string get(0, "name")(users); // $ExpectType string get(0, "fart")(users); // $ExpectError get("bestFriend")(user); // $ExpectType User | undefined get("bestFriend", "name")(user); // $ExpectType ErrorCannotLensIntoOptionalKey<User | undefined, "name"> get("friends", all<User>(), "name")(user); // $ExpectType string[] get(matching("goldMember"))(users); // $ExpectType User[] get(matching("goldMember"), "name")(users); // $ExpectType string[] get("friends", findBy.of<User>({ name: "john" }), "name")(user); // $ExpectType string get("friends", findBy.of<User>("goldMember"), "posts")(user); // $ExpectType Post[] get("friends", findBy((user: User) => user.settings), "posts")(user); // $ExpectType Post[] get("friends", findBy((user: User) => user.settings), "pots")(user); // $ExpectError get("friends", maxBy.of<User>({ name: "john" }), "name")(user); // $ExpectType string get("friends", maxBy.of<User>("goldMember"), "posts")(user); // $ExpectType Post[] get("friends", maxBy((user: User) => user.settings), "posts")(user); // $ExpectType Post[] get("friends", maxBy((user: User) => user.settings), "pots")(user); // $ExpectError get("friends", minBy.of<User>({ name: "john" }), "name")(user); // $ExpectType string get("friends", minBy.of<User>("goldMember"), "posts")(user); // $ExpectType Post[] get("friends", minBy((user: User) => user.settings), "posts")(user); // $ExpectType Post[] get("friends", minBy((user: User) => user.settings), "pots")(user); // $ExpectError updateAll<User>( set("name")("jack"), mod("posts", all(), "title")(s => s.toUpperCase()) )(user); // $ExpectType User get("bestFriend")(user); // $ExpectType User | undefined get("bestFriend", valueOr(user))(user); // $ExpectType User get(all(), "bestFriend")(users); // $ExpectType (User | undefined)[] get(all(), "bestFriend", valueOr(user))(users); // $ExpectType User[] filter((user: User) => user.friends.length > 0)(users); // $ExpectType User[] filter((user: User) => user.name)(byName); // $ExpectType { [name: string]: User; } filter("name")(users); // $ExpectType User[] filter("name")(byName); // $ExpectType { [name: string]: User; } filter("butts")(users); // $ExpectError filter({ name: "john" })(users); // $ExpectType User[] filter({ name: "john" })(byName); // $ExpectType { [name: string]: User; } filter({ settings: (settings: string) => settings })(users); // $ExpectError filter({ settings: (settings: Settings) => settings })(users); // $ExpectType User[] map("name")(users); // $ExpectType string[] map("name")(byName); // $ExpectType { [key: string]: string; } map("not-a-key")(users); // $ExpectError map("not-a-key")(byName); // $ExpectError map("bestFriend")(users); // $ExpectType (User | undefined)[] const usersFriends = map("friends")(users); // $ExpectType User[][] map(1)(usersFriends); // $ExpectType User[] map(1)(users); // $ExpectError const usersFriendsByName = map("friends")(byName); // $ExpectType { [key: string]: User[]; } map(2)(usersFriendsByName); // $ExpectType { [key: string]: User; } map((x: User) => x.name)(users); // $ExpectType string[] map({ name: "john", settings: (settings: Settings) => !!settings })(users); // $ExpectType boolean[] map({ name: "john", settings: (settings: Settings) => !!settings })(byName); // $ExpectType { [key: string]: boolean; } declare const fetchUsers: Promise<User[]>; // Nested maps require type annotations, but still provide safety map<User[], string[]>(map("name"))(fetchUsers); // $ExpectType Promise<string[]> // map<User[], boolean[]>(map('name'))(fetchUsers) // $ExpectError declare const userMap: Map<string, User>; declare const userSet: Set<User>; map("name")(userMap); // $ExpectType Map<string, string> map("name")(userSet); // $ExpectType Set<string> find("name")(users); // $ExpectType User | undefined find("fart")(users); // $ExpectError find((user: User) => user.friends)(users); // $ExpectType User | undefined find((user: User) => user.friends.length > 0)(users); // $ExpectType User | undefined find({ name: "barg" })(users); // $ExpectType User | undefined find({ name: false })(users); // $ExpectError find({ name: (s: string) => !!"barg" })(users); // $ExpectType User | undefined find({ name: (s: Settings) => !!"barg" })(users); // $ExpectError const a = find({ friends: find({ name: "silent bob" }) })(users); a; // $ExpectType User | undefined find({ settings: { permissions: false } })(users); // $ExpectError find({ settings: { permissions: false } })(users); // $ExpectError find({ settings: { permissions: (perm: string) => !!perm } })(users); // ExpectType User | undefined find({ settings: { permissions: (perm: boolean) => !!perm } })(users); // $ExpectError some("name")(users); // $ExpectType boolean some((user: User) => user.friends)(users); // $ExpectType boolean some((user: User) => user.friends.length > 0)(users); // $ExpectType boolean some({ name: "barg" })(users); // $ExpectType boolean some({ name: false })(users); // $ExpectError some({ name: (s: string) => !!"barg" })(users); // $ExpectType boolean some({ name: (s: boolean) => !!"barg" })(users); // $ExpectError cons(1)([1, 2, 3]); // $ExpectType number[] cons("a")(["a", "b", "c"]); // $ExpectType string[] cons(1)(2); // $ExpectError cons(1)(["a", "b", "c"]); // $ExpectError cons("1")([1, 2, 3]); // $ExpectError unshift(1)([1, 2, 3]); // $ExpectType number[] unshift("a")(["a", "b", "c"]); // $ExpectType string[] unshift(1)(2); // $ExpectError unshift(1)(["a", "b", "c"]); // $ExpectError unshift("1")([1, 2, 3]); // $ExpectError first([1, 3, 4]); // $ExpectType number first(users); // $ExpectType User first("hi"); // $ExpectType string first(true); // $ExpectError rest([1, 3, 4]); // $ExpectType number[] rest(users); // $ExpectType User[] rest("hi"); // $ExpectError rest(true); // $ExpectError concat([1, 2, 3])([2, 3]); // $ExpectType number[] // [2, 3, 1, 2, 3] concat(["hi"])(["wo"]); // $ExpectType string[] // ['wo', 'hi'] concat(["hi"])([1, 2, 3]); // $ExpectError prepend([1, 2, 3])([2, 3]); // $ExpectType number[] // [1, 2, 3, 2, 3] prepend(["hi"])(["wo"]); // $ExpectType string[] // ['hi', 'wo'] prepend(["hi"])([1, 2, 3]); // $ExpectError
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Dashboards } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { Portal } from "../portal"; import { Dashboard, DashboardsListByResourceGroupNextOptionalParams, DashboardsListByResourceGroupOptionalParams, DashboardsListBySubscriptionNextOptionalParams, DashboardsListBySubscriptionOptionalParams, DashboardsCreateOrUpdateOptionalParams, DashboardsCreateOrUpdateResponse, DashboardsDeleteOptionalParams, DashboardsGetOptionalParams, DashboardsGetResponse, PatchableDashboard, DashboardsUpdateOptionalParams, DashboardsUpdateResponse, DashboardsListByResourceGroupResponse, DashboardsListBySubscriptionResponse, DashboardsListByResourceGroupNextResponse, DashboardsListBySubscriptionNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Dashboards operations. */ export class DashboardsImpl implements Dashboards { private readonly client: Portal; /** * Initialize a new instance of the class Dashboards class. * @param client Reference to the service client */ constructor(client: Portal) { this.client = client; } /** * Gets all the Dashboards within a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: DashboardsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<Dashboard> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: DashboardsListByResourceGroupOptionalParams ): AsyncIterableIterator<Dashboard[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: DashboardsListByResourceGroupOptionalParams ): AsyncIterableIterator<Dashboard> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Gets all the dashboards within a subscription. * @param options The options parameters. */ public listBySubscription( options?: DashboardsListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<Dashboard> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: DashboardsListBySubscriptionOptionalParams ): AsyncIterableIterator<Dashboard[]> { let result = await this._listBySubscription(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listBySubscriptionNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listBySubscriptionPagingAll( options?: DashboardsListBySubscriptionOptionalParams ): AsyncIterableIterator<Dashboard> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * Creates or updates a Dashboard. * @param resourceGroupName The name of the resource group. * @param dashboardName The name of the dashboard. * @param dashboard The parameters required to create or update a dashboard. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, dashboardName: string, dashboard: Dashboard, options?: DashboardsCreateOrUpdateOptionalParams ): Promise<DashboardsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, dashboardName, dashboard, options }, createOrUpdateOperationSpec ); } /** * Deletes the Dashboard. * @param resourceGroupName The name of the resource group. * @param dashboardName The name of the dashboard. * @param options The options parameters. */ delete( resourceGroupName: string, dashboardName: string, options?: DashboardsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, dashboardName, options }, deleteOperationSpec ); } /** * Gets the Dashboard. * @param resourceGroupName The name of the resource group. * @param dashboardName The name of the dashboard. * @param options The options parameters. */ get( resourceGroupName: string, dashboardName: string, options?: DashboardsGetOptionalParams ): Promise<DashboardsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, dashboardName, options }, getOperationSpec ); } /** * Updates an existing Dashboard. * @param resourceGroupName The name of the resource group. * @param dashboardName The name of the dashboard. * @param dashboard The updatable fields of a Dashboard. * @param options The options parameters. */ update( resourceGroupName: string, dashboardName: string, dashboard: PatchableDashboard, options?: DashboardsUpdateOptionalParams ): Promise<DashboardsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, dashboardName, dashboard, options }, updateOperationSpec ); } /** * Gets all the Dashboards within a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: DashboardsListByResourceGroupOptionalParams ): Promise<DashboardsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Gets all the dashboards within a subscription. * @param options The options parameters. */ private _listBySubscription( options?: DashboardsListBySubscriptionOptionalParams ): Promise<DashboardsListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: DashboardsListByResourceGroupNextOptionalParams ): Promise<DashboardsListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListBySubscriptionNext * @param nextLink The nextLink from the previous successful call to the ListBySubscription method. * @param options The options parameters. */ private _listBySubscriptionNext( nextLink: string, options?: DashboardsListBySubscriptionNextOptionalParams ): Promise<DashboardsListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listBySubscriptionNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.Dashboard }, 201: { bodyMapper: Mappers.Dashboard }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.dashboard, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.dashboardName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.dashboardName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.Dashboard }, 404: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.dashboardName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.Dashboard }, 404: {}, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.dashboard1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.dashboardName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DashboardListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Portal/dashboards", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DashboardListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DashboardListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DashboardListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer };
the_stack
import Component from '@glimmer/component'; import { getOwner } from '@ember/application'; import { inject as service } from '@ember/service'; import { action } from '@ember/object'; import { tracked } from '@glimmer/tracking'; import RouterService from '@ember/routing/router-service'; import Layer2Network from '@cardstack/web-client/services/layer2-network'; import WorkflowPersistence from '@cardstack/web-client/services/workflow-persistence'; import HubAuthentication from '@cardstack/web-client/services/hub-authentication'; import { currentNetworkDisplayInfo as c } from '@cardstack/web-client/utils/web3-strategies/network-display-info'; import { Milestone, NetworkAwareWorkflowCard, NetworkAwareWorkflowMessage, PostableCollection, Workflow, WorkflowCard, WorkflowMessage, WorkflowName, conditionalCancelationMessage, } from '@cardstack/web-client/models/workflow'; import { standardCancelationPostables } from '@cardstack/web-client/models/workflow/cancelation-helpers'; const FAILURE_REASONS = { L2_DISCONNECTED: 'L2_DISCONNECTED', L2_ACCOUNT_CHANGED: 'L2_ACCOUNT_CHANGED', UNAUTHENTICATED: 'UNAUTHENTICATED', RESTORATION_L2_DISCONNECTED: 'RESTORATION_L2_DISCONNECTED', RESTORATION_L2_ACCOUNT_CHANGED: 'RESTORATION_L2_ACCOUNT_CHANGED', RESTORATION_UNAUTHENTICATED: 'RESTORATION_UNAUTHENTICATED', } as const; export const MILESTONE_TITLES = [ `Connect ${c.layer2.conversationalName} wallet`, `Pick username`, `Save Card Space details`, `Create Card Space`, ]; export const WORKFLOW_VERSION = 2; class CreateSpaceWorkflow extends Workflow { @service declare router: RouterService; @service declare layer2Network: Layer2Network; @service declare hubAuthentication: HubAuthentication; name: WorkflowName = 'CARD_SPACE_CREATION'; version = WORKFLOW_VERSION; milestones = [ new Milestone({ title: MILESTONE_TITLES[0], postables: [ new WorkflowMessage({ message: `Hello, welcome to Card Space, we're happy to see you!`, }), new NetworkAwareWorkflowMessage({ message: `Looks like you’ve already connected your ${c.layer2.fullName} wallet, which you can see below. Please continue with the next step of this workflow.`, includeIf() { return this.hasLayer2Account; }, }), new NetworkAwareWorkflowMessage({ message: `To get started, connect your ${c.layer2.fullName} wallet via your Card Wallet mobile app. If you don’t have the app installed, please do so now.`, includeIf() { return !this.hasLayer2Account; }, }), new NetworkAwareWorkflowMessage({ message: `Once you have installed the app, open the app and add an existing wallet/account or create a new account. Scan this QR code with your account, which will connect it with Card Space.`, includeIf() { return !this.hasLayer2Account; }, }), new WorkflowCard({ cardName: 'LAYER2_CONNECT', componentName: 'card-pay/layer-two-connect-card', }), ], completedDetail: `${c.layer2.fullName} wallet connected`, }), new Milestone({ title: MILESTONE_TITLES[1], postables: [ // TODO // new WorkflowMessage({ // message: `It looks like you don’t have a prepaid card in your account. You will need one to pay the **100 SPEND ($1 USD)** Card Space creation fee. Please buy a prepaid card before you continue with this workflow.`, // }), // new WorkflowCard({ // cardName: 'PREPAID_CARD_PURCHASE_INSTRUCTIONS', // componentName: 'card-pay/prepaid-card-purchase-instructions', // }), new NetworkAwareWorkflowMessage({ message: `To store data in the Cardstack Hub, you need to authenticate using your Card Wallet. You only need to do this once per browser/device.`, includeIf() { return !this.isHubAuthenticated; }, }), new NetworkAwareWorkflowCard({ cardName: 'HUB_AUTH', componentName: 'card-pay/hub-authentication', includeIf(this: NetworkAwareWorkflowCard) { return !this.isHubAuthenticated; }, }), new WorkflowMessage({ message: `Please pick a username for your account. This is the name that will be shown to others when you communicate with them. If you like, you can upload a profile picture too.`, }), new WorkflowCard({ cardName: 'CARD_SPACE_USERNAME', componentName: 'card-space/create-space-workflow/username', }), ], completedDetail: `Username picked`, }), new Milestone({ title: MILESTONE_TITLES[2], postables: [ new WorkflowMessage({ message: `Nice choice!`, }), new WorkflowMessage({ message: `Now it's time to set up your space. The preview shows you how your space will be displayed to users who visit the Card Space org.`, }), new WorkflowCard({ cardName: 'CARD_SPACE_DETAILS', componentName: 'card-space/create-space-workflow/details', }), ], completedDetail: `Card Space details saved`, }), new Milestone({ title: MILESTONE_TITLES[3], postables: [ new WorkflowMessage({ message: `We have sent your URL reservation badge to your connected account (just check your Card Wallet mobile app).`, }), new WorkflowCard({ cardName: 'CARD_SPACE_BADGE', componentName: 'card-space/create-space-workflow/badge', }), new WorkflowMessage({ message: `On to the next step: You need to pay a small protocol fee to create your Card Space. Please select a prepaid card with a spendable balance from your ${c.layer2.fullName} wallet.`, }), new WorkflowCard({ cardName: 'CARD_SPACE_CONFIRM', componentName: 'card-space/create-space-workflow/confirm', }), new WorkflowMessage({ message: `Thank you for your payment.`, }), ], completedDetail: 'Card Space created', }), ]; epilogue = new PostableCollection([ new WorkflowMessage({ message: `This is the remaining balance on your prepaid card:`, }), // TODO // new WorkflowCard({ // cardName: 'EPILOGUE_PREPAID_CARD_BALANCE', // componentName: 'card-pay/prepaid-card-balance', // }), new WorkflowMessage({ message: `Congrats, you have created your Card Space!`, }), new WorkflowCard({ cardName: 'EPILOGUE_NEXT_STEPS', componentName: 'card-space/create-space-workflow/next-steps', }), ]); cancelationMessages = new PostableCollection([ // if we disconnect from layer 2 conditionalCancelationMessage({ forReason: FAILURE_REASONS.L2_DISCONNECTED, message: `It looks like your ${c.layer2.fullName} wallet got disconnected. If you still want to create a Card Space, please start again by connecting your wallet.`, }), // cancelation for changing accounts conditionalCancelationMessage({ forReason: FAILURE_REASONS.L2_ACCOUNT_CHANGED, message: 'It looks like you changed accounts in the middle of this workflow. If you still want to create a Card Space, please restart the workflow.', }), conditionalCancelationMessage({ forReason: FAILURE_REASONS.UNAUTHENTICATED, message: 'You are no longer authenticated. Please restart the workflow.', }), conditionalCancelationMessage({ forReason: FAILURE_REASONS.RESTORATION_UNAUTHENTICATED, message: 'You attempted to restore an unfinished workflow, but you are no longer authenticated. Please restart the workflow.', }), conditionalCancelationMessage({ forReason: FAILURE_REASONS.RESTORATION_L2_ACCOUNT_CHANGED, message: 'You attempted to restore an unfinished workflow, but you changed your Card Wallet address. Please restart the workflow.', }), conditionalCancelationMessage({ forReason: FAILURE_REASONS.RESTORATION_L2_DISCONNECTED, message: 'You attempted to restore an unfinished workflow, but your Card Wallet got disconnected. Please restart the workflow.', }), ...standardCancelationPostables(), ]); constructor(owner: unknown, workflowPersistenceId?: string) { super(owner, workflowPersistenceId); this.attachWorkflow(); } restorationErrors() { let { hubAuthentication, layer2Network } = this; let errors = super.restorationErrors(); if (!layer2Network.isConnected) { errors.push(FAILURE_REASONS.RESTORATION_L2_DISCONNECTED); } let persistedLayer2Address = this.session.getValue<string>( 'layer2WalletAddress' ); if ( layer2Network.isConnected && persistedLayer2Address && layer2Network.walletInfo.firstAddress !== persistedLayer2Address ) { errors.push(FAILURE_REASONS.RESTORATION_L2_ACCOUNT_CHANGED); } if (!hubAuthentication.isAuthenticated) { errors.push(FAILURE_REASONS.RESTORATION_UNAUTHENTICATED); } return errors; } beforeRestorationChecks() { return []; } } class CreateSpaceWorkflowComponent extends Component { @service declare layer2Network: Layer2Network; @service declare workflowPersistence: WorkflowPersistence; @service declare router: RouterService; @tracked workflow: CreateSpaceWorkflow | null = null; @tracked detailsEditFormShown: boolean = true; constructor(owner: unknown, args: {}) { super(owner, args); let workflowPersistenceId = this.router.currentRoute.queryParams['flow-id']!; let workflow = new CreateSpaceWorkflow( getOwner(this), workflowPersistenceId ); this.restore(workflow); } async restore(workflow: any) { await workflow.restore(); this.workflow = workflow; } @action onDisconnect() { this.workflow?.cancel(FAILURE_REASONS.L2_DISCONNECTED); } @action onAccountChanged() { this.workflow?.cancel(FAILURE_REASONS.L2_ACCOUNT_CHANGED); } } export default CreateSpaceWorkflowComponent;
the_stack
import { Signal } from 'signals' import { Log } from '../globals' import { defaults } from '../utils' import { NumberArray } from '../types' import { circularMean, arrayMean } from '../math/array-utils' import { lerp, spline } from '../math/math-utils' import Selection from '../selection/selection' import Superposition from '../align/superposition' import Structure from '../structure/structure' import AtomProxy from '../proxy/atom-proxy' import TrajectoryPlayer, { TrajectoryPlayerInterpolateType } from './trajectory-player' function centerPbc (coords: NumberArray, mean: number[], box: ArrayLike<number>) { if (box[ 0 ] === 0 || box[ 8 ] === 0 || box[ 4 ] === 0) { return } const n = coords.length const bx = box[ 0 ] const by = box[ 1 ] const bz = box[ 2 ] const mx = mean[ 0 ] const my = mean[ 1 ] const mz = mean[ 2 ] const fx = -mx + bx + bx / 2 const fy = -my + by + by / 2 const fz = -mz + bz + bz / 2 for (let i = 0; i < n; i += 3) { coords[ i + 0 ] = (coords[ i + 0 ] + fx) % bx coords[ i + 1 ] = (coords[ i + 1 ] + fy) % by coords[ i + 2 ] = (coords[ i + 2 ] + fz) % bz } } function removePbc (x: NumberArray, box: ArrayLike<number>) { if (box[ 0 ] === 0 || box[ 8 ] === 0 || box[ 4 ] === 0) { return } // ported from GROMACS src/gmxlib/rmpbc.c:rm_gropbc() // in-place const n = x.length for (let i = 3; i < n; i += 3) { for (let j = 0; j < 3; ++j) { const dist = x[ i + j ] - x[ i - 3 + j ] if (Math.abs(dist) > 0.9 * box[ j * 3 + j ]) { if (dist > 0) { for (let d = 0; d < 3; ++d) { x[ i + d ] -= box[ j * 3 + d ] } } else { for (let d = 0; d < 3; ++d) { x[ i + d ] += box[ j * 3 + d ] } } } } } return x } function removePeriodicity (x: NumberArray, box: ArrayLike<number>, mean: number[]) { if (box[ 0 ] === 0 || box[ 8 ] === 0 || box[ 4 ] === 0) { return } const n = x.length for (let i = 3; i < n; i += 3) { for (let j = 0; j < 3; ++j) { const f = (x[ i + j ] - mean[ j ]) / box[ j * 3 + j ] if (Math.abs(f) > 0.5) { x[ i + j ] -= box[ j * 3 + j ] * Math.round(f) } } } return x } function circularMean3 (indices: NumberArray, coords: NumberArray, box: ArrayLike<number>) { return [ circularMean(coords, box[ 0 ], 3, 0, indices), circularMean(coords, box[ 1 ], 3, 1, indices), circularMean(coords, box[ 2 ], 3, 2, indices) ] } function arrayMean3 (coords: NumberArray) { return [ arrayMean(coords, 3, 0), arrayMean(coords, 3, 1), arrayMean(coords, 3, 2) ] } function interpolateSpline (c: NumberArray, cp: NumberArray, cpp: NumberArray, cppp: NumberArray, t: number) { const m = c.length const coords = new Float32Array(m) for (let j0 = 0; j0 < m; j0 += 3) { const j1 = j0 + 1 const j2 = j0 + 2 coords[ j0 ] = spline(cppp[ j0 ], cpp[ j0 ], cp[ j0 ], c[ j0 ], t, 1) coords[ j1 ] = spline(cppp[ j1 ], cpp[ j1 ], cp[ j1 ], c[ j1 ], t, 1) coords[ j2 ] = spline(cppp[ j2 ], cpp[ j2 ], cp[ j2 ], c[ j2 ], t, 1) } return coords } function interpolateLerp (c: NumberArray, cp: NumberArray, t: number) { const m = c.length const coords = new Float32Array(m) for (let j0 = 0; j0 < m; j0 += 3) { const j1 = j0 + 1 const j2 = j0 + 2 coords[ j0 ] = lerp(cp[ j0 ], c[ j0 ], t) coords[ j1 ] = lerp(cp[ j1 ], c[ j1 ], t) coords[ j2 ] = lerp(cp[ j2 ], c[ j2 ], t) } return coords } /** * Trajectory parameter object. * @typedef {Object} TrajectoryParameters - parameters * * @property {Number} deltaTime - timestep between frames in picoseconds * @property {Number} timeOffset - starting time of frames in picoseconds * @property {String} sele - to restrict atoms used for superposition * @property {Boolean} centerPbc - center on initial frame * @property {Boolean} removePeriodicity - move atoms into the origin box * @property {Boolean} remo - try fixing periodic boundary discontinuities * @property {Boolean} superpose - superpose on initial frame */ /** * @example * trajectory.signals.frameChanged.add( function(i){ ... } ); * * @typedef {Object} TrajectorySignals * @property {Signal<Integer>} countChanged - when the frame count is changed * @property {Signal<Integer>} frameChanged - when the set frame is changed * @property {Signal<TrajectoryPlayer>} playerChanged - when the player is changed */ export interface TrajectoryParameters { deltaTime: number // timestep between frames in picoseconds timeOffset: number // starting time of frames in picoseconds sele: string // to restrict atoms used for superposition centerPbc: boolean // center on initial frame removePbc: boolean // move atoms into the origin box removePeriodicity: boolean // try fixing periodic boundary discontinuities superpose: boolean // superpose on initial frame } export interface TrajectorySignals { countChanged: Signal frameChanged: Signal playerChanged: Signal } /** * Base class for trajectories, tying structures and coordinates together * @interface */ class Trajectory { signals: TrajectorySignals = { countChanged: new Signal(), frameChanged: new Signal(), playerChanged: new Signal() } deltaTime: number timeOffset: number sele: string centerPbc: boolean removePbc: boolean removePeriodicity: boolean superpose: boolean name: string frame: number trajPath: string initialCoords: Float32Array structureCoords: Float32Array selectionIndices: NumberArray backboneIndices: NumberArray coords1: Float32Array coords2: Float32Array frameCache: { [k: number]: Float32Array } = {} loadQueue: { [k: number]: boolean } = {} boxCache: { [k: number]: ArrayLike<number> } = {} pathCache = {} frameCacheSize = 0 atomCount: number inProgress: boolean selection: Selection // selection to restrict atoms used for superposition structure: Structure player: TrajectoryPlayer private _frameCount = 0 private _currentFrame = -1 private _disposed = false /** * @param {String} trajPath - trajectory source * @param {Structure} structure - the structure object * @param {TrajectoryParameters} params - trajectory parameters */ constructor (trajPath: string, structure: Structure, params: Partial<TrajectoryParameters> = {}) { this.deltaTime = defaults(params.deltaTime, 0) this.timeOffset = defaults(params.timeOffset, 0) this.centerPbc = defaults(params.centerPbc, false) this.removePbc = defaults(params.removePbc, false) this.removePeriodicity = defaults(params.removePeriodicity, false) this.superpose = defaults(params.superpose, false) this.name = trajPath.replace(/^.*[\\/]/, '') this.trajPath = trajPath this.selection = new Selection( defaults(params.sele, 'backbone and not hydrogen') ) this.selection.signals.stringChanged.add(() => { this.selectionIndices = this.structure.getAtomIndices(this.selection)! this._resetCache() this._saveInitialCoords() this.setFrame(this._currentFrame) }) } /** * Number of frames in the trajectory */ get frameCount () { return this._frameCount } /** * Currently set frame of the trajectory */ get currentFrame () { return this._currentFrame } _init (structure: Structure) { this.setStructure(structure) this._loadFrameCount() this.setPlayer(new TrajectoryPlayer(this)) } _loadFrameCount () {} setStructure (structure: Structure) { this.structure = structure this.atomCount = structure.atomCount this.backboneIndices = this._getIndices( new Selection('backbone and not hydrogen') ) this._makeAtomIndices() this._saveStructureCoords() this.selectionIndices = this._getIndices(this.selection) this._resetCache() this._saveInitialCoords() this.setFrame(this._currentFrame) } _saveInitialCoords () { if (this.structure.hasCoords()) { this.initialCoords = new Float32Array(this.structureCoords) this._makeSuperposeCoords() } else if (this.frameCache[0]) { this.initialCoords = new Float32Array(this.frameCache[0]) this._makeSuperposeCoords() } else { this.loadFrame(0, () => this._saveInitialCoords()) } } _saveStructureCoords () { const p = { what: { position: true } } this.structureCoords = this.structure.getAtomData(p).position! } setSelection (string: string) { this.selection.setString(string) return this } _getIndices (selection: Selection) { let i = 0 const test = selection.test const indices: number[] = [] if (test) { this.structure.eachAtom((ap: AtomProxy) => { if (test(ap)) indices.push(i) i += 1 }) } return indices } _makeSuperposeCoords () { const n = this.selectionIndices.length * 3 this.coords1 = new Float32Array(n) this.coords2 = new Float32Array(n) const y = this.initialCoords const coords2 = this.coords2 for (let i = 0; i < n; i += 3) { const j = this.selectionIndices[ i / 3 ] * 3 coords2[ i + 0 ] = y[ j + 0 ] coords2[ i + 1 ] = y[ j + 1 ] coords2[ i + 2 ] = y[ j + 2 ] } } _makeAtomIndices () { Log.error('Trajectory._makeAtomIndices not implemented') } _resetCache () { this.frameCache = {} this.loadQueue = {} this.boxCache = {} this.pathCache = {} this.frameCacheSize = 0 this.initialCoords = new Float32Array(0) } setParameters (params: Partial<TrajectoryParameters> = {}) { let resetCache = false if (params.centerPbc !== undefined && params.centerPbc !== this.centerPbc) { this.centerPbc = params.centerPbc resetCache = true } if (params.removePeriodicity !== undefined && params.removePeriodicity !== this.removePeriodicity) { this.removePeriodicity = params.removePeriodicity resetCache = true } if (params.removePbc !== undefined && params.removePbc !== this.removePbc) { this.removePbc = params.removePbc resetCache = true } if (params.superpose !== undefined && params.superpose !== this.superpose) { this.superpose = params.superpose resetCache = true } this.deltaTime = defaults(params.deltaTime, this.deltaTime) this.timeOffset = defaults(params.timeOffset, this.timeOffset) if (resetCache) { this._resetCache() this.setFrame(this._currentFrame) } } /** * Check if a frame is available * @param {Integer|Integer[]} i - the frame index * @return {Boolean} frame availability */ hasFrame (i: number|number[]) { if (Array.isArray(i)) { return i.every(j => !!this.frameCache[j]) } else { return !!this.frameCache[i] } } /** * Set trajectory to a frame index * @param {Integer} i - the frame index * @param {Function} [callback] - fired when the frame has been set */ setFrame (i: number, callback?: Function) { if (i === undefined) return this this.inProgress = true // i = parseInt(i) // TODO if (i === -1 || this.frameCache[ i ]) { this._updateStructure(i) if (callback) callback() } else { this.loadFrame(i, () => { this._updateStructure(i) if (callback) callback() }) } return this } _interpolate (i: number, ip: number, ipp: number, ippp: number, t: number, type: TrajectoryPlayerInterpolateType) { const fc = this.frameCache let coords if (type === 'spline') { coords = interpolateSpline(fc[ i ], fc[ ip ], fc[ ipp ], fc[ ippp ], t) } else { coords = interpolateLerp(fc[ i ], fc[ ip ], t) } this.structure.updatePosition(coords) this._currentFrame = i this.signals.frameChanged.dispatch(i) } /** * Interpolated and set trajectory to frame indices * @param {Integer} i - the frame index * @param {Integer} ip - one before frame index * @param {Integer} ipp - two before frame index * @param {Integer} ippp - three before frame index * @param {Number} t - interpolation step [0,1] * @param {String} type - interpolation type, '', 'spline' or 'linear' * @param {Function} callback - fired when the frame has been set */ setFrameInterpolated (i: number, ip: number, ipp: number, ippp: number, t: number, type: TrajectoryPlayerInterpolateType, callback?: Function) { if (i === undefined) return this const fc = this.frameCache const iList: number[] = [] if (!fc[ ippp ]) iList.push(ippp) if (!fc[ ipp ]) iList.push(ipp) if (!fc[ ip ]) iList.push(ip) if (!fc[ i ]) iList.push(i) if (iList.length) { this.loadFrame(iList, () => { this._interpolate(i, ip, ipp, ippp, t, type) if (callback) callback() }) } else { this._interpolate(i, ip, ipp, ippp, t, type) if (callback) callback() } return this } /** * Load frame index * @param {Integer|Integer[]} i - the frame index * @param {Function} callback - fired when the frame has been loaded */ loadFrame (i: number|number[], callback?: Function) { if (Array.isArray(i)) { i.forEach(j => { if (!this.loadQueue[j] && !this.frameCache[j]) { this.loadQueue[j] = true this._loadFrame(j, () => { delete this.loadQueue[j] }) } }) } else { if (!this.loadQueue[i] && !this.frameCache[i]) { this.loadQueue[i] = true this._loadFrame(i, () => { delete this.loadQueue[i] if (callback) callback() }) } } } /** * Load frame index * @abstract * @param {Integer} i - the frame index * @param {Function} callback - fired when the frame has been loaded */ _loadFrame (i: number, callback?: Function) { Log.error('Trajectory._loadFrame not implemented', i, callback) } _updateStructure (i: number) { if (this._disposed) { console.error('updateStructure: traj disposed') return } if (i === -1) { if (this.structureCoords) { this.structure.updatePosition(this.structureCoords) } } else { this.structure.updatePosition(this.frameCache[ i ]) } this.structure.trajectory = { name: this.trajPath, frame: i } this._currentFrame = i this.inProgress = false this.signals.frameChanged.dispatch(i) } _doSuperpose (x: Float32Array) { const n = this.selectionIndices.length * 3 const coords1 = this.coords1 const coords2 = this.coords2 for (let i = 0; i < n; i += 3) { const j = this.selectionIndices[ i / 3 ] * 3 coords1[ i + 0 ] = x[ j + 0 ] coords1[ i + 1 ] = x[ j + 1 ] coords1[ i + 2 ] = x[ j + 2 ] } // TODO re-use superposition object const sp = new Superposition(coords1, coords2) sp.transform(x) } _process (i: number, box: ArrayLike<number>, coords: Float32Array, frameCount: number) { this._setFrameCount(frameCount) if (box) { if (this.backboneIndices.length > 0 && this.centerPbc) { const box2 = [ box[ 0 ], box[ 4 ], box[ 8 ] ] const circMean = circularMean3(this.backboneIndices, coords, box2) centerPbc(coords, circMean, box2) } if (this.removePeriodicity) { const mean = arrayMean3(coords) removePeriodicity(coords, box, mean) } if (this.removePbc) { removePbc(coords, box) } } if (this.selectionIndices.length > 0 && this.coords1 && this.superpose) { this._doSuperpose(coords) } this.frameCache[ i ] = coords this.boxCache[ i ] = box this.frameCacheSize += 1 } _setFrameCount (n: number) { if (n !== this._frameCount) { this._frameCount = n this.signals.countChanged.dispatch(n) } } /** * Dispose of the trajectory object * @return {undefined} */ dispose () { this._resetCache() // aid GC this._disposed = true if (this.player) this.player.stop() } /** * Set player for this trajectory * @param {TrajectoryPlayer} player - the player */ setPlayer (player: TrajectoryPlayer) { this.player = player this.signals.playerChanged.dispatch(player) } /** * Get time for frame * @param {Integer} i - frame index * @return {Number} time in picoseconds */ getFrameTime (i: number) { return this.timeOffset + i * this.deltaTime } } export default Trajectory
the_stack
import type { IBounds } from "../util/IBounds"; import type { IPoint } from "../util/IPoint"; import type { Pattern } from "../render/patterns/Pattern"; import type { Time } from "../util/Animation"; import type { Sprite } from "../render/Sprite"; import type { MultiDisposer, IDisposer } from "../util/Disposer"; import { Label } from "../render/Label"; import { PointedRectangle } from "../render/PointedRectangle"; import { Container, IContainerPrivate, IContainerSettings } from "./Container"; import { Percent } from "../util/Percent"; import { Color } from "../util/Color"; import * as $math from "../util/Math"; import * as $array from "../util/Array"; import * as $utils from "../util/Utils"; //import * as $utils from "../util/Utils"; import type { DataItem, IComponentDataItem } from "./Component"; export interface ITooltipSettings extends IContainerSettings { /** * Text to use for tooltip's label. */ labelText?: string /** * A direction of the tooltip pointer. * * https://www.amcharts.com/docs/v5/concepts/common-elements/tooltips/#Orientation */ pointerOrientation?: "left" | "right" | "up" | "down" | "vertical" | "horizontal"; /** * If set to `true` will use the same `fill` color for its background as * its `tooltipTarget`. * * @see {@link https://www.amcharts.com/docs/v5/concepts/common-elements/tooltips/#Colors} for more info * @defaul false */ getFillFromSprite?: boolean; /** * If set to `true` will use the same `fill` color as its `tooltipTarget`. * * @see {@link https://www.amcharts.com/docs/v5/concepts/common-elements/tooltips/#Colors} for more info * @defaul false */ getLabelFillFromSprite?: boolean; /** * If set to `true` will use the same `stroke` color as its `tooltipTarget`. * * @see {@link https://www.amcharts.com/docs/v5/concepts/common-elements/tooltips/#Colors} for more info * @default false */ getStrokeFromSprite?: boolean; /** * Scree bounds to constring tooltip within. */ bounds?: IBounds; /** * If set to `true` tooltip will adjust its text color for better visibility * on its background. * * @default true */ autoTextColor?: boolean; /** * Screen coordinates the tooltip show point to. */ pointTo?: IPoint; /** * Duration in milliseconds for tooltip position change, e.g. when tooltip * is jumping from one target to another. */ animationDuration?: number; /** * Easing function for tooltip animation. * * @see {@link https://www.amcharts.com/docs/v5/concepts/animations/#Easing_functions} for more info */ animationEasing?: (t: Time) => Time; /** * A target element tooltip is shown fow. */ tooltipTarget?: Sprite; } export interface ITooltipPrivate extends IContainerPrivate { } /** * Creates a tooltip. * * @see {@link https://www.amcharts.com/docs/v5/concepts/common-elements/tooltips/} for more info * @important */ export class Tooltip extends Container { protected _arrangeDisposer: MultiDisposer | undefined; public _fx: number = 0; public _fy: number = 0; declare public _settings: ITooltipSettings; declare public _privateSettings: ITooltipPrivate; protected _label!: Label; public static className: string = "Tooltip"; public static classNames: Array<string> = Container.classNames.concat([Tooltip.className]); protected _fillDp: IDisposer | undefined; protected _strokeDp: IDisposer | undefined; protected _labelDp: IDisposer | undefined; protected _w: number = 0; protected _h: number = 0; protected _afterNew() { this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["tooltip"]); super._afterNew(); this.set("background", PointedRectangle.new(this._root, { themeTags: ["tooltip", "background"] })); this._label = this.children.push(Label.new(this._root, {})); this._disposers.push(this._label.events.on("boundschanged", () => { this._updateBackground(); })) this.on("bounds", () => { this._updateBackground(); }) this._updateTextColor(); this._root.tooltipContainer.children.push(this); this.hide(0); this._root._tooltips.push(this); } /** * A [[Label]] element for the tooltip. * * @readonly * @return Label */ public get label(): Label { return this._label; } /** * Permanently disposes the tooltip. */ public dispose() { super.dispose(); $array.remove(this._root._tooltips, this); } public _updateChildren() { super._updateChildren(); const labelText = this.get("labelText"); if (labelText != null) { this.label.set("text", this.get("labelText")); } } public _changed() { super._changed(); if (this.isDirty("pointTo")) { // can't compare to previous, as sometimes pointTo is set twice (when pointer moves, so the position won't be udpated) this._updateBackground(); } if (this.isDirty("tooltipTarget")) { this.updateBackgroundColor(); } } protected _onShow() { super._onShow(); this.updateBackgroundColor(); } public updateBackgroundColor() { let tooltipTarget = this.get("tooltipTarget"); const background = this.get("background"); let fill: Color | undefined; let stroke: Color | undefined; if (tooltipTarget && background) { fill = tooltipTarget.get("fill" as any); stroke = tooltipTarget.get("stroke" as any); if (fill == null) { fill = stroke; } if (this.get("getFillFromSprite")) { if (this._fillDp) { this._fillDp.dispose(); } if (fill != null) { background.set("fill", fill as any); } this._fillDp = tooltipTarget.on("fill" as any, (fill) => { if (fill != null) { background.set("fill", fill as any); this._updateTextColor(fill); } }) } if (this.get("getStrokeFromSprite")) { if (this._strokeDp) { this._strokeDp.dispose(); } if (fill != null) { background.set("stroke", fill as any); } this._strokeDp = tooltipTarget.on("fill" as any, (fill) => { if (fill != null) { background.set("stroke", fill as any); } }) } if (this.get("getLabelFillFromSprite")) { if (this._labelDp) { this._labelDp.dispose(); } if (fill != null) { this.label.set("fill", fill as any); } this._labelDp = tooltipTarget.on("fill" as any, (fill) => { if (fill != null) { this.label.set("fill", fill as any); } }) } } this._updateTextColor(fill); } protected _updateTextColor(fill?: Color | Pattern) { if (this.get("autoTextColor")) { if (fill == null) { fill = this.get("background")!.get("fill") as Color; } if (fill == null) { fill = this._root.interfaceColors.get("background"); } if (fill instanceof Color) { this.label.set("fill", Color.alternative(fill, this._root.interfaceColors.get("alternativeText"), this._root.interfaceColors.get("text"))); } } } public _setDataItem(dataItem?: DataItem<IComponentDataItem>): void { super._setDataItem(dataItem); this.label._setDataItem(dataItem); } protected _updateBackground() { super.updateBackground(); const parent = this._root.container; if (parent) { let cw = 0.5; let ch = 0.5; let centerX = this.get("centerX"); if (centerX instanceof Percent) { cw = centerX.value; } let centerY = this.get("centerY"); if (centerY instanceof Percent) { ch = centerY.value; } let parentW = parent.width(); let parentH = parent.height(); const bounds = this.get("bounds", { left: 0, top: 0, right: parentW, bottom: parentH }); this._updateBounds(); let w = this.width(); let h = this.height(); // use old w and h,as when tooltip is hidden, these are 0 and unneeded animation happens if (w === 0) { w = this._w; } if (h === 0) { h = this._h; } let pointTo = this.get("pointTo", { x: parentW / 2, y: parentH / 2 }); let x = pointTo.x; let y = pointTo.y; let pointerOrientation = this.get("pointerOrientation"); let background = this.get("background"); let pointerLength = 0; if (background instanceof PointedRectangle) { pointerLength = background.get("pointerLength", 0); } let pointerX = 0; let pointerY = 0; let boundsW = bounds.right - bounds.left; let boundsH = bounds.bottom - bounds.top; // horizontal if (pointerOrientation == "horizontal" || pointerOrientation == "left" || pointerOrientation == "right") { if (pointerOrientation == "horizontal") { if (x > bounds.left + boundsW / 2) { x -= (w * (1 - cw) + pointerLength); } else { x += (w * cw + pointerLength); } } else if (pointerOrientation == "left") { x += (w * (1 - cw) + pointerLength); } else { x -= (w * cw + pointerLength); } } // vertical pointer else { if (pointerOrientation == "vertical") { if (y > bounds.top + h / 2 + pointerLength) { y -= (h * (1 - ch) + pointerLength); } else { y += (h * ch + pointerLength); } } else if (pointerOrientation == "down") { y -= (h * (1 - ch) + pointerLength); } else { y += (h * ch + pointerLength); } } x = $math.fitToRange(x, bounds.left + w * cw, bounds.left + boundsW - w * (1 - cw)); y = $math.fitToRange(y, bounds.top + h * ch, bounds.top + boundsH - h * (1 - ch)); pointerX = pointTo.x - x + w * cw; pointerY = pointTo.y - y + h * ch; this._fx = x; this._fy = y; const animationDuration = this.get("animationDuration", 0); if (animationDuration > 0 && this.get("visible") && this.get("opacity") > 0.1) { const animationEasing = this.get("animationEasing"); this.animate({ key: "x", to: x, duration: animationDuration, easing: animationEasing }); this.animate({ key: "y", to: y, duration: animationDuration, easing: animationEasing }); } else { this.set("x", x); this.set("y", y); } if (background instanceof PointedRectangle) { background.set("pointerX", pointerX); background.set("pointerY", pointerY); } if (w > 0) { this._w = w; } if (h > 0) { this._h = h; } } } }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { ConnectorModel } from '../../../src/diagram/objects/connector-model'; import { BezierSegment } from '../../../src/diagram/objects/connector'; import { NodeModel, BasicShapeModel } from '../../../src/diagram/objects/node-model'; import { Segments, ConnectorConstraints } from '../../../src/diagram/enum/enum'; import { MouseEvents } from './mouseevents.spec'; import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec'; /** * Connector Constraints spec */ describe('Diagram Control', () => { describe('Conectors with Constraints', () => { let diagram: Diagram; let ele: HTMLElement; let mouseEvents: MouseEvents = new MouseEvents(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 100, y: 100 }, targetPoint: { x: 200, y: 200 } }; let connector2: ConnectorModel = { id: 'connector2', type: 'Straight', sourcePoint: { x: 300, y: 100 }, targetPoint: { x: 300, y: 200 } }; let connector3: ConnectorModel = { id: 'connector3', type: 'Orthogonal', sourcePoint: { x: 400, y: 100 }, targetPoint: { x: 500, y: 200 } }; let connector4: ConnectorModel = { id: 'connector4', type: 'Orthogonal', sourcePoint: { x: 600, y: 100 }, targetPoint: { x: 700, y: 200 } }; let connector5: ConnectorModel = { id: 'connector5', type: 'Straight', sourcePoint: { x: 700, y: 100 }, targetPoint: { x: 700, y: 200 } }; let connector6: ConnectorModel = { id: 'connector6', type: 'Straight', sourcePoint: { x: 900, y: 100 }, targetPoint: { x: 900, y: 200 } }; let connector7: ConnectorModel = { id: 'connector7', type: 'Straight', sourcePoint: { x: 900, y: 100 }, targetPoint: { x: 900, y: 200 } }; let connector8: ConnectorModel = { id: 'connector8', type: 'Bezier', constraints:ConnectorConstraints.Default&~ConnectorConstraints.DragSourceEnd&~ConnectorConstraints.DragTargetEnd, sourcePoint: { x: 100, y: 300 }, targetPoint: { x: 200, y: 400 } }; diagram = new Diagram({ width: '1000px', height: '700px', connectors: [connector1, connector2, connector3, connector4, connector5, connector6, connector7,connector8] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking connector constraints - Select ', (done: Function) => { diagram.connectors[0].constraints = ConnectorConstraints.Default; diagram.connectors[1].constraints = ConnectorConstraints.Default & ~ConnectorConstraints.Select; diagram.connectors[2].constraints = ConnectorConstraints.Interaction & ~ConnectorConstraints.Select; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); for (let i = 0; i < 3; i++) { switch (i) { case 0: mouseEvents.clickEvent(diagramCanvas, 200 + 8, 198 + 8); expect(diagram.selectedItems.connectors.length === 1 && diagram.selectedItems.connectors[0].id === 'connector1').toBe(true); done(); break; case 1: mouseEvents.clickEvent(diagramCanvas, 300 + 8, 198 + 8); expect(diagram.selectedItems.connectors.length === 0).toBe(true) done(); break; case 2: mouseEvents.clickEvent(diagramCanvas, 500 + 8, 198 + 8); expect(diagram.selectedItems.connectors.length === 0).toBe(true) done(); break; } } }); it('Checking connector constraints - Drag ', (done: Function) => { diagram.connectors[0].constraints = ConnectorConstraints.Default; diagram.connectors[1].constraints = ConnectorConstraints.Default & ~ConnectorConstraints.Drag; diagram.connectors[2].constraints = ConnectorConstraints.Interaction & ~ConnectorConstraints.Drag; let conn, tx, ty, sourcePointx, sourcePointy, targetPointx, targetPointy; for (let i = 0; i < 3; i++) { conn = diagram.connectors[i]; tx = 10; ty = 10; sourcePointx = diagram.connectors[i].sourcePoint.x; sourcePointy = diagram.connectors[i].sourcePoint.y; targetPointx = diagram.connectors[i].targetPoint.x; targetPointy = diagram.connectors[i].targetPoint.y; diagram.drag(conn, tx, ty); switch (i) { case 0: expect(diagram.connectors[0].sourcePoint.x === sourcePointx + tx && diagram.connectors[0].sourcePoint.y === sourcePointy + ty && diagram.connectors[0].targetPoint.x === targetPointx + tx && diagram.connectors[0].targetPoint.y === targetPointy + ty).toBe(true) done(); break; case 1: expect(diagram.connectors[1].sourcePoint.x != sourcePointx + tx && diagram.connectors[1].sourcePoint.y != sourcePointy + ty && diagram.connectors[1].targetPoint.x != targetPointx + tx && diagram.connectors[1].targetPoint.y != targetPointy + ty).toBe(true) done(); break; case 2: expect(diagram.connectors[2].sourcePoint.x != sourcePointx + tx && diagram.connectors[2].sourcePoint.x != sourcePointx + tx && diagram.connectors[2].sourcePoint.x != sourcePointx + tx && diagram.connectors[2].sourcePoint.x != sourcePointx + tx).toBe(true) done(); break; } } }); it('Checking connector constraints - DragSourceEnd ', (done: Function) => { diagram.connectors[0].constraints = ConnectorConstraints.Default; diagram.connectors[1].constraints = ConnectorConstraints.Default & ~ConnectorConstraints.DragSourceEnd; diagram.connectors[2].constraints = ConnectorConstraints.Interaction & ~ConnectorConstraints.DragSourceEnd; let conn, tx, ty, sourcePointx, sourcePointy; for (let i = 0; i < 3; i++) { conn = diagram.connectors[i]; tx = 10; ty = 10; sourcePointx = diagram.connectors[i].sourcePoint.x; sourcePointy = diagram.connectors[i].sourcePoint.y; diagram.dragSourceEnd(conn, tx, ty); switch (i) { case 0: expect(diagram.connectors[0].sourcePoint.x === sourcePointx + tx && diagram.connectors[0].sourcePoint.y === sourcePointy + ty).toBe(true) done(); break; case 1: expect(diagram.connectors[1].sourcePoint.x != sourcePointx + tx && diagram.connectors[1].sourcePoint.y != sourcePointy + ty).toBe(true) done(); break; case 2: expect(diagram.connectors[2].sourcePoint.x != sourcePointx + tx && diagram.connectors[2].sourcePoint.y != sourcePointy + ty).toBe(true) done(); break; } } }); it('Checking connector constraints - DragTargetEnd ', (done: Function) => { diagram.connectors[0].constraints = ConnectorConstraints.Default; diagram.connectors[1].constraints = ConnectorConstraints.Default & ~ConnectorConstraints.DragTargetEnd; diagram.connectors[2].constraints = ConnectorConstraints.Interaction & ~ConnectorConstraints.DragTargetEnd; let conn, tx, ty, targetPointx, targetPointy; for (let i = 0; i < 3; i++) { conn = diagram.connectors[i]; tx = 10; ty = 10; targetPointx = diagram.connectors[i].targetPoint.x; targetPointy = diagram.connectors[i].targetPoint.y; diagram.dragTargetEnd(conn, tx, ty); switch (i) { case 0: expect(diagram.connectors[0].targetPoint.x === targetPointx + tx && diagram.connectors[0].targetPoint.y === targetPointy + ty).toBe(true) done(); break; case 1: expect(diagram.connectors[1].targetPoint.x != targetPointx + tx && diagram.connectors[1].targetPoint.y != targetPointy + ty).toBe(true) done(); break; case 2: expect(diagram.connectors[2].targetPoint.x != targetPointx + tx && diagram.connectors[2].targetPoint.y != targetPointy + ty).toBe(true) done(); break; } } }); it('Checking connector constraints with PointerEvents ', (done: Function) => { diagram.connectors[3].constraints = ConnectorConstraints.Default; diagram.connectors[4].constraints = ConnectorConstraints.Default; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.clickEvent(diagramCanvas, 700 + diagram.element.offsetLeft, 100 + diagram.element.offsetTop); expect(diagram.selectedItems.connectors[0].id === 'connector5').toBe(true) done(); }); it('Checking connector constraints without PointerEvents ', (done: Function) => { diagram.connectors[5].constraints = ConnectorConstraints.Default; diagram.connectors[6].constraints = ConnectorConstraints.Default & ~ConnectorConstraints.PointerEvents; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.clickEvent(diagramCanvas, 900 + diagram.element.offsetLeft, 100 + diagram.element.offsetTop); expect(diagram.selectedItems.connectors[0].id === 'connector6').toBe(true) done(); }); it('Checking connector constraints - Delete ', (done: Function) => { diagram.clearSelection(); diagram.selectedItems.connectors = []; diagram.selectedItems.nodes = []; diagram.connectors[0].constraints = ConnectorConstraints.Default; diagram.connectors[1].constraints = ConnectorConstraints.Default & ~ConnectorConstraints.Delete; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); let conns; for (let i = 0; i < 3; i++) { switch (i) { case 0: conns = diagram.connectors.length; diagram.remove(diagram.connectors[0]); expect(diagram.connectors.length != conns).toBe(true) done(); break; case 1: conns = diagram.connectors.length; diagram.remove(diagram.connectors[1]); expect(diagram.connectors.length === conns).toBe(true) done(); break; } } }); it('Checking checking bezier source end target end constrants ', (done: Function) => { var diagramCanvas = document.getElementById(diagram.element.id + 'content'); var mouseEvents = new MouseEvents(); diagram.select([diagram.connectors[6]]); mouseEvents.dragAndDropEvent(diagramCanvas, 150, 298, 155, 302); mouseEvents.dragAndDropEvent(diagramCanvas, 154, 409, 160, 425); var connectors = diagram.selectedItems.connectors[0]; expect(connectors === undefined).toBe(true) done(); }) it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); });
the_stack
import { Workbook } from './../src/workbook'; import { Utils } from './../spec/utils.spec'; describe('CellStyle', () => { // afterEach(function () { // sleep(3000); // }); // function sleep(millSecs: any) { // let date: any = new Date(); // let curDate: any = null; // do { curDate = new Date(); } // while (curDate - date < millSecs); // } it('GlobalStyle', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Tahoma', fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->2*/{ name: 'Custom Heading', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->3*/{ name: 'Custom H2', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->4*/{ name: 'Custom H3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: '$#,###.00' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true } }, { index: 2, value: 20, style: { name: 'Tahoma' } }] }, { index: 2, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true } }, { index: 2, value: 'Custom H2', style: { name: 'Custom H2' } }] }, { index: 3, cells: [{ index: 1, value: 10, style: { wrapText: true } }, { index: 2, value: 'Custom Heading', style: { name: 'Custom Heading', fontName: 'Tahoma' } }] }, { index: 4, cells: [{ index: 1, value: 10, style: { fontColor: '#C67878' } }, { index: 2, value: 'Custom H3 ', style: { name: 'Custom H3' } }] }, { index: 5, cells: [{ index: 1, value: 10, style: { backColor: '#C67878' } }, { index: 2, value: 'Custom H2', style: { name: 'Custom H2', fontName: 'Tahoma' } }] }, { index: 6, cells: [{ index: 1, value: 10, style: { backColor: '#C67878' } }] }, { index: 7, cells: [{ index: 4, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'right', vAlign: 'top' } }] }, { index: 8, cells: [{ index: 1, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'right', vAlign: 'top' } }] }, { index: 10, cells: [{ index: 3, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'center', vAlign: 'center' } }] }, { index: 12, cells: [{ index: 4, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'center', vAlign: 'center' } }] }, { index: 13, cells: [{ index: 7, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'fill', vAlign: 'justify' } }] }, { index: 16, cells: [{ index: 3, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'fill', vAlign: 'justify' } }] }, { index: 18, cells: [{ index: 9, value: 'erterterrrrrrrrrrrrrrrrrrrrrrrrr', style: { wrapText: true, hAlign: 'fill', vAlign: 'justify' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'globalStyle.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('GlobalStyleDuplicate', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Tahoma', fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->2*/{ name: 'Custom Heading', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->3*/{ name: 'Custom H2', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->4*/{ name: 'Custom H3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: '$#,###.00' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 20, style: { name: 'Custom H2' } }] }, { index: 2, cells: [{ index: 1, value: 'Custom H2', style: { name: 'Custom H2' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'GlobalStyleDuplicate.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('GlobalStyle-1', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ { name: 'Custom H2', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: '$#,###.00' } ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 20, style: { name: 'Custom H2' } }, { index: 2, value: 'commonStyle', style: { fontName: 'Tahoma', fontSize: 20, fontColor: '#C67878', backColor: '#C67878', wrapText: true, hAlign: 'right', vAlign: 'top', numberFormat: 'yyyy-mm-dd' } }] }, { index: 2, cells: [{ index: 1, value: 'Custom H2', style: { name: 'Custom H2' } }, { index: 2, value: 'commonStyle', style: { fontName: 'Tahoma', fontSize: 20, fontColor: '#C67878', backColor: '#C67878', wrapText: true, hAlign: 'right', vAlign: 'top', numberFormat: 'yyyy-mm-dd' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'globalStyle-1.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('GlobalStyleWithouName', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->2*/{ fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->3*/{ name: 'Custom H2', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->4*/{ name: 'Custom H3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: '$#,###.00' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, value: 20, style: { name: 'Custom H2' } }] }, { index: 2, cells: [{ index: 1, value: 'Custom H2', style: { name: 'Custom H2' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'GlobalStyleWithouName.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('GlobalStyle-wrongName', (done) => { let book: Workbook = new Workbook({ styles: [{ name: 'check', fontName: 'Arial' }], worksheets: [{ rows: [{ index: 1, cells: [{ index: 1, style: { name: 'check1' } }] }] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'GlobalStyle-wrongName.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('GlobalStyle-withoutvalue', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Tahoma', fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->2*/{ name: 'Custom Heading', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->3*/{ name: 'Custom H2', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->4*/{ name: 'Custom H3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: '$#,###.00' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, style: { name: 'Custom H2' } }, { index: 5, style: { name: 'Tahoma' } }] }, { index: 2, cells: [{ index: 1, style: { name: 'Custom H3' } }, { index: 10, style: { name: 'Custom Heading' } }] }, ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'globalStyle-withoutvalue.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('GlobalStyle-Numberformat', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ /*Style ->1*/{ name: 'Tahoma', fontColor: '#C67878', fontName: 'Tahoma', fontSize: 20, italic: true, bold: true, underline: true, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->2*/{ name: 'Custom Heading', fontName: 'Arial', fontSize: 20, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->3*/{ name: 'Custom H2', fontName: 'Arial', fontSize: 18, wrapText: true, numberFormat: '$#,###.00' }, /*Style ->4*/{ name: 'Custom H3', fontName: 'Arial', fontSize: 16, wrapText: true, numberFormat: '$#,###.00' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, style: { numberFormat: 'C' } }, { index: 2, style: { numberFormat: 'C' } }] } ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'globalStyle-numberFormat.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('GlobalStyle-duplicateHeader', (done) => { try { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ { name: 'duplicate', fontName: 'Arial', fontSize: '20', wrapText: true, backColor: '#C67890' }, { name: 'duplicate1', fontName: 'Arial', fontSize: '20', wrapText: true, backColor: '#C67890' }, { name: 'duplicate1', fontName: 'Arial', fontSize: '20', wrapText: true, backColor: '#C67890' }, // { name: 'duplicate', fontName: 'Arial', fontSize: '20', wrapText: true, backColor: '#C67896' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [{ index: 1, style: { name: 'duplicate' } }] } ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'globalStyle-duplicateHeader.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); } catch (error) { expect('Style name duplicate1 is already existed').toEqual(error.message); done(); } }); it('GlobalStyle-duplicateStylee', (done) => { let book: Workbook = new Workbook({ /*Global Styles*/styles: [ { name: 'norm', fontName: 'Arial', fontSize: '20', wrapText: true, backColor: '#C67890' }, { name: 'duplicate', fontName: 'Arial', fontSize: '20', wrapText: true }, { name: 'duplicate1', fontName: 'Arial', fontSize: '20', wrapText: true }, // { name: 'duplicate', fontName: 'Arial', fontSize: '20', wrapText: true, backColor: '#C67896' }, ], worksheets: [ { name: 'CellStyle', rows: [ { index: 1, cells: [ { index: 1, value: 'A1', style: { name: 'duplicate' } }, { index: 2, value: 'B1', style: { fontSize: 10 } }, { index: 3, value: 'C1', style: { name: 'duplicate1' } }, { index: 4, value: 10, style: { name: 'norm' } } ] } ], }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'GlobalStyle-duplicateStylee.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); });
the_stack
namespace gdjs { /** Represents a color in RGB Format */ export type RGBColor = { /** The Red component of the color, from 0 to 255. */ r: integer; /** The Green component of the color, from 0 to 255. */ g: integer; /** The Blue component of the color, from 0 to 255. */ b: integer; }; /** Initial properties for a for {@link gdjs.ShapePainterRuntimeObject}. */ export type ShapePainterObjectDataType = { /** The color (in RGB format) of the inner part of the painted shape */ fillColor: RGBColor; /** The color (in RGB format) of the outline of the painted shape */ outlineColor: RGBColor; /** The opacity of the inner part of the painted shape, from 0 to 255 */ fillOpacity: float; /** The opacity of the outline of the painted shape, from 0 to 255 */ outlineOpacity: float; /** The size of the outline of the painted shape, in pixels. */ outlineSize: float; /** Use absolute coordinates? */ absoluteCoordinates: boolean; /** Clear the previous render before the next draw? */ clearBetweenFrames: boolean; }; export type ShapePainterObjectData = ObjectData & ShapePainterObjectDataType; /** * The ShapePainterRuntimeObject allows to draw graphics shapes on screen. */ export class ShapePainterRuntimeObject extends gdjs.RuntimeObject { _fillColor: integer; _outlineColor: integer; _fillOpacity: float; _outlineOpacity: float; _outlineSize: float; _absoluteCoordinates: boolean; _clearBetweenFrames: boolean; _renderer: gdjs.ShapePainterRuntimeObjectRenderer; /** * @param runtimeScene The scene the object belongs to. * @param shapePainterObjectData The initial properties of the object */ constructor( runtimeScene: gdjs.RuntimeScene, shapePainterObjectData: ShapePainterObjectData ) { super(runtimeScene, shapePainterObjectData); this._fillColor = parseInt( gdjs.rgbToHex( shapePainterObjectData.fillColor.r, shapePainterObjectData.fillColor.g, shapePainterObjectData.fillColor.b ), 16 ); this._outlineColor = parseInt( gdjs.rgbToHex( shapePainterObjectData.outlineColor.r, shapePainterObjectData.outlineColor.g, shapePainterObjectData.outlineColor.b ), 16 ); this._fillOpacity = shapePainterObjectData.fillOpacity; this._outlineOpacity = shapePainterObjectData.outlineOpacity; this._outlineSize = shapePainterObjectData.outlineSize; this._absoluteCoordinates = shapePainterObjectData.absoluteCoordinates; this._clearBetweenFrames = shapePainterObjectData.clearBetweenFrames; this._renderer = new gdjs.ShapePainterRuntimeObjectRenderer( this, runtimeScene ); // *ALWAYS* call `this.onCreated()` at the very end of your object constructor. this.onCreated(); } getRendererObject() { return this._renderer.getRendererObject(); } updateFromObjectData( oldObjectData: ShapePainterObjectData, newObjectData: ShapePainterObjectData ): boolean { if ( oldObjectData.fillColor.r !== newObjectData.fillColor.r || oldObjectData.fillColor.g !== newObjectData.fillColor.g || oldObjectData.fillColor.b !== newObjectData.fillColor.b ) { this.setFillColor( '' + newObjectData.fillColor.r + ';' + newObjectData.fillColor.g + ';' + newObjectData.fillColor.b ); } if ( oldObjectData.outlineColor.r !== newObjectData.outlineColor.r || oldObjectData.outlineColor.g !== newObjectData.outlineColor.g || oldObjectData.outlineColor.b !== newObjectData.outlineColor.b ) { this.setOutlineColor( '' + newObjectData.outlineColor.r + ';' + newObjectData.outlineColor.g + ';' + newObjectData.outlineColor.b ); } if (oldObjectData.fillOpacity !== newObjectData.fillOpacity) { this.setFillOpacity(newObjectData.fillOpacity); } if (oldObjectData.outlineOpacity !== newObjectData.outlineOpacity) { this.setOutlineOpacity(newObjectData.outlineOpacity); } if (oldObjectData.outlineSize !== newObjectData.outlineSize) { this.setOutlineSize(newObjectData.outlineSize); } if ( oldObjectData.absoluteCoordinates !== newObjectData.absoluteCoordinates ) { this._absoluteCoordinates = newObjectData.absoluteCoordinates; this._renderer.updateXPosition(); this._renderer.updateYPosition(); } if ( oldObjectData.clearBetweenFrames !== newObjectData.clearBetweenFrames ) { this._clearBetweenFrames = newObjectData.clearBetweenFrames; } return true; } stepBehaviorsPreEvents(runtimeScene: gdjs.RuntimeScene) { //We redefine stepBehaviorsPreEvents just to clear the graphics before running events. if (this._clearBetweenFrames) { this.clear(); } super.stepBehaviorsPreEvents(runtimeScene); } /** * Clear the graphics. */ clear() { this._renderer.clear(); } getVisibilityAABB() { return this._absoluteCoordinates ? null : this.getAABB(); } drawRectangle(x1: float, y1: float, x2: float, y2: float) { this._renderer.drawRectangle(x1, y1, x2, y2); } drawCircle(x: float, y: float, radius: float) { this._renderer.drawCircle(x, y, radius); } drawLine(x1: float, y1: float, x2: float, y2: float, thickness: float) { this._renderer.drawLine(x1, y1, x2, y2, thickness); } drawLineV2(x1: float, y1: float, x2: float, y2: float, thickness: float) { this._renderer.drawLineV2(x1, y1, x2, y2, thickness); } drawEllipse(centerX: float, centerY: float, width: float, height: float) { this._renderer.drawEllipse(centerX, centerY, width, height); } drawRoundedRectangle( startX1: float, startY1: float, endX2: float, endY2: float, radius: float ) { this._renderer.drawRoundedRectangle( startX1, startY1, endX2, endY2, radius ); } drawStar( centerX: float, centerY: float, points: float, radius: float, innerRadius: float, rotation: float ) { this._renderer.drawStar( centerX, centerY, points, radius, innerRadius, rotation ); } drawArc( centerX: float, centerY: float, radius: float, startAngle: float, endAngle: float, anticlockwise: boolean, closePath: boolean ) { this._renderer.drawArc( centerX, centerY, radius, startAngle, endAngle, anticlockwise, closePath ); } drawBezierCurve( x1: float, y1: float, cpX: float, cpY: float, cpX2: float, cpY2: float, x2: float, y2: float ) { this._renderer.drawBezierCurve(x1, y1, cpX, cpY, cpX2, cpY2, x2, y2); } drawQuadraticCurve( x1: float, y1: float, cpX: float, cpY: float, x2: float, y2: float ) { this._renderer.drawQuadraticCurve(x1, y1, cpX, cpY, x2, y2); } beginFillPath(x1: float, y1: float) { this._renderer.beginFillPath(); this._renderer.drawPathMoveTo(x1, y1); } endFillPath() { this._renderer.endFillPath(); } drawPathMoveTo(x1: float, y1: float) { this._renderer.drawPathMoveTo(x1, y1); } drawPathLineTo(x1: float, y1: float) { this._renderer.drawPathLineTo(x1, y1); } drawPathBezierCurveTo( cpX: float, cpY: float, cpX2: float, cpY2: float, toX: float, toY: float ) { this._renderer.drawPathBezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY); } drawPathArc( cx: float, cy: float, radius: float, startAngle: float, endAngle: float, anticlockwise: boolean ) { this._renderer.drawPathArc( cx, cy, radius, startAngle, endAngle, anticlockwise ); } drawPathQuadraticCurveTo(cpX: float, cpY: float, toX: float, toY: float) { this._renderer.drawPathQuadraticCurveTo(cpX, cpY, toX, toY); } closePath() { this._renderer.closePath(); } setClearBetweenFrames(value: boolean): void { this._clearBetweenFrames = value; } isClearedBetweenFrames(): boolean { return this._clearBetweenFrames; } setCoordinatesRelative(value: boolean): void { this._absoluteCoordinates = !value; } areCoordinatesRelative(): boolean { return !this._absoluteCoordinates; } /** * * @param rgbColor semicolon separated decimal values */ setFillColor(rgbColor: string): void { const colors = rgbColor.split(';'); if (colors.length < 3) { return; } this._fillColor = parseInt( gdjs.rgbToHex( parseInt(colors[0], 10), parseInt(colors[1], 10), parseInt(colors[2], 10) ), 16 ); } getFillColorR(): integer { return gdjs.hexNumberToRGB(this._fillColor).r; } getFillColorG(): integer { return gdjs.hexNumberToRGB(this._fillColor).g; } getFillColorB(): integer { return gdjs.hexNumberToRGB(this._fillColor).b; } /** * * @param rgbColor semicolon separated decimal values */ setOutlineColor(rgbColor: string): void { const colors = rgbColor.split(';'); if (colors.length < 3) { return; } this._outlineColor = parseInt( gdjs.rgbToHex( parseInt(colors[0], 10), parseInt(colors[1], 10), parseInt(colors[2], 10) ), 16 ); this._renderer.updateOutline(); } getOutlineColorR(): integer { return gdjs.hexNumberToRGB(this._outlineColor).r; } getOutlineColorG(): integer { return gdjs.hexNumberToRGB(this._outlineColor).g; } getOutlineColorB(): integer { return gdjs.hexNumberToRGB(this._outlineColor).b; } setOutlineSize(size: float): void { this._outlineSize = size; this._renderer.updateOutline(); } getOutlineSize() { return this._outlineSize; } /** * * @param opacity from 0 to 255 */ setFillOpacity(opacity: float): void { this._fillOpacity = opacity; } /** * * @returns an opacity value from 0 to 255. */ getFillOpacity() { return this._fillOpacity; } /** * * @param opacity from 0 to 255 */ setOutlineOpacity(opacity: float): void { this._outlineOpacity = opacity; this._renderer.updateOutline(); } /** * * @returns an opacity value from 0 to 255. */ getOutlineOpacity() { return this._outlineOpacity; } setX(x: float): void { if (x === this.x) { return; } super.setX(x); this._renderer.updateXPosition(); } setY(y: float): void { if (y === this.y) { return; } super.setY(y); this._renderer.updateYPosition(); } getWidth(): float { return 32; } getHeight(): float { return 32; } } gdjs.registerObject( 'PrimitiveDrawing::Drawer', gdjs.ShapePainterRuntimeObject ); ShapePainterRuntimeObject.supportsReinitialization = false; }
the_stack
import { BaseResource, CloudError } from "ms-rest-azure"; import * as moment from "moment"; export { BaseResource, CloudError }; /** * The resource model definition. */ export interface Resource extends BaseResource { /** * The resource identifier. */ readonly id?: string; /** * The resource name. */ readonly name?: string; /** * The resource type. */ readonly type?: string; /** * The resource location. */ readonly location?: string; /** * The resource tags. */ readonly tags?: { [propertyName: string]: string }; } /** * The resource model definition for a nested resource. */ export interface SubResource extends BaseResource { /** * The resource identifier. */ readonly id?: string; /** * The resource name. */ readonly name?: string; /** * The resource type. */ readonly type?: string; } /** * The encryption identity properties. */ export interface EncryptionIdentity { /** * The principal identifier associated with the encryption. */ readonly principalId?: string; /** * The tenant identifier associated with the encryption. */ readonly tenantId?: string; } /** * Metadata information used by account encryption. */ export interface KeyVaultMetaInfo { /** * The resource identifier for the user managed Key Vault being used to encrypt. */ keyVaultResourceId: string; /** * The name of the user managed encryption key. */ encryptionKeyName: string; /** * The version of the user managed encryption key. */ encryptionKeyVersion: string; } /** * The encryption configuration for the account. */ export interface EncryptionConfig { /** * The type of encryption configuration being used. Currently the only supported types are * 'UserManaged' and 'ServiceManaged'. Possible values include: 'UserManaged', 'ServiceManaged' */ type: string; /** * The Key Vault information for connecting to user managed encryption keys. */ keyVaultMetaInfo?: KeyVaultMetaInfo; } /** * Data Lake Store firewall rule information. */ export interface FirewallRule extends SubResource { /** * The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ readonly startIpAddress?: string; /** * The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ readonly endIpAddress?: string; } /** * Data Lake Store virtual network rule information. */ export interface VirtualNetworkRule extends SubResource { /** * The resource identifier for the subnet. */ readonly subnetId?: string; } /** * Data Lake Store trusted identity provider information. */ export interface TrustedIdProvider extends SubResource { /** * The URL of this trusted identity provider. */ readonly idProvider?: string; } /** * Data Lake Store account information. */ export interface DataLakeStoreAccount extends Resource { /** * The Key Vault encryption identity, if any. */ readonly identity?: EncryptionIdentity; /** * The unique identifier associated with this Data Lake Store account. */ readonly accountId?: string; /** * The provisioning status of the Data Lake Store account. Possible values include: 'Failed', * 'Creating', 'Running', 'Succeeded', 'Patching', 'Suspending', 'Resuming', 'Deleting', * 'Deleted', 'Undeleting', 'Canceled' */ readonly provisioningState?: string; /** * The state of the Data Lake Store account. Possible values include: 'Active', 'Suspended' */ readonly state?: string; /** * The account creation time. */ readonly creationTime?: Date; /** * The account last modified time. */ readonly lastModifiedTime?: Date; /** * The full CName endpoint for this account. */ readonly endpoint?: string; /** * The default owner group for all new folders and files created in the Data Lake Store account. */ readonly defaultGroup?: string; /** * The Key Vault encryption configuration. */ readonly encryptionConfig?: EncryptionConfig; /** * The current state of encryption for this Data Lake Store account. Possible values include: * 'Enabled', 'Disabled' */ readonly encryptionState?: string; /** * The current state of encryption provisioning for this Data Lake Store account. Possible values * include: 'Creating', 'Succeeded' */ readonly encryptionProvisioningState?: string; /** * The list of firewall rules associated with this Data Lake Store account. */ readonly firewallRules?: FirewallRule[]; /** * The list of virtual network rules associated with this Data Lake Store account. */ readonly virtualNetworkRules?: VirtualNetworkRule[]; /** * The current state of the IP address firewall for this Data Lake Store account. Possible values * include: 'Enabled', 'Disabled' */ readonly firewallState?: string; /** * The current state of allowing or disallowing IPs originating within Azure through the * firewall. If the firewall is disabled, this is not enforced. Possible values include: * 'Enabled', 'Disabled' */ readonly firewallAllowAzureIps?: string; /** * The list of trusted identity providers associated with this Data Lake Store account. */ readonly trustedIdProviders?: TrustedIdProvider[]; /** * The current state of the trusted identity provider feature for this Data Lake Store account. * Possible values include: 'Enabled', 'Disabled' */ readonly trustedIdProviderState?: string; /** * The commitment tier to use for next month. Possible values include: 'Consumption', * 'Commitment_1TB', 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB', * 'Commitment_5PB' */ readonly newTier?: string; /** * The commitment tier in use for the current month. Possible values include: 'Consumption', * 'Commitment_1TB', 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB', * 'Commitment_5PB' */ readonly currentTier?: string; } /** * Basic Data Lake Store account information, returned on list calls. */ export interface DataLakeStoreAccountBasic extends Resource { /** * The unique identifier associated with this Data Lake Store account. */ readonly accountId?: string; /** * The provisioning status of the Data Lake Store account. Possible values include: 'Failed', * 'Creating', 'Running', 'Succeeded', 'Patching', 'Suspending', 'Resuming', 'Deleting', * 'Deleted', 'Undeleting', 'Canceled' */ readonly provisioningState?: string; /** * The state of the Data Lake Store account. Possible values include: 'Active', 'Suspended' */ readonly state?: string; /** * The account creation time. */ readonly creationTime?: Date; /** * The account last modified time. */ readonly lastModifiedTime?: Date; /** * The full CName endpoint for this account. */ readonly endpoint?: string; } /** * The display information for a particular operation. */ export interface OperationDisplay { /** * The resource provider of the operation. */ readonly provider?: string; /** * The resource type of the operation. */ readonly resource?: string; /** * A friendly name of the operation. */ readonly operation?: string; /** * A friendly description of the operation. */ readonly description?: string; } /** * An available operation for Data Lake Store. */ export interface Operation { /** * The name of the operation. */ readonly name?: string; /** * The display information for the operation. */ display?: OperationDisplay; /** * The intended executor of the operation. Possible values include: 'user', 'system', * 'user,system' */ readonly origin?: string; } /** * The list of available operations for Data Lake Store. */ export interface OperationListResult { /** * The results of the list operation. */ readonly value?: Operation[]; /** * The link (url) to the next page of results. */ readonly nextLink?: string; } /** * Subscription-level properties and limits for Data Lake Store. */ export interface CapabilityInformation { /** * The subscription credentials that uniquely identifies the subscription. */ readonly subscriptionId?: string; /** * The subscription state. Possible values include: 'Registered', 'Suspended', 'Deleted', * 'Unregistered', 'Warned' */ readonly state?: string; /** * The maximum supported number of accounts under this subscription. */ readonly maxAccountCount?: number; /** * The current number of accounts under this subscription. */ readonly accountCount?: number; /** * The Boolean value of true or false to indicate the maintenance state. */ readonly migrationState?: boolean; } /** * Data Lake Store account name availability result information. */ export interface NameAvailabilityInformation { /** * The Boolean value of true or false to indicate whether the Data Lake Store account name is * available or not. */ readonly nameAvailable?: boolean; /** * The reason why the Data Lake Store account name is not available, if nameAvailable is false. */ readonly reason?: string; /** * The message describing why the Data Lake Store account name is not available, if nameAvailable * is false. */ readonly message?: string; } /** * The parameters used to create a new firewall rule while creating a new Data Lake Store account. */ export interface CreateFirewallRuleWithAccountParameters { /** * The unique name of the firewall rule to create. */ name: string; /** * The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ startIpAddress: string; /** * The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ endIpAddress: string; } /** * The parameters used to create a new virtual network rule while creating a new Data Lake Store * account. */ export interface CreateVirtualNetworkRuleWithAccountParameters { /** * The unique name of the virtual network rule to create. */ name: string; /** * The resource identifier for the subnet. */ subnetId: string; } /** * The parameters used to create a new trusted identity provider while creating a new Data Lake * Store account. */ export interface CreateTrustedIdProviderWithAccountParameters { /** * The unique name of the trusted identity provider to create. */ name: string; /** * The URL of this trusted identity provider. */ idProvider: string; } export interface CreateDataLakeStoreAccountParameters { /** * The resource location. */ location: string; /** * The resource tags. */ tags?: { [propertyName: string]: string }; /** * The Key Vault encryption identity, if any. */ identity?: EncryptionIdentity; /** * The default owner group for all new folders and files created in the Data Lake Store account. */ defaultGroup?: string; /** * The Key Vault encryption configuration. */ encryptionConfig?: EncryptionConfig; /** * The current state of encryption for this Data Lake Store account. Possible values include: * 'Enabled', 'Disabled' */ encryptionState?: string; /** * The list of firewall rules associated with this Data Lake Store account. */ firewallRules?: CreateFirewallRuleWithAccountParameters[]; /** * The list of virtual network rules associated with this Data Lake Store account. */ virtualNetworkRules?: CreateVirtualNetworkRuleWithAccountParameters[]; /** * The current state of the IP address firewall for this Data Lake Store account. Possible values * include: 'Enabled', 'Disabled' */ firewallState?: string; /** * The current state of allowing or disallowing IPs originating within Azure through the * firewall. If the firewall is disabled, this is not enforced. Possible values include: * 'Enabled', 'Disabled' */ firewallAllowAzureIps?: string; /** * The list of trusted identity providers associated with this Data Lake Store account. */ trustedIdProviders?: CreateTrustedIdProviderWithAccountParameters[]; /** * The current state of the trusted identity provider feature for this Data Lake Store account. * Possible values include: 'Enabled', 'Disabled' */ trustedIdProviderState?: string; /** * The commitment tier to use for next month. Possible values include: 'Consumption', * 'Commitment_1TB', 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB', * 'Commitment_5PB' */ newTier?: string; } /** * The Key Vault update information used for user managed key rotation. */ export interface UpdateKeyVaultMetaInfo { /** * The version of the user managed encryption key to update through a key rotation. */ encryptionKeyVersion?: string; } /** * The encryption configuration used to update a user managed Key Vault key. */ export interface UpdateEncryptionConfig { /** * The updated Key Vault key to use in user managed key rotation. */ keyVaultMetaInfo?: UpdateKeyVaultMetaInfo; } /** * The parameters used to update a firewall rule while updating a Data Lake Store account. */ export interface UpdateFirewallRuleWithAccountParameters { /** * The unique name of the firewall rule to update. */ name: string; /** * The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ startIpAddress?: string; /** * The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ endIpAddress?: string; } /** * The parameters used to update a virtual network rule while updating a Data Lake Store account. */ export interface UpdateVirtualNetworkRuleWithAccountParameters { /** * The unique name of the virtual network rule to update. */ name: string; /** * The resource identifier for the subnet. */ subnetId?: string; } /** * The parameters used to update a trusted identity provider while updating a Data Lake Store * account. */ export interface UpdateTrustedIdProviderWithAccountParameters { /** * The unique name of the trusted identity provider to update. */ name: string; /** * The URL of this trusted identity provider. */ idProvider?: string; } /** * Data Lake Store account information to update. */ export interface UpdateDataLakeStoreAccountParameters { /** * Resource tags */ tags?: { [propertyName: string]: string }; /** * The default owner group for all new folders and files created in the Data Lake Store account. */ defaultGroup?: string; /** * Used for rotation of user managed Key Vault keys. Can only be used to rotate a user managed * encryption Key Vault key. */ encryptionConfig?: UpdateEncryptionConfig; /** * The list of firewall rules associated with this Data Lake Store account. */ firewallRules?: UpdateFirewallRuleWithAccountParameters[]; /** * The list of virtual network rules associated with this Data Lake Store account. */ virtualNetworkRules?: UpdateVirtualNetworkRuleWithAccountParameters[]; /** * The current state of the IP address firewall for this Data Lake Store account. Disabling the * firewall does not remove existing rules, they will just be ignored until the firewall is * re-enabled. Possible values include: 'Enabled', 'Disabled' */ firewallState?: string; /** * The current state of allowing or disallowing IPs originating within Azure through the * firewall. If the firewall is disabled, this is not enforced. Possible values include: * 'Enabled', 'Disabled' */ firewallAllowAzureIps?: string; /** * The list of trusted identity providers associated with this Data Lake Store account. */ trustedIdProviders?: UpdateTrustedIdProviderWithAccountParameters[]; /** * The current state of the trusted identity provider feature for this Data Lake Store account. * Disabling trusted identity provider functionality does not remove the providers, they will * just be ignored until this feature is re-enabled. Possible values include: 'Enabled', * 'Disabled' */ trustedIdProviderState?: string; /** * The commitment tier to use for next month. Possible values include: 'Consumption', * 'Commitment_1TB', 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB', * 'Commitment_5PB' */ newTier?: string; } /** * The parameters used to create a new firewall rule. */ export interface CreateOrUpdateFirewallRuleParameters { /** * The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ startIpAddress: string; /** * The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ endIpAddress: string; } /** * The parameters used to update a firewall rule. */ export interface UpdateFirewallRuleParameters { /** * The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ startIpAddress?: string; /** * The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End * should be in the same protocol. */ endIpAddress?: string; } /** * The parameters used to create a new virtual network rule. */ export interface CreateOrUpdateVirtualNetworkRuleParameters { /** * The resource identifier for the subnet. */ subnetId: string; } /** * The parameters used to update a virtual network rule. */ export interface UpdateVirtualNetworkRuleParameters { /** * The resource identifier for the subnet. */ subnetId?: string; } /** * The parameters used to create a new trusted identity provider. */ export interface CreateOrUpdateTrustedIdProviderParameters { /** * The URL of this trusted identity provider. */ idProvider: string; } /** * The parameters used to update a trusted identity provider. */ export interface UpdateTrustedIdProviderParameters { /** * The URL of this trusted identity provider. */ idProvider?: string; } /** * Data Lake Store account name availability check parameters. */ export interface CheckNameAvailabilityParameters { /** * The Data Lake Store name to check availability for. */ name: string; } /** * Data Lake Store account list information response. */ export interface DataLakeStoreAccountListResult extends Array<DataLakeStoreAccountBasic> { /** * The link (url) to the next page of results. */ readonly nextLink?: string; } /** * Data Lake Store firewall rule list information. */ export interface FirewallRuleListResult extends Array<FirewallRule> { /** * The link (url) to the next page of results. */ readonly nextLink?: string; } /** * Data Lake Store virtual network rule list information. */ export interface VirtualNetworkRuleListResult extends Array<VirtualNetworkRule> { /** * The link (url) to the next page of results. */ readonly nextLink?: string; } /** * Data Lake Store trusted identity provider list information. */ export interface TrustedIdProviderListResult extends Array<TrustedIdProvider> { /** * The link (url) to the next page of results. */ readonly nextLink?: string; }
the_stack
import { ExtensionContext, ExtensionTab, Logger } from '@extraterm/extraterm-extension-api'; import { escape } from "he"; let log: Logger = null; let context: ExtensionContext = null; export function activate(_context: ExtensionContext): any { log = _context.logger; context = _context; context.commands.registerCommand("styleguide:open", styleGuideCommand); } let styleGuideTab: ExtensionTab = null; function styleGuideCommand(): void { if (styleGuideTab != null) { styleGuideTab.open(); return; } styleGuideTab = context.window.createExtensionTab("styleguide"); styleGuideTab.title = "Style Guide"; styleGuideTab.icon = "fas fa-swatchbook"; styleGuideTab.containerElement.innerHTML = contentsHTML(); styleGuideTab.containerElement.addEventListener("click", handleClick); styleGuideTab.onClose(() => { styleGuideTab = null; }); styleGuideTab.open(); } function handleClick(ev: MouseEvent): void { ev.preventDefault(); if ((<HTMLElement> ev.target).tagName === "A") { const href = (<HTMLAnchorElement> ev.target).href; context.application.openExternal(href); } } function contentsHTML(): string { return `<div id="guide"> <h1>Style Guide</h1> <p>This guide demonstrates the built in styles and CSS classes for use by those developing extensions.</p> <p>Extraterm uses SASS at run time to complete CSS style sheets.</p> <h2>Variables</h2> <p> To use thse SASS variables, first import them into your stylesheet with: '@import "general-gui/variables";' </p> ${colorPatch([ "text-color", "text-color-subtle", "text-minor-color", "text-highlight-color", "text-selected-color", "text-muted-color", ])} ${colorPatch([ "background-highlight-color", "background-color", "background-selected-color", ])} ${colorPatch([ "brand-primary", "brand-success", "brand-info", "brand-warning", "brand-danger", ])} ${colorPatch([ "brand-text-primary", "brand-text-success", "brand-text-info", "brand-text-warning", "brand-text-danger" ])} <div class="code-example"> <div class="code-example-result"><div class="panel-example"><div>Panel contents</div></div></div> <div class="code-example-source">The dashed outer box has "padding: $panel-body-padding;", separating it from the inner box..</div> </div> <h2>Text</h2> ${codeBlockVerbatum(` <h1>H1 Heading</h1> <h2>H2 Heading</h2> <h3>H3 Heading</h3> <h4>H4 Heading</h4> <h5>H5 Heading</h5> <h6>H6 Heading</h6> <p> Plain default text in a paragraph. </p> `)} <h2>Buttons</h2> ${codeBlock(` <button>Default button</button> <button class="success">Success button</button> <button class="info">Info button</button> <button class="warning">Warning button</button> <button class="danger">Danger button</button> `)} ${codeBlock(` <button disabled>Disabled default button</button> <button disabled class="success">Disabled success button</button> <button disabled class="info">Disabled info button</button> <button disabled class="warning">Disabled warning button</button> <button disabled class="danger">Disabled danger button</button> `)} ${codeBlock(` <button class="small">Small Default button</button> <button class="success small">Small Success button</button> <button class="info small">Small Info button</button> <button class="warning small">Small Warning button</button> <button class="danger small">Small Danger button</button> `)} ${codeBlock(` <button class="quiet">+</button> `)} ${codeBlock(` <button class="microtool">D</button><br /> <button class="microtool primary">P</button><br /> <button class="microtool success">S</button><br /> <button class="microtool info">I</button><br /> <button class="microtool warning">W</button><br /> <button class="microtool danger">D</button><br /> `)} ${codeBlock(` <button class="selected">Selected button</button><br /> `)} <h2>Inputs</h2> ${codeBlock(` <label>Text input:</label><input type="text" placeholder="Placeholder" value="Some text input" /> <label>Number input:</label><input type="number" value="5" min="0" max="100" /> `)} ${codeBlock(` <label>Select:</label><select> <option selected value="1">One</option> <option value="2">Two</option> </select> `)} ${codeBlock(` <label><input type="checkbox"> Checkbox</label> <label><input type="checkbox" checked> Selected Checkbox</label> `)} ${codeBlock(` <label><input type="radio" name="radio"> Radio button</label> <label><input type="radio" name="radio" checked> Selected radio button</label> `)} <h2>Input validation states</h2> ${codeBlock(` <label>Success input:</label><input type="text" class="has-success" value="Some text input" /> <label>Warning input:</label><input type="text" class="has-warning" value="Some text input" /> <label>Error input:</label><input type="text" class="has-error" value="Some text input" /> `)} <h2>Button groups</h2> ${codeBlock(` <span class="group"><button>Left</button><button>Right</button></span> <span class="group"><button class="success">Success</button><button class="warning">Warning</button><button class="danger">Danger</button></span> <span class="group"><button class="small">Left</button><button class="small">Right</button></span> `)} <h2>Input addons</h2> ${codeBlock(` <label>Amount:</label><span class="group"><input type="number" min="1" max="9999" ><span>euro</span></span><button class="inline">Inline button</button><br /> <label>Amount:</label><span class="group"><span>$</span><input type="number" min="1" max="9999" ></span><br /> <label>Amount:</label><span class="group"><span>$</span><input type="number" min="1" max="9999" ><span>.00</span></span> `)} <h2>Progress</h2> ${codeBlock(` Indeterminate: <progress class='inline-block'></progress> <progress class='inline-block' max='100' value='50'></progress> `)} <h2>GUI Layouts</h2> ${codeBlockVerbatum(` <div class="gui-layout cols-1-2 width-100pc"> <label>First name:</label><input type="text" /> <label>Last name:</label><input type="text" /> <label>Gender:</label><div><input type="radio" name="gender" /> Man</div> <label></label><div><input type="radio" name="gender" /> Woman</div> <label></label><div><input type="radio" name="gender" /> Other</div> <label>Acceptable drinks:</label><div><input type="checkbox" checked /> Tea</div> <label></label><div><input type="checkbox" /> Coffee</div> </div> `)} <p> Two columns are supported and the relative columns widths are set using one of 'cols-1', 'cols-1-1', 'cols-1-2', and 'cols-1-3'. </p> <h2>GUI Packed Row</h2> <p>Neatly packs a bunch of inputs into one row.</p> ${codeBlock(` <div class="gui-packed-row width-100pc"> <label class="compact">Enter long text:</label> <input type="text" class="expand" /> <button class="small primary compact">Done</button> <label class="compact">trailing text</label> </div> `)} <h2>Width Classes</h2> <p>Element widths in percent and pixels.</p> <div class="code-example"> <div class="code-example-result"> width-100pc<br> width-800px<br> max-width-800px </div> </div> <p>Character based widths for use on INPUT elements.</p> <div class="code-example"> <div class="code-example-result"> char-width-2<br> char-width-3<br> char-width-4<br> char-width-6<br> char-width-8<br> char-width-12<br> char-width-20<br> char-width-30<br> char-width-40<br> char-width-60<br> char-width-80 </div> </div> <p>Maximum character based widths for use on INPUT elements.</p> <div class="code-example"> <div class="code-example-result"> char-max-width-2<br> char-max-width-3<br> char-max-width-4<br> char-max-width-6<br> char-max-width-8<br> char-max-width-12<br> char-max-width-20<br> char-max-width-30<br> char-max-width-40<br> char-max-width-60<br> char-max-width-80 </div> </div> <h2>Tables</h2> ${codeBlockVerbatum(` <table class="table-hover width-100pc"> <thead> <tr> <th>Meaning</th> <th>Color</th> </tr> </thead> <tbody> <tr> <td>Success</td> <td>Green</td> </tr> <tr> <td>Info</td> <td>Blue</td> </tr> <tr> <td>Warning</td> <td>Yellow</td> </tr> </tbody> </table> `)} <h1>Badges</h1> ${codeBlockVerbatum(` <h1>Heading <span class="badge">1</span></h1> <h2>Heading <span class="badge">2</span></h2> <h3>Heading <span class="badge">3</span></h3> <h1>Success Heading <span class="badge success">1</span></h1> <h2>Success Heading <span class="badge success">2</span></h2> <h3>Success Heading <span class="badge success">3</span></h3> <h1>Info Heading <span class="badge info">1</span></h1> <h2>Info Heading <span class="badge info">2</span></h2> <h3>Info Heading <span class="badge info">3</span></h3> <h1>Warning Heading <span class="badge warning">1</span></h1> <h2>Warning Heading <span class="badge warning">2</span></h2> <h3>Warning Heading <span class="badge warning">3</span></h3> <h1>Danger Heading <span class="badge danger">1</span></h1> <h2>Danger Heading <span class="badge danger">2</span></h2> <h3>Danger Heading <span class="badge danger">3</span></h3> `)} <h1>Keycaps</h1> ${codeBlock(` <span class="keycap">Ctrl+K</span> `)} <h2>Font Awesome Icons</h2> <p> The <a href="https://fontawesome.com/icons?d=gallery&p=2&m=free">free icons from Font Awesome 5</a> icons are available if "fontAwesome" is set to true in the CSS section of the package.json. </p> ${codeBlockVerbatum(` <h1><i class="fas fa-book"></i> icon in heading 1</h1> <h2><i class="fas fa-cog"></i> icon in heading 2</h2> <p><i class="fas fa-dice-d20"></i> plain icon in text.</p> `)} </div> `; } function codeBlockVerbatum(code: string): string { return `<div class="code-example"> <div class="code-example-result">${code}</div> <div class="code-example-source">${crToBr(escape(code))}</div> </div> `; } function codeBlock(code: string): string { return `<div class="code-example"> <div class="code-example-result">${crToBr(code)}</div> <div class="code-example-source">${crToBr(escape(code))}</div> </div> `; } function crToBr(s: string): string { return s.trim().replace(/\n/g,"<br>"); } function colorPatch(names: string[]): string { return `<div class="code-example"> <div class="code-example-result"> ${names.map(color => `<div class="color-patch color-patch__${color}"></div> $${color}<br>`).join("")} </div></div>`; }
the_stack
import * as fs from 'fs'; import {app, BrowserWindow, shell, dialog, Menu} from 'electron'; import windowState = require('electron-window-state'); import * as menubar from 'menubar'; import {Config, Account, hostUrl} from './config'; import {partitionForAccount} from './account_switcher'; import log from './log'; import {IS_DEBUG, IS_DARWIN, IS_WINDOWS, APP_ICON, PRELOAD_JS, USER_CSS, IOS_SAFARI_USERAGENT, trayIcon} from './common'; function shouldOpenInternal(host: string, url: string): boolean { if (host.startsWith('https://pawoo.net') && url.startsWith('https://accounts.pixiv.net/login?')) { log.debug('accounts.pixiv.net opens and will redirect to pawoo.net for signin with Pixiv account.'); return true; } return false; } export default class Window { static create(account: Account, config: Config, mb: Menubar.MenubarApp | null = null) { return (config.normal_window ? startNormalWindow(account, config) : startMenuBar(account, config, mb)) .then(win => { win.browser.webContents.on('dom-ready', () => { applyUserCss(win.browser, config); win.browser.webContents.setZoomFactor(config.zoom_factor); log.debug('Send config to renderer procress'); win.browser.webContents.send('mstdn:config', config, account); }); return win; }); } constructor( public browser: Electron.BrowserWindow, public state: any /*XXX: ElectronWindowState.WindowState */, public account: Account, /* tslint:disable:no-shadowed-variable */ public menubar: Menubar.MenubarApp | null, /* tslint:enable:no-shadowed-variable */ ) { if (!IS_DARWIN) { // Users can still access menu bar with pressing Alt key. browser.setMenu(Menu.getApplicationMenu()); } browser.webContents.on('will-navigate', (e, url) => { const host = hostUrl(this.account); if (url.startsWith(host)) { return; } if (shouldOpenInternal(host, url)) { return; } e.preventDefault(); shell.openExternal(url); log.debug('Opened URL with external browser (will-navigate)', url); }); browser.webContents.on('new-window', (e, url) => { e.preventDefault(); shell.openExternal(url); log.debug('Opened URL with external browser (new-window)', url); }); browser.webContents.session.setPermissionRequestHandler((contents, permission, callback) => { const url = contents.getURL(); const grantedByDefault = url.startsWith(hostUrl(this.account)) && permission !== 'geolocation' && permission !== 'media'; if (grantedByDefault) { // Granted log.debug('Permission was granted', permission); callback(true); return; } log.debug('Create dialog for user permission', permission); dialog.showMessageBox({ type: 'question', buttons: ['Accept', 'Reject'], message: `Permission '${permission}' is requested by ${url}`, detail: "Please choose one of 'Accept' or 'Reject'", }, (buttonIndex: number) => { const granted = buttonIndex === 0; callback(granted); }); }); } open(url: string) { log.debug('Open URL:', url); this.browser.webContents.once('did-get-redirect-request', (e: Event, _: string, newUrl: string) => { if (url === newUrl) { return; } log.debug('Redirecting to ' + newUrl + '. Will navigate to login page for user using single user mode'); e.preventDefault(); this.browser.loadURL(hostUrl(this.account) + '/auth/sign_in'); }); if (url.startsWith('https://pawoo.net')) { this.browser.loadURL(url, { userAgent: IOS_SAFARI_USERAGENT, }); } else { this.browser.loadURL(url); } } close() { log.debug('Closing window:', this.account); this.state.saveState(); this.state.unmanage(); this.browser.webContents.removeAllListeners(); this.browser.removeAllListeners(); if (this.menubar) { // Note: // menubar.windowClear() won't be called because all listeners were removed delete this.menubar.window; } this.browser.close(); } toggle() { if (this.menubar) { if (this.browser.isFocused()) { log.debug('Toggle window: shown -> hidden'); this.menubar.hideWindow(); } else { log.debug('Toggle window: hidden -> shown'); this.menubar.showWindow(); } } else { if (this.browser.isFocused()) { log.debug('Toggle window: shown -> hidden'); if (IS_DARWIN) { app.hide(); } else if (IS_WINDOWS) { this.browser.minimize(); } else { this.browser.hide(); } } else { log.debug('Toggle window: hidden -> shown'); this.browser.show(); if (IS_WINDOWS) { this.browser.focus(); } } } } } function applyUserCss(win: Electron.BrowserWindow, config: Config) { if (config.chromium_sandbox) { log.debug('User CSS is disabled because Chromium sandbox is enabled'); return; } fs.readFile(USER_CSS, 'utf8', (err, css) => { if (err) { log.debug('Failed to load user.css: ', err.message); return; } win.webContents.insertCSS(css); log.debug('Applied user CSS:', USER_CSS); }); } function startNormalWindow(account: Account, config: Config): Promise<Window> { log.debug('Setup a normal window'); return new Promise<Window>(resolve => { const state = windowState({ defaultWidth: 600, defaultHeight: 800, }); const win = new BrowserWindow({ width: state.width, height: state.height, x: state.x, y: state.y, icon: APP_ICON, show: false, autoHideMenuBar: !!config.hide_menu, webPreferences: { nodeIntegration: false, sandbox: sandboxFlag(config, account), preload: PRELOAD_JS, partition: partitionForAccount(account), zoomFactor: config.zoom_factor, }, }); win.once('ready-to-show', () => { win.show(); }); win.once('closed', () => { app.quit(); }); if (state.isFullScreen) { win.setFullScreen(true); } else if (state.isMaximized) { win.maximize(); } state.manage(win); win.webContents.once('dom-ready', () => { log.debug('Normal window application was launched'); if (IS_DEBUG) { win.webContents.openDevTools({mode: 'detach'}); } }); resolve(new Window(win, state, account, null)); }); } function sandboxFlag(config: Config, account: Account) { // XXX: // Electron has a bug that CSP prevents preload script from being loaded. // mstdn.jp enables CSP. So currently we need to disable native sandbox to load preload script. // // Ref: https://github.com/electron/electron/issues/9276 // const electronBugIssue9276 = account.host === 'mstdn.jp' || account.host === 'https://mstdn.jp'; if (electronBugIssue9276) { return false; } return !!config.chromium_sandbox; } function startMenuBar(account: Account, config: Config, bar: Menubar.MenubarApp | null): Promise<Window> { log.debug('Setup a menubar window'); return new Promise<Window>(resolve => { const state = windowState({ defaultWidth: 320, defaultHeight: 420, }); const icon = trayIcon(config.icon_color); const mb = bar || menubar({ icon, width: state.width, height: state.height, alwaysOnTop: IS_DEBUG || !!config.always_on_top, tooltip: 'Mstdn', autoHideMenuBar: !!config.hide_menu, show: false, showDockIcon: true, webPreferences: { nodeIntegration: false, sandbox: sandboxFlag(config, account), preload: PRELOAD_JS, partition: partitionForAccount(account), zoomFactor: config.zoom_factor, }, }); mb.once('after-create-window', () => { log.debug('Menubar application was launched'); if (IS_DEBUG) { mb.window.webContents.openDevTools({mode: 'detach'}); } state.manage(mb.window); resolve(new Window(mb.window, state, account, mb)); }); mb.once('after-close', () => { app.quit(); }); if (bar) { log.debug('Recreate menubar window with different partition:', account); const pref = mb.getOption('webPreferences'); pref.partition = partitionForAccount(account); pref.sandbox = sandboxFlag(config, account); mb.setOption('webPreferences', pref); mb.showWindow(); } else { log.debug('New menubar instance was created:', account); mb.once('ready', () => mb.showWindow()); } }); }
the_stack
declare namespace SDK { /** * SDK.Metadata namespace */ namespace Metadata { /** * Enum which corresponds to the entity filters used in the metadata functions. */ const enum EntityFilters { Default = 1, Entity = 1, Attributes = 2, Privileges = 4, Relationships = 8, All = 15, } /** * Sends an asynchronous RetrieveAllEntities Request to retrieve all entities in the system. * * @param EntityFilters SDK.Metadata.EntityFilters provides an enumeration for the filters available to filter which data is retrieved. * Include only those elements of the entity you want to retrieve. Retrieving all parts of all entitities may take significant time. * @param RetrieveAsIfPublished Sets whether to retrieve the metadata that has not been published. * @param successCallback The function that will be passed through and be called by a successful response. * This function must accept the entityMetadataCollection as a parameter. * @param errorCallBack The function that will be passed through and be called by a failed response. * This function must accept an Error object as a parameter. * @param passThroughObject An Object that will be passed through to as the second parameter to the successCallBack. */ function RetrieveAllEntities(EntityFilters: EntityFilters, RetrieveAsIfPublished: boolean, successCallback: (metadata: EntityMetadata[], passThroughObject?: any) => any, errorCallback: (error: Error) => any, passThroughObject: any): void; /** * Sends an asynchronous RetrieveEntity Request to retrieve a specific entity. * * @param EntityFilters SDK.Metadata.EntityFilters provides an enumeration for the filters available to filter which data is retrieved. * Include only those elements of the entity you want to retrieve. Retrieving all parts of all entitities may take significant time. * @param LogicalName The logical name of the entity requested. A null value may be used if a MetadataId is provided. * @param MetadataId A null value or an empty guid may be passed if a LogicalName is provided. * @param RetrieveAsIfPublished Sets whether to retrieve the metadata that has not been published. * @param successCallback The function that will be passed through and be called by a successful response. * This function must accept the entityMetadata as a parameter. * @param errorCallback The function that will be passed through and be called by a failed response. * This function must accept an Error object as a parameter. * @param passThroughObject An Object that will be passed through to as the second parameter to the successCallBack. */ function RetrieveEntity(EntityFilters: EntityFilters, LogicalName: string, MetadataId: string | null, RetrieveAsIfPublished: boolean, successCallback: (metadata: EntityMetadata, passThroughObject?: any) => any, errorCallback: (error: Error) => any, passThroughObject: any): void; /** * Sends an asynchronous RetrieveAttribute Request to retrieve a specific entity. * * @param EntityLogicalName The logical name of the entity for the attribute requested. A null value may be used if a MetadataId is provided. * @param LogicalName The logical name of the attribute requested. * @param MetadataId A null value may be passed if an EntityLogicalName and LogicalName is provided. * @param RetrieveAsIfPublished Sets whether to retrieve the metadata that has not been published. * @param successCallback The function that will be passed through and be called by a successful response. * This function must accept the entityMetadata as a parameter. * @param errorCallback The function that will be passed through and be called by a failed response. * This function must accept an Error object as a parameter. * @param passThroughObject An Object that will be passed through to as the second parameter to the successCallBack. */ function RetrieveAttribute(EntityLogicalName: string, LogicalName: string, MetadataId: string | null, RetrieveAsIfPublished: boolean, successCallback: (metadata: AttributeMetadata, passThroughObject?: any) => any, errorCallback: (error: Error) => any, passThroughObject: any): void; interface BasicMetadata { HasChanged: any; MetadataId: string; IsManaged: boolean; } interface GeneralMetadata extends BasicMetadata { IntroducedVersion: string; IsCustomizable: ManagedProperty<boolean>; } /** * Interface that holds metadata for an attribute. */ interface AttributeMetadata extends GeneralMetadata { AttributeOf: string; AttributeType: string; AttributeTypeName: Value<string>; CanBeSecuredForCreate: boolean; CanBeSecuredForRead: boolean; CanBeSecuredForUpdate: boolean; CanModifyAdditionalSettings: ManagedProperty<boolean>; ColumnNumber: number; DeprecatedVersion: string; Description: Label; DisplayName: Label; /** * Logical name of the entity. */ EntityLogicalName: string; IsAuditEnabled: ManagedProperty<boolean>; IsCustomAttribute: boolean; IsLogical: string; IsPrimaryId: boolean; IsPrimaryName: boolean; IsRenameable: ManagedProperty<boolean>; IsSecured: boolean; IsValidForAdvancedFind: ManagedProperty<boolean>; IsValidForCreate: boolean; IsValidForRead: boolean; IsValidForUpdate: boolean; LinkedAttributeId: string; /** * Logical name of the attribute. */ LogicalName: string; RequiredLevel: ManagedProperty<string>; /** * Schema name of the attribute. */ SchemaName: string; SourceType: string; /** * Only available on Attributes with AttributeType == "Picklist" */ SourceTypeMask?: string; /** * Only available on Attributes with AttributeType == "Picklist" */ DefaultFormValue?: number; /** * Only available on Attributes with AttributeType == "Picklist" */ FormulaDefinition?: string; /** * Only available on Attributes with AttributeType == "Picklist" */ OptionSet?: OptionSetMetadata; /** * Only available on Attributes with AttributeType == "Lookup" */ Targets?: string[]; /** * Only available on Attributes with AttributeType == "String" */ MaxLength?: number; /** * Only available on Attributes with AttributeType == "Integer", "Decimal", "Money" */ MinValue?: number; /** * Only available on Attributes with AttributeType == "Integer", "Decimal", "Money" */ MaxValue?: number; /** * Only available on Attributes with AttributeType == "Decimal", "Money" */ Precision?: number; /** * Only available on Attributes with AttributeType == "Money" */ PrecisionSource?: PrecisionSource; } const enum PrecisionSource { Precision = 0, UseOrganizationPricingDecimalPrecision = 1, UseCurrencyPrecision = 2, } interface OptionSetMetadata extends GeneralMetadata { Description: Label; DisplayName: Label; IsCustomOptionSet: boolean; IsGlobal: boolean; Name: string; OptionSetType: string; Options: OptionMetadata[]; } interface OptionMetadata extends BasicMetadata { Description: Label; Label: Label; Value: number; } interface Label { LocalizedLabels: LocalizedLabel[]; UserLocalizedLabel: LocalizedLabel; } interface LocalizedLabel extends BasicMetadata { Label: string; LanguageCode: number; } interface ManagedProperty<T> { CanBeChanged: boolean; ManagedPropertyLogicalName: string; Value: T; } /** * Interface that holds metadata for an entity. */ interface EntityMetadata extends GeneralMetadata { AttributeTypeMask: number; /** * Attribute metadata of the entity */ Attributes: AttributeMetadata[]; AutoCreateAccessTeams: any; AutoRouteToOwnerQueue: boolean; CanBeInManyToMany: ManagedProperty<boolean>; CanBePrimaryEntityInRelationship: ManagedProperty<boolean>; CanBeRelatedEntityInRelationship: ManagedProperty<boolean>; CanChangeHierarchicalRelationship: ManagedProperty<boolean>; CanCreateAttributes: ManagedProperty<boolean>; CanCreateCharts: ManagedProperty<boolean>; CanCreateForms: ManagedProperty<boolean>; CanCreateViews: ManagedProperty<boolean>; CanModifyAdditionalSettings: ManagedProperty<boolean>; CanTriggerWorkflow: boolean; Description: Label; DisplayCollectionName: Label; DisplayName: Label; EnforceStateTransitions: string; EntityHelpUrl: string; EntityHelpUrlEnabled: string; IconLargeName: string; IconMediumName: string; IconSmallName: string; IsActivity: boolean; IsActivityParty: boolean; IsAIRUpdated: boolean; IsAuditEnabled: ManagedProperty<boolean>; IsAvailableOffline: boolean; IsBusinessProcessEnabled: string; IsChildEntity: boolean; IsConnectionsEnabled: ManagedProperty<boolean>; IsCustomEntity: boolean; IsDocumentManagementEnabled: boolean; IsDuplicateDetectionEnabled: ManagedProperty<boolean>; IsEnabledForCharts: boolean; IsEnabledForTrace: string; IsImportable: boolean; IsIntersect: boolean; IsMailMergeEnabled: ManagedProperty<boolean>; IsMappable: ManagedProperty<boolean>; IsQuickCreateEnabled: string; IsReadingPaneEnabled: boolean; IsReadOnlyInMobileClient: ManagedProperty<boolean>; IsRenameable: ManagedProperty<boolean>; IsStateModelAware: string; IsValidForAdvancedFind: boolean; IsValidForQueue: ManagedProperty<boolean>; IsVisibleInMobile: ManagedProperty<boolean>; IsVisibleInMobileClient: ManagedProperty<boolean>; LogicalName: string; ManyToManyRelationships: ManyToManyRelationshipMetadata[]; ManyToOneRelationships: OneToManyRelationshipMetadata[]; ObjectTypeCode: number; OneToManyRelationships: OneToManyRelationshipMetadata[]; OwnershipType: string; PrimaryIdAttribute: string; PrimaryImageAttribute: string; PrimaryNameAttribute: string; Privileges: Privilege[]; RecurrenceBaseEntityLogicalName: string; ReportViewName: string; SchemaName: string; } interface RelationshipMetadata extends GeneralMetadata { IsCustomRelationship: boolean; IsValidForAdvancedFind: boolean; RelationshipType: string; SchemaName: string; SecurityTypes: string; } interface OneToManyRelationshipMetadata extends RelationshipMetadata { AssociatedMenuConfiguration: AssociatedMenuConfiguration; CascadeConfiguration: CascadeConfiguration; IsHierarchical: string; ReferencedAttribute: string; ReferencedEntity: string; ReferencingAttribute: string; ReferencingEntity: string; } interface ManyToManyRelationshipMetadata extends RelationshipMetadata { Entity1AssociatedMenuConfiguration: AssociatedMenuConfiguration; Entity1IntersectAttribute: string; Entity1LogicalName: string; Entity2AssociatedMenuConfiguration: AssociatedMenuConfiguration; Entity2IntersectAttribute: string; Entity2LogicalName: string; IntersectEntityName: string; } interface CascadeConfiguration { Assign: string; Delete: string; Merge: string; Reparent: string; Share: string; Unshare: string; } interface AssociatedMenuConfiguration { Behavior: string; Group: string; Label: Label; Order: number; } interface Privilege { CanBeBasic: boolean; CanBeDeep: boolean; CanBeGlobal: boolean; CanBeLocal: boolean; Name: string; PrivilegeId: string; PrivilegeType: string; } interface Value<T> { Value: T; } } }
the_stack
declare namespace adone { /** * Various archivers */ namespace archive { /** * tar archiver */ namespace tar { namespace I { interface Header { /** * File path */ name: string; /** * Type of entry, file by default */ type: "file" | "directory" | "link" | "symlink" | "block-device" | "character-device" | "fifo" | "contiguous-file"; /** * Entry mode, 0755 for dirs and 0644 by default */ mode: number; /** * Last modified date for entry, now by default */ mtime: number; /** * Entry size, 0 by default */ size: number; /** * Linked file name */ linkname: string; /** * uid for entry owner, 0 by default */ uid: number; /** * gid for entry owner, 9 by default */ gid: number; /** * uname of entry owner, null by default */ uname: string; /** * gname of entry owner, null by default */ gname: string; /** * device minor versio, 0 by default */ devmajor: number; /** * device minor version, 0 by default */ devminor: number; } type Optional<T> = { [P in keyof T]?: T[P]; }; interface OptionalHeader extends Optional<Header> { /** * File path */ name: string; } interface CommonOptions { /** * Entries filter */ ignore?(name: string): boolean; /** * Header mapper, called for each each entry */ map?(header: Header): Header | undefined; /** * Set the dmode and fmode to writable */ readable?: boolean; /** * Set the dmode and fmode to writable */ writable?: boolean; /** * Strip the parts of paths of files */ strip?: number; /** * Ensure that packed directories have the corresponding modes */ dmode?: number; /** * Ensure that packed files have the corresponding modes */ fmode?: number; /** * A custom umask, process.umask() by default */ umask?: number; } interface PackOptions extends CommonOptions { /** * Input read stream modifier, called for each entry */ mapStream?(stream: fs.I.ReadStream, header: Header): nodestd.stream.Readable; /** * Pack the contents of the symlink instead of the link itself, false by default */ dereference?: boolean; /** * Specifies which entries to pack, all by default */ entries?: string[]; /** * Whether to sort entries before packing */ sort?: boolean; /** * set false to ignore errors due to unsupported entry types (like device files), true by default */ strict?: boolean; /** * A custom initial pack stream */ pack?: RawPackStream; } type Writable = nodestd.stream.Writable; interface LinkSink extends Writable { linkname: string; } interface UnpackOptions extends CommonOptions { /** * Input read stream modifier, called for each entry */ mapStream?(stream: UnpackSourceStream, header: Header): nodestd.stream.Readable; /** * Whether to change time properties of files */ utimes?: boolean; /** * Whether to change owner of the files */ chown?: boolean; /** * A custom unpack stream */ unpack?: RawUnpackStream; /** * Copies a file if cannot create a link */ hardlinkAsFilesFallback?: boolean; } interface UnpackSourceStream extends nodestd.stream.PassThrough { _parent: RawUnpackStream; } } /** * Represents a raw tar unpack stream */ class RawPackStream extends nodestd.stream.Readable { entry(header: I.OptionalHeader, buffer: Buffer, callback?: (err: any) => void): I.Writable; entry(header: I.OptionalHeader & { type: "symblink", linkname: string }, callback?: (err: any) => void): I.Writable; entry(header: I.OptionalHeader & { type: "symlink" }, callback?: (err: any) => void): I.LinkSink; entry(header: I.OptionalHeader, callback?: (err: any) => void): I.Writable; finalize(): void; destroy(err?: any): void; } /** * Represents a raw writable unpack stream */ class RawUnpackStream extends nodestd.stream.Writable { on(event: string, listener: (...args: any[]) => void): this; on(event: "entry", listener: (header: I.Header, stream: I.UnpackSourceStream, next: (err?: any) => void) => void): this; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "finish", listener: () => void): this; on(event: "pipe", listener: (src: nodestd.stream.Readable) => void): this; on(event: "unpipe", listener: (src: nodestd.stream.Readable) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "entry", listener: (header: I.Header, stream: I.UnpackSourceStream, next: (err?: any) => void) => void): this; once(event: "close", listener: () => void): this; once(event: "drain", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "finish", listener: () => void): this; once(event: "pipe", listener: (src: nodestd.stream.Readable) => void): this; once(event: "unpipe", listener: (src: nodestd.stream.Readable) => void): this; } /** * Creates a pack stream for the files from the given directory * * @param cwd directory to pack */ function packStream(cwd: string, options?: I.PackOptions): RawPackStream; /** * Creates an unpack stream to the given direcotry * * @param cwd direcotry to unpack to */ function unpackStream(cwd: string, options?: I.UnpackOptions): RawUnpackStream; } /** * zip archiver */ namespace zip { /** * zip packer */ namespace pack { class ZipFile { /** * A readable stream that will produce the contents of the zip file */ outputStream: nodestd.stream.Readable; /** * Adds a file from the file system at realPath into the zipfile as metadataPath * * @param path path to the file * @param metadataPath path to the file inside the archive */ addFile(path: string, metadataPath: string, options?: { /** * Overrides the value that will be obtained from stat */ mtime?: number, /** * Overrides the value that will be obtained from stat */ mode?: number, /** * If true, the file data will be deflated (compression method 8). * * If false, the file data will be stored (compression method 0) */ compress?: boolean, /** * Use ZIP64 format in this entry's Data Descriptor and Central Directory Record * regardless of if it's required or not (this may be useful for testing.). * Otherwise, packer will use ZIP64 format where necessary. */ forceZip64Format?: boolean }): this; /** * Adds a file to the zip file whose content is read from readStream * * @param stream a readable stream for the file * @param metadataPath path to the file inside the archive */ addReadStream(stream: nodestd.stream.Readable, metadataPath: string, options?: { /** * Defines modified date, now by default */ mtime?: number, /** * Defines file mode, 0o100664 by default */ mode?: number, /** * If true, the file data will be deflated (compression method 8). * * If false, the file data will be stored (compression method 0) */ compress?: boolean, /** * Use ZIP64 format in this entry's Data Descriptor and Central Directory Record * regardless of if it's required or not (this may be useful for testing.). * Otherwise, packer will use ZIP64 format where necessary. */ forceZip64Format?: boolean, /** * If given, it will be checked against the actual number of bytes in the readStream, * and an error will be emitted if there is a mismatch */ size?: number }): this; /** * Adds a file to the zip file whose content is buffer * * @param buffer the file's contents, must be at most 0x3fffffff bytes long * @param metadataPath path to the file inside the archive */ addBuffer(buffer: Buffer, metadataPath: string, options?: { /** * Defines modified date, now by default */ mtime?: number, /** * Defines file mode, 0o100664 by default */ mode?: number, /** * If true, the file data will be deflated (compression method 8). * * If false, the file data will be stored (compression method 0) */ compress?: boolean, /** * Use ZIP64 format in this entry's Data Descriptor and Central Directory Record * regardless of if it's required or not (this may be useful for testing.). * Otherwise, packer will use ZIP64 format where necessary. */ forceZip64Format?: boolean }): this; /** * Adds an entry to the zip file that indicates a directory should be created, * even if no other items in the zip file are contained in the directory */ addEmptyDirectory(metadataPath: string, options?: { /** * Defines modified date, now by default */ mtime?: number, /** * Defines file mode, 0o40775 by default */ mode?: number }): this; /** * Indicates that no more files will be added via addFile(), addReadStream(), or addBuffer(). * Some time after calling this function, outputStream will be ended. * * @returns the final guessed size of the file, can be -1 if it is hard to guess before processing. This will happend * only if compression is enabled, or a stream with no size hint given */ end(options?: { /** * If true, packet will include the ZIP64 End of Central Directory Locator and ZIP64 End of Central Directory Record * regardless of whether or not they are required (this may be useful for testing.). * Otherwise, packer will include these structures if necessary */ forceZip64Format?: boolean }): Promise<number>; } } /** * zip unpacker */ namespace unpack { namespace I { interface ExtraField { id: number; data: Buffer; } interface Entry<StringType> { versionMadeBy: number; versionNeededToExtract: number; generalPurposeBitFlag: number; compressionMethod: number; lastModFileTime: number; lastModFileDate: number; crc32: number; compressedSize: number; uncompressedSize: number; fileNameLength: number; extraFieldLength: number; fileCommentLength: number; internalFileAttributes: number; externalFileAttributes: number; relativeOffsetOfLocalHeader: number; /** * The bytes for the file name are decoded with UTF-8 if generalPurposeBitFlag & 0x800, otherwise with CP437. * Alternatively, this field may be populated from the Info-ZIP Unicode Path Extra Field (see extraFields). */ fileName: StringType; extraFields: ExtraField[]; /** * Comment decoded with the charset indicated by generalPurposeBitFlag & 0x800 as with the fileName */ fileComment: StringType; getLastModDate(): adone.I.datetime.Datetime; /** * Whether this entry is encrypted with "Traditional Encryption" */ isEncrypted(): boolean; /** * Whether the entry is compressed */ isCompressed(): boolean; } interface ZipFile<StringType> extends event.Emitter { /** * true until close() is called; then it's false */ isOpen: boolean; /** * Total number of central directory records */ entryCount: number; /** * Always decoded with CP437 per the spec */ comment: StringType; /** * Causes all future calls to openReadStream() to fail, * and closes the fd after all streams created by openReadStream() have emitted their end events */ close(): void; readEntry(): Promise<void>; /** * Opens a read stream for the given entry */ openReadStream(entry: Entry<StringType>, options?: { /** * The option must be omitted when the entry is not compressed (see isCompressed()), * and either true (or omitted) or false when the entry is compressed. * Specifying decompress: false for a compressed entry causes the read stream * to provide the raw compressed file data without going through a zlib inflate transform */ decompress?: boolean, /** * The option must be null (or omitted) for non-encrypted entries, * and false for encrypted entries. Omitting the option for an encrypted entry will result in an err. */ decrypt?: boolean, /** * The start byte offset (inclusive) into this entry's file data */ start?: number, /** * The end byte offset (exclusive) into this entry's file data */ end?: number, }): Promise<nodestd.stream.Readable>; /** * Emitted for each entry. * * If decodeStrings is true, entries emitted via this event have already passed file name validation * * If validateEntrySizes is true and this entry's compressionMethod is 0 (stored without compression), * this entry has already passed entry size validation */ on(event: "entry", listener: (entry: Entry<StringType>) => void): this; /** * Emitted after the last entry event has been emitted */ on(event: "end", listener: () => void): this; /** * Emitted after the fd is actually closed */ on(event: "close", listener: () => void): this; /** * Emitted in the case of errors with reading the zip file */ on(event: "error", listener: (err: any) => void): this; /** * Emitted for each entry. * * If decodeStrings is true, entries emitted via this event have already passed file name validation * * If validateEntrySizes is true and this entry's compressionMethod is 0 (stored without compression), * this entry has already passed entry size validation */ once(event: "entry", listener: (entry: Entry<StringType>) => void): this; /** * Emitted after the last entry event has been emitted */ once(event: "end", listener: () => void): this; /** * Emitted after the fd is actually closed */ once(event: "close", listener: () => void): this; /** * Emitted in the case of errors with reading the zip file */ once(event: "error", listener: (err: any) => void): this; } interface CommonOptions { /** * Indicates that entries should be read only when readEntry() is called. * If lazyEntries is false, entry events will be emitted as fast as possible * to allow pipe()-ing file data from all entries in parallel. * * Default is false */ lazyEntries?: boolean; /** * Causes unpacker to decode strings with CP437 or UTF-8 as required by the spec. * * When turned off zipfile.comment, entry.fileName, and entry.fileComment will be Buffer, * any Info-ZIP Unicode Path Extra Field will be ignored, automatic file name validation will not be performed */ decodeStrings?: boolean; /** * Ensures that an entry's reported uncompressed size matches its actual uncompressed size */ validateEntrySizes?: boolean; } interface PathOptions extends CommonOptions { /** * Autocloses the file after the last entry reading or when an error occurs * * Default is true */ autoClose?: boolean; } interface FdOptions extends CommonOptions { /** * Autocloses the file after the last entry reading or when an error occurs * * Default is false */ autoClose?: boolean; } type BufferOptions = CommonOptions; interface RandomAccessReaderOptions extends CommonOptions { /** * Autocloses the file after the last entry reading or when an error occurs * * Default is true */ autoClose?: boolean; } } /** * Opens a file and creates a zipfile unpacker */ function open(path: string, options: I.PathOptions & { decodeStrings: false }): I.ZipFile<Buffer>; /** * Opens a file and creates a zipfile unpacker */ function open(path: string, options?: I.PathOptions): I.ZipFile<string>; /** * Creates a zipfile unpacker for the given fd */ function fromFd(fd: number, options: I.FdOptions & { decodeStrings: false }): I.ZipFile<Buffer>; /** * Creates a zipfile unpacker for the given fd */ function fromFd(fd: number, options?: I.FdOptions): I.ZipFile<string>; /** * Creates a zipfile unpacker for the given buffer */ function fromBuffer(buffer: Buffer, options: I.BufferOptions & { decodeStrings: false }): I.ZipFile<Buffer>; /** * Creates a zipfile unpacker for the given buffer */ function fromBuffer(buffer: Buffer, options?: I.BufferOptions): I.ZipFile<string>; /** * Creates a zipfile unpacker for the given random access reader. * This method of reading a zip file allows clients to implement their own back-end file system * * @param totalSize Indicates the total file size of the zip file */ function fromRandomAccessReader( reader: fs.AbstractRandomAccessReader, totalSize: number, options: I.RandomAccessReaderOptions & { decodeStrings: false } ): I.ZipFile<Buffer>; /** * Creates a zipfile unpacker for the given random access reader. * This method of reading a zip file allows clients to implement their own back-end file system * * @param totalSize Indicates the total file size of the zip file */ function fromRandomAccessReader( reader: fs.AbstractRandomAccessReader, totalSize: number, options?: I.RandomAccessReaderOptions ): I.ZipFile<string>; /** * Returns null or a String error message depending on the validity of fileName */ function validateFileName(filename: string): string | null; } } } }
the_stack
import * as api from '@aws-cdk/aws-apigateway'; import * as apiv2 from '@aws-cdk/aws-apigatewayv2'; import * as apiv2_integrations from '@aws-cdk/aws-apigatewayv2-integrations'; import * as cdk from '@aws-cdk/core'; import * as codebuild from '@aws-cdk/aws-codebuild'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as events from '@aws-cdk/aws-events'; import * as iam from '@aws-cdk/aws-iam'; import * as lambda from '@aws-cdk/aws-lambda'; import * as lambda_nodejs from '@aws-cdk/aws-lambda-nodejs'; import * as path from 'path'; import * as s3 from '@aws-cdk/aws-s3'; import * as sfn from '@aws-cdk/aws-stepfunctions'; import * as sns from '@aws-cdk/aws-sns'; import * as sns_sub from '@aws-cdk/aws-sns-subscriptions'; import * as tasks from '@aws-cdk/aws-stepfunctions-tasks'; import * as targets from '@aws-cdk/aws-events-targets'; export interface Stage { name: string, stageName?: string, deployContexts: DeployContexts, assumeRoleContexts: AssumeRoleContexts, } export interface DeployContexts { vpcId: string, fileSystem?: { id: string, sgId: string }, iamCertId: string, domainName: string, domainZone: string, additionalOptions?: string, } export interface AssumeRoleContexts { account: string, roleName: string, } export interface PipelineStage extends cdk.StackProps { topic: sns.ITopic, uat: Stage, prod: Stage, } export class PipelineStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props: PipelineStage) { super(scope, id, props); const stack = cdk.Stack.of(this); const vpc = new ec2.Vpc(this, 'PipelineVpc', { maxAzs: 2, natGateways: 1, gatewayEndpoints: { s3: { service: ec2.GatewayVpcEndpointAwsService.S3, }, }, }); const npmMirror = this.node.tryGetContext('npmMirror'); const npmConfigs = []; if (npmMirror) { npmConfigs.push(`npm config set registry ${npmMirror}`); } npmConfigs.push('npm install -g npm@7.10.0'); const pipelineBucket = new s3.Bucket(this, 'PipelineBucket'); // create states of step functions for pipeline const failure = new sfn.Fail(this, 'Fail', {}); const approvalTimeout = new sfn.Succeed(this, `The approval of deploying to stage '${props.prod.name}' timeout`, { comment: 'mark the execution as succeed due to the approval is timeout.', }); const end = new sfn.Succeed(this, 'Stop deploying to next stage', { comment: 'next stage deployment is stopped.', }); const sourceBranch = this.node.tryGetContext('sourceBranch') ?? 'master'; const buildAndTestProject = new codebuild.Project(this, 'OpenTUNABuild', { vpc, subnetSelection: { subnetType: ec2.SubnetType.PRIVATE, }, allowAllOutbound: true, source: codebuild.Source.gitHub({ owner: this.node.tryGetContext('sourceOwner') ?? 'tuna', repo: this.node.tryGetContext('sourceRepo') ?? 'opentuna', cloneDepth: 1, branchOrRef: sourceBranch, }), environment: { buildImage: codebuild.LinuxBuildImage.AMAZON_LINUX_2_3, privileged: true, }, cache: codebuild.Cache.bucket(pipelineBucket, { prefix: 'pipeline/build', }), buildSpec: codebuild.BuildSpec.fromObject({ version: '0.2', env: { 'exported-variables': [ 'COMMIT_HASH' ], }, phases: { install: { 'runtime-versions': { nodejs: 12 }, commands: [ ...npmConfigs, 'npm run install-deps', ], }, pre_build: { commands: [ 'git submodule init', 'git submodule update --depth 1', 'export COMMIT_HASH=`git rev-parse HEAD`', ], }, build: { commands: [ 'npm run build', 'npm run test', ], }, }, cache: { paths: [ 'node_modules/', '.git/modules/', ] }, }) }); const updatePipeline = new codebuild.Project(this, 'OpenTUNAPipelineUpdate', { vpc, subnetSelection: { subnetType: ec2.SubnetType.PRIVATE, }, allowAllOutbound: true, source: codebuild.Source.gitHub({ owner: this.node.tryGetContext('sourceOwner') ?? 'tuna', repo: this.node.tryGetContext('sourceRepo') ?? 'opentuna', cloneDepth: 1, branchOrRef: sourceBranch, }), environment: { buildImage: codebuild.LinuxBuildImage.AMAZON_LINUX_2_3, privileged: true, }, cache: codebuild.Cache.bucket(pipelineBucket, { prefix: 'pipeline/update-pipeline', }), buildSpec: codebuild.BuildSpec.fromObject({ version: '0.2', env: { }, phases: { install: { 'runtime-versions': { nodejs: 12 }, commands: [ ...npmConfigs, 'npm run install-deps', ], }, pre_build: { commands: [ ], }, build: { commands: [ `npm run deploy-pipeline -- --require-approval never \ ${this.node.tryGetContext('slackHookUrl') ? `-c slackHookUrl=${this.node.tryGetContext('slackHookUrl')}`: ''} \ ${this.node.tryGetContext('slackChannel') ? `-c slackChannel=${this.node.tryGetContext('slackChannel')}`: ''} \ `, ], }, }, cache: { paths: [ 'node_modules/', ] }, }), }); updatePipeline.addToRolePolicy(new iam.PolicyStatement({ actions: [ '*' ], effect: iam.Effect.ALLOW, resources: ['*'], })); // TODO: pass the commit when trigger the pipeline stepfunctions const commitVersion = sourceBranch; const codeBuildTestTask = new tasks.CodeBuildStartBuild(stack, 'Build & Test', { project: buildAndTestProject, integrationPattern: sfn.IntegrationPattern.RUN_JOB, }).addCatch(failure, { errors: [sfn.Errors.TASKS_FAILED, sfn.Errors.PARAMETER_PATH_FAILURE, sfn.Errors.PERMISSIONS] }); const pipelineUpdateTask = new tasks.CodeBuildStartBuild(stack, 'Pipeline update', { project: updatePipeline, integrationPattern: sfn.IntegrationPattern.RUN_JOB, }).addCatch(failure, { errors: [sfn.Errors.ALL] }); const uatDeployTask = new tasks.CodeBuildStartBuild(stack, `Deploy to ${props.uat.name} account ${props.uat.assumeRoleContexts.account}`, { project: this.deployToAccount(vpc, pipelineBucket, commitVersion, props.topic, props.uat, npmConfigs), integrationPattern: sfn.IntegrationPattern.RUN_JOB, }).addCatch(failure, { errors: [sfn.Errors.ALL] }); const prodDeployTask = new tasks.CodeBuildStartBuild(stack, `Deploy to ${props.prod.name} account ${props.prod.assumeRoleContexts.account}`, { project: this.deployToAccount(vpc, pipelineBucket, commitVersion, props.topic, props.prod, npmConfigs), integrationPattern: sfn.IntegrationPattern.RUN_JOB, }).addCatch(failure, { errors: [sfn.Errors.ALL] }); const approvalActionsFn = new lambda_nodejs.NodejsFunction(this, 'PipelineApprovalActions', { entry: path.join(__dirname, './lambda.pipelines.d/approver-actions/index.ts'), handler: 'pipelineApprovalAction' }); const approvalActionsIntegration = new apiv2_integrations.LambdaProxyIntegration({ handler: approvalActionsFn, }); const pipelineApi = new apiv2.HttpApi(this, 'OpenTUNAPipelineHttpApi'); pipelineApi.addRoutes({ path: '/approval', methods: [apiv2.HttpMethod.GET], integration: approvalActionsIntegration, }); const approverNotificationFn = new lambda_nodejs.NodejsFunction(this, 'PipelineApproverNotification', { entry: path.join(__dirname, './lambda.pipelines.d/approver-notification/index.ts'), handler: 'pipelineApproverNotification' }); props.topic.grantPublish(approverNotificationFn); const nextStage = props.prod.name; const approvalTimeoutInMinutes = this.node.tryGetContext('approvalTimeoutInMinutes') ?? 60 * 24 * 3; const approvalTask = new tasks.LambdaInvoke(this, 'Notify approvers', { lambdaFunction: approverNotificationFn, integrationPattern: sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN, timeout: cdk.Duration.minutes(approvalTimeoutInMinutes), payload: sfn.TaskInput.fromObject({ ExecutionContext: sfn.TaskInput.fromJsonPathAt('$$').value, ActionEndpoint: pipelineApi.url, SNSTopicArn: props.topic.topicArn, Commit: commitVersion, // TODO: replaced by commit given executation pipelines NextStage: nextStage, Timeout: approvalTimeoutInMinutes, Stage: props.uat.name, Domain: props.uat.deployContexts.domainName, }), }).addCatch(approvalTimeout, { errors: [ sfn.Errors.TIMEOUT ] }).addCatch(failure, { errors: [ sfn.Errors.ALL ] }); const getApproverChoice = new sfn.Choice(this, `Can the pipeline continue deploying to next stage "${nextStage}"?`); getApproverChoice.when(sfn.Condition.stringEquals('$.Status', 'Approved'), prodDeployTask); getApproverChoice.when(sfn.Condition.stringEquals('$.Status', 'Rejected'), end); const definition = codeBuildTestTask.next(pipelineUpdateTask) .next(uatDeployTask).next(approvalTask) .next(getApproverChoice); const pipeline = new sfn.StateMachine(this, 'Pipeline', { definition, }); approvalActionsFn.addToRolePolicy(new iam.PolicyStatement({ actions: [ 'states:SendTaskSuccess', 'states:SendTaskFailure', 'states:SendTaskHeartbeat', ], resources: [ cdk.Arn.format({ service: 'states', resource: 'stateMachine', sep: ':', resourceName: `${pipeline.stateMachineName}`, }, stack), ] })); // create restful API endpoint to start pipeline const pipelineRestApi = new api.RestApi(this, 'PipelineRestApi', { deployOptions: { stageName: 'pipeline', loggingLevel: api.MethodLoggingLevel.INFO, dataTraceEnabled: false, metricsEnabled: true, }, endpointConfiguration: { types: [ api.EndpointType.REGIONAL, ], }, }); const stateRole = new iam.Role(this, 'StateRole', { assumedBy: new iam.ServicePrincipal('apigateway.amazonaws.com'), }); stateRole.attachInlinePolicy(new iam.Policy(this, 'StatePolicy', { statements: [ new iam.PolicyStatement({ actions: ['states:StartExecution'], effect: iam.Effect.ALLOW, resources: [pipeline.stateMachineArn], }), ], })); const errorResponses = [ { selectionPattern: '400', statusCode: '400', responseTemplates: { 'application/json': `{ "error": "Bad input!" }`, }, }, { selectionPattern: '5\\d{2}', statusCode: '500', responseTemplates: { 'application/json': `{ "error": "Internal Service Error!" }`, }, }, ]; const integrationResponses = [ { statusCode: '200', responseTemplates: { 'application/json': `{ "executionArn": "integration.response.body.executionArn", "startDate": "integration.response.body.startDate" }`, }, }, ...errorResponses, ]; const pipelineStepFunctionsIntegration = new api.AwsIntegration({ service: 'states', action: 'StartExecution', options: { credentialsRole: stateRole, integrationResponses, passthroughBehavior: api.PassthroughBehavior.WHEN_NO_TEMPLATES, requestTemplates: { 'application/json': `{ "input": "{ \\\"commit\\\": \\\"$input.params('commit')\\\" }", "stateMachineArn": "${pipeline.stateMachineArn}" }`, }, }, }); const startPath = 'start'; pipelineRestApi.root.addResource(startPath).addMethod('PUT', pipelineStepFunctionsIntegration, { methodResponses: [ { statusCode: '200' }, { statusCode: '400' }, { statusCode: '500' } ] }, ); new events.Rule(this, `PipelineFailureEvent`, { enabled: true, eventPattern: { source: ['aws.states'], detailType: ['Step Functions Execution Status Change'], detail: { stateMachineArn: [ pipeline.stateMachineArn ], status: [ 'FAILED', 'ABORTED', 'SUCCEEDED', 'TIMED_OUT' ] }, }, targets: [new targets.SnsTopic(props.topic, { message: events.RuleTargetInput.fromObject({ type: 'pipeline', execution: events.EventField.fromPath('$.detail.name'), account: events.EventField.fromPath('$.account'), input: events.EventField.fromPath('$.detail.input'), output: events.EventField.fromPath('$.detail.output'), result: events.EventField.fromPath('$.detail.status'), }), })], }); const parameterPrefix = '/opentuna/pipeline/stage/'; const confUpdatorFn = new lambda_nodejs.NodejsFunction(this, 'StageConfigUpdator', { entry: path.join(__dirname, './lambda.pipelines.d/stage-conf-updator/index.ts'), handler: 'certChangedEvent', timeout: cdk.Duration.minutes(3), runtime: lambda.Runtime.NODEJS_12_X, }); confUpdatorFn.addToRolePolicy(new iam.PolicyStatement({ actions: [ 'ssm:GetParameter', 'ssm:PutParameter' ], effect: iam.Effect.ALLOW, resources: [ cdk.Arn.format({ service: 'ssm', resource: 'parameter', resourceName: `${parameterPrefix.substring(1)}*`, }, stack) ] })); const iamCertChangedTopic = new sns.Topic(this, 'IAMCertChangedTopic', { displayName: `The IAM cert changed topic of OpenTuna stages.` }); iamCertChangedTopic.addToResourcePolicy( this.createAccessPolicy(iamCertChangedTopic, props.prod.assumeRoleContexts.account)); iamCertChangedTopic.addToResourcePolicy( this.createAccessPolicy(iamCertChangedTopic, props.uat.assumeRoleContexts.account)); iamCertChangedTopic.addSubscription(new sns_sub.LambdaSubscription(confUpdatorFn)); new cdk.CfnOutput(this, 'PipelineAPI', { value: pipelineRestApi.urlForPath(`/${startPath}`), exportName: 'startUrl', description: 'endpoint of starting OpenTUNA pipeline', }); new cdk.CfnOutput(this, 'IAMCertChangedTopicOutput', { value: iamCertChangedTopic.topicArn, exportName: 'topicArn', description: 'topic arn of IAM Certs changed topic', }); cdk.Tags.of(this).add('component', 'pipeline'); } private createAccessPolicy(iamCertChangedTopic: sns.Topic, account: string) : iam.PolicyStatement { const publishingPolicy = new iam.PolicyStatement({ effect: iam.Effect.ALLOW, principals: [ new iam.AccountPrincipal(account) ], resources: [iamCertChangedTopic.topicArn], actions: [ 'sns:Publish', ] }); return publishingPolicy; } deployToAccount( vpc: ec2.IVpc, pipelineBucket: s3.IBucket, sourceVersion: string, topic: sns.ITopic, stage: Stage, npmConfigs: string[], ): codebuild.IProject { const stack = cdk.Stack.of(this); const prj = new codebuild.Project(this, `OpenTuna${stage.name}Deployment`, { vpc, subnetSelection: { subnetType: ec2.SubnetType.PRIVATE, }, allowAllOutbound: true, source: codebuild.Source.gitHub({ owner: this.node.tryGetContext('sourceOwner') ?? 'tuna', repo: this.node.tryGetContext('sourceRepo') ?? 'opentuna', cloneDepth: 1, branchOrRef: sourceVersion, }), environment: { buildImage: codebuild.LinuxBuildImage.AMAZON_LINUX_2_3, privileged: true, computeType: codebuild.ComputeType.SMALL, }, cache: codebuild.Cache.bucket(pipelineBucket, { prefix: `pipeline/deployment/${stage.name}`, }), buildSpec: codebuild.BuildSpec.fromObject({ version: '0.2', phases: { install: { 'runtime-versions': { nodejs: 12 }, commands: [ ...npmConfigs, 'npm run install-deps', ], }, pre_build: { commands: [ 'git submodule init', 'git submodule update --depth 1', ], }, build: { commands: [ `ASSUME_ROLE_ARN=arn:${stack.partition}:iam::${stage.assumeRoleContexts.account}:role/${stage.assumeRoleContexts.roleName}`, `SESSION_NAME=deployment-to-${stage.assumeRoleContexts.account}`, 'creds=$(mktemp -d)/creds.json', 'echo "assuming role ${ASSUME_ROLE_ARN} with session-name ${SESSION_NAME}"', 'aws sts assume-role --role-arn $ASSUME_ROLE_ARN --role-session-name $SESSION_NAME > $creds', `export AWS_ACCESS_KEY_ID=$(cat \${creds} | grep "AccessKeyId" | cut -d '"' -f 4)`, `export AWS_SECRET_ACCESS_KEY=$(cat \${creds} | grep "SecretAccessKey" | cut -d '"' -f 4)`, `export AWS_SESSION_TOKEN=$(cat \${creds} | grep "SessionToken" | cut -d '"' -f 4)`, `npx cdk deploy OpenTunaStack --require-approval never -v \ -c stage=${stage.stageName ?? stage.name} \ -c vpcId=${stage.deployContexts.vpcId} \ ${this.getFileSystemOptions(stage.deployContexts.fileSystem)} \ -c domainName=${stage.deployContexts.domainName} \ -c domainZone=${stage.deployContexts.domainZone} \ -c iamCertId=${stage.deployContexts.iamCertId} \ ${stage.deployContexts.additionalOptions ?? ''} \ `, ], }, }, cache: { paths: [ 'node_modules/', '.git/modules/', ] }, }) }); prj.addToRolePolicy(new iam.PolicyStatement({ actions: ['sts:AssumeRole'], resources: ['*'], })); return prj; } getFileSystemOptions(fileSystem?: { id: string, sgId: string, }): string { if (fileSystem) return `-c fileSystemId=${fileSystem.id} -c fileSystemSGId=${fileSystem.sgId}`; return ''; } }
the_stack
import { AttributeSpec, MarkSpec, Node, NodeSpec, ParseRule, Schema, } from 'prosemirror-model' /** * ProseMirror schema for a Stencila `Article`. * * This schema uses the following conventions: * * - Properties of Stencila nodes are represented as ProseMirror `NodeSpec`s with * a lowercase name (e.g. `title`, `abstract`) and `toDOM` and `parseDOM` rules * which use the corresponding `data-prop` selector (e.g. [data-prop=title]). * The `prop` function is a shortcut for creating these node specs. * * - Stencila node types are represented as ProseMirror node types with title * case name (e.g. `Paragraph`), a `toDOM` rule that includes `itemtype` (and `itemscope`) * for application of semantic themes, and `parseDOM` rules that are as simple as * possible (for copy-paste) compatibility. * * - Stencila node types can define a `contentProp` which is the name of the node property * that will be used when generating an address e.g. `contentProp: 'cells'` * * These conventions make it possible to convert a ProseMirror offset position e.g. `83` * into a Stencila address e.g. `["content", 1, "caption", 4]`. * * Note: When adding types here, please ensure transformations are handled in the * `transformProsemirror` function. * * For docs and examples see: * - https://prosemirror.net/docs/guide/#schema * - https://prosemirror.net/examples/schema/ * - https://github.com/ProseMirror/prosemirror-schema-basic/blob/master/src/schema-basic.js */ export const articleSchema = new Schema({ topNode: 'Article', nodes: { // Article type and its properties Article: { content: 'title? abstract? content' }, title: prop('title', 'div', 'InlineContent*'), abstract: prop('abstract', 'div', 'BlockContent+'), content: prop('content', 'div', 'BlockContent+'), // Block content types. Note that order is important as the // first is the default block content Paragraph: block('Paragraph', 'p', 'InlineContent*'), Heading: heading(), List: list(), ListItem: listItem(), CodeBlock: codeBlock(), QuoteBlock: block('QuoteBlock', 'blockquote', 'BlockContent+'), Table: table(), TableRow: tableRow(), TableCell: tableCell(), TableHeader: tableHeader(), ThematicBreak: thematicBreak(), // Inline content types, starting with `text` (equivalent of Stencila `String`), // the default inline node type text: { group: 'InlineContent', }, CodeFragment: codeFragment(), }, marks: { Emphasis: mark('Emphasis', 'em', [ { tag: 'em' }, { tag: 'i' }, { style: 'font-style=italic' }, ]), Strong: mark('Strong', 'strong', [ { tag: 'strong' }, { tag: 'b' }, { style: 'font-weight', getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value as string) && null, }, ]), NontextualAnnotation: mark('NontextualAnnotation', 'u'), Delete: mark('Delete', 'del'), Subscript: mark('Subscript', 'sub'), Superscript: mark('Superscript', 'sup'), }, }) export const articleMarks = Object.keys(articleSchema.marks) /** * Generate a `NodeSpec` to represent the property of a Stencila node type. * * @param name The name of the property * @param tag The tag name of the HTML element for `toDOM` and `parseDOM`) * @param content The expression specifying valid content for the property e.g `InlineContent+` * @param marks The expression specifying valid marks for the property e.g '_' (all), '' (none) */ function prop( name: string, tag: string, content: string, marks = '_' ): NodeSpec { return { content, marks, defining: true, parseDOM: [{ tag: `${tag}[data-itemprop=${name}]` }], toDOM(_node) { return [tag, { 'data-itemprop': name }, 0] }, } } /** * Generate a `NodeSpec` to represent a Stencila `BlockContent` node type. * * @param name The name of the type e.g. `Paragraph` * @param group The content group that the type belongs to * @param tag The tag name of the HTML element for `toDOM` and `parseDOM`) * @param content The expression specifying valid content for the property e.g `InlineContent+` * @param marks The expression specifying valid marks for the property e.g '_' (all), '' (none) */ function block( name: string, tag: string, content: string, marks = '_' ): NodeSpec { return { group: 'BlockContent', content, marks, defining: true, parseDOM: [{ tag }], toDOM(_node) { return [ tag, { itemtype: `http://schema.stenci.la/${name}`, itemscope: '' }, 0, ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `Heading`. * * Note that, consistent with treatment elsewhere, `h2` => level 3 etc. * This is because there should only be one `h1` (for the title) and when encoding to * HTML we add one to the depth e.g. `depth: 1` => `h2` */ function heading(): NodeSpec { return { group: 'BlockContent', content: 'InlineContent*', marks: '_', defining: true, attrs: { depth: { default: 1 } }, parseDOM: [ { tag: 'h1', attrs: { depth: 1 } }, { tag: 'h2', attrs: { depth: 1 } }, { tag: 'h3', attrs: { depth: 2 } }, { tag: 'h4', attrs: { depth: 3 } }, { tag: 'h5', attrs: { depth: 4 } }, { tag: 'h6', attrs: { depth: 5 } }, ], toDOM(node) { return [ `h${(node.attrs.depth as number) + 1}`, { itemtype: 'http://schema.stenci.la/Heading', itemscope: '' }, 0, ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `List` * * See https://github.com/ProseMirror/prosemirror-schema-list/blob/master/src/schema-list.js * for slightly different node specs for lists. */ function list(): NodeSpec { return { group: 'BlockContent', content: 'ListItem*', contentProp: 'items', attrs: { order: { default: 'Unordered' } }, parseDOM: [ { tag: 'ul', attrs: { order: 'Unordered' } }, { tag: 'ol', attrs: { order: 'Ascending' } }, ], toDOM(node) { return [ node.attrs.order === 'Unordered' ? 'ul' : 'ol', { itemtype: 'http://schema.org/ItemList', itemscope: '' }, 0, ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `ListItem` * * See https://github.com/ProseMirror/prosemirror-schema-list/blob/master/src/schema-list.js#L50 * for why the `content` is defined as it is: to be able to use the commands in `prosemirror-schema-list` * package */ function listItem(): NodeSpec { return { content: 'Paragraph BlockContent*', parseDOM: [{ tag: 'li' }], toDOM(_node) { return [ 'li', { itemtype: 'http://schema.org/ListItem', itemscope: '' }, 0, ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `CodeBlock` * * This is temporary and wil be replaced with a CodeMirror editor * (see https://prosemirror.net/examples/codemirror/ and https://gist.github.com/BrianHung/08146f89ea903f893946963570263040). * * Based on https://github.com/ProseMirror/prosemirror-schema-basic/blob/b5ae707ab1be98a1d8735dfdc7d1845bcd126f18/src/schema-basic.js#L59 */ function codeBlock(): NodeSpec { return { group: 'BlockContent', content: 'text*', contentProp: 'text', marks: '', attrs: { programmingLanguage: { default: '' }, }, code: true, defining: true, parseDOM: [ { tag: 'pre', preserveWhitespace: 'full', getAttrs(dom) { const elem = dom as HTMLElement return { programmingLanguage: elem .querySelector('meta[itemprop="programmingLanguage"][content]') ?.getAttribute('content') ?? elem .querySelector('code[class^="language-"]') ?.getAttribute('class') ?.substring(9), } }, }, ], toDOM(node) { return [ 'pre', { itemtype: 'http://schema.stenci.la/CodeBlock', itemscope: '', // This is just for inspection that language is parsed properly title: node.attrs.programmingLanguage as string, }, ['code', 0], ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `CodeFragment` * * This is temporary and wil be replaced with a CodeMirror editor (as with `CodeBlock`) */ function codeFragment(): NodeSpec { return { inline: true, group: 'InlineContent', content: 'text*', contentProp: 'text', marks: '', attrs: { programmingLanguage: { default: '' }, }, code: true, parseDOM: [{ tag: 'pre', preserveWhitespace: 'full' }], toDOM(_node) { return [ 'code', { itemtype: 'http://schema.stenci.la/CodeFragment', itemscope: '' }, 0, ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `Table` * * This, and other table related schemas are compatible with `prosemirror-tables` (e.g. `tableRole` * and `isolating`) attributes but with Stencila compatible naming. * * See https://github.com/ProseMirror/prosemirror-tables/blob/master/src/schema.js */ function table(): NodeSpec { return { group: 'BlockContent', content: 'TableRow+', contentProp: 'rows', tableRole: 'table', isolating: true, parseDOM: [{ tag: 'table' }], toDOM(_node) { return [ 'table', { itemtype: 'http://schema.org/Table', itemscope: '' }, ['tbody', 0], ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `TableRow`. */ function tableRow(): NodeSpec { return { content: '(TableHeader|TableCell)*', contentProp: 'cells', tableRole: 'row', parseDOM: [{ tag: 'tr' }], toDOM(_node) { return [ 'tr', { itemtype: 'http://schema.stenci.la/TableRow', itemscope: '' }, 0, ] }, } } /** * The attributes of a `TableCell` */ function tableCellAttrsSpec(): Record<string, AttributeSpec> { return { colspan: { default: 1 }, rowspan: { default: 1 }, colwidth: { default: null }, } } /** * Get `TableCell` attributes as part of `parseDOM` */ function tableCellAttrsGet(dom: HTMLElement): Record<string, unknown> { const widthAttr = dom.getAttribute('data-colwidth') ?? '' const widths = /^\d+(,\d+)*$/.test(widthAttr) ? widthAttr.split(',').map((s) => Number(s)) : null const colspan = Number(dom.getAttribute('colspan') ?? 1) return { colspan, rowspan: Number(dom.getAttribute('rowspan') ?? 1), colwidth: widths && widths.length === colspan ? widths : null, } } /** * Set `TableCell` attributes as part of `toDOM` */ function tableCellAttrsSet(node: Node): Record<string, string | number> { const attrs: Record<string, string | number> = { itemtype: 'http://schema.stenci.la/TableCell', itemscope: '', } if (node.attrs.colspan !== 1) attrs.colspan = node.attrs.colspan as number if (node.attrs.rowspan !== 1) attrs.rowspan = node.attrs.rowspan as number if (node.attrs.colwidth != null) attrs['data-colwidth'] = (node.attrs.colwidth as string[]).join(',') return attrs } /** * Generate a `NodeSpec` to represent a Stencila `TableCell`. */ function tableCell(): NodeSpec { return { content: 'InlineContent*', attrs: tableCellAttrsSpec(), tableRole: 'cell', isolating: true, parseDOM: [ { tag: 'td', getAttrs: (dom) => tableCellAttrsGet(dom as HTMLElement) }, ], toDOM(node) { return ['td', tableCellAttrsSet(node), 0] }, } } /** * Generate a `NodeSpec` to represent a Stencila `TableCell` with `cellType` 'Header'. * * The reason this exists as a separate `NodeSpec` to `TableCell` is that the * `prosemirror-tables` package seems to want to have a node type with `tableRole: header_cell` * presumably for its commands to work. * * See https://github.com/ProseMirror/prosemirror-tables/blob/master/src/schema.js#L96 */ function tableHeader(): NodeSpec { return { content: 'InlineContent*', attrs: tableCellAttrsSpec(), tableRole: 'header_cell', isolating: true, parseDOM: [ { tag: 'th', getAttrs: (dom) => tableCellAttrsGet(dom as HTMLElement) }, ], toDOM(node) { return ['th', tableCellAttrsSet(node), 0] }, } } /** * Generate a `NodeSpec` to represent a Stencila `ThematicBreak` */ function thematicBreak(): NodeSpec { return { group: 'BlockContent', parseDOM: [{ tag: 'hr' }], toDOM(_node) { return [ 'hr', { itemtype: 'http://schema.stenci.la/ThematicBreak', itemscope: '' }, ] }, } } /** * Generate a `NodeSpec` to represent a Stencila `InlineContent` node type. */ function _inline( name: string, tag: string, content: string, marks = '_' ): NodeSpec { return { group: 'InlineContent', inline: true, content, marks, parseDOM: [{ tag }], toDOM(_node) { return [ tag, { itemtype: `http://schema.stenci.la/${name}`, itemscope: '' }, 0, ] }, } } /** * Generate a `MarkSpec` to represent a Stencila inline node type. * * @param name The name of the type e.g. `Paragraph` * @param tag The tag name of the HTML element for `toDOM` and `parseDOM`) * @param parseDOM: The parse rules for the mark */ function mark(name: string, tag: string, parseDOM?: ParseRule[]): MarkSpec { return { parseDOM: parseDOM ?? [{ tag }], toDOM(_node) { return [tag, { itemtype: name, itemscope: '' }, 0] }, } }
the_stack
import { MonacoEditor } from "../../app/elements/options/editpages/monaco-editor/monaco-editor"; import { CodeEditBehaviorBase, CodeEditBehaviorStylesheetInstance, CodeEditBehaviorScriptInstance } from "../../app/elements/options/editpages/code-edit-pages/code-edit-behavior"; import { PaperLibrariesSelector } from "../../app/elements/options/editpages/code-edit-pages/tools/paper-libraries-selector/paper-libraries-selector"; import { PaperGetPageProperties } from "../../app/elements/options/editpages/code-edit-pages/tools/paper-get-page-properties/paper-get-page-properties"; import { CrmEditPage } from "../../app/elements/options/crm-edit-page/crm-edit-page"; import { EditCrm } from "../../app/elements/options/edit-crm/edit-crm"; import { EditCrmItem } from "../../app/elements/options/edit-crm-item/edit-crm-item"; import { CenterElement } from "../../app/elements/util/center-element/center-element"; import { PaperSearchWebsiteDialog } from "../../app/elements/options/editpages/code-edit-pages/tools/paper-search-website-dialog/paper-search-website-dialog"; import { UseExternalEditor } from "../../app/elements/options/editpages/code-edit-pages/tools/use-external-editor/use-external-editor"; import { TypeSwitcher } from "../../app/elements/options/type-switcher/type-switcher"; import { PaperDropdownMenu } from "../../app/elements/options/inputs/paper-dropdown-menu/paper-dropdown-menu"; import { AnimatedButton } from "../../app/elements/util/animated-button/animated-button"; import { SplashScreen } from "../../app/elements/util/splash-screen/splash-screen"; import { NodeEditBehaviorMenuInstance, NodeEditBehaviorLinkInstance, NodeEditBehaviorDividerInstance, NodeEditBehaviorBase } from "../../app/elements/options/node-edit-behavior/node-edit-behavior"; import { LogPage } from "../../app/elements/logging/log-page/log-page"; import { LogConsole } from "../../app/elements/logging/log-console/log-console"; import { InstallPage } from "../../app/elements/installing/install-page/install-page"; import { InstallConfirm } from "../../app/elements/installing/install-confirm/install-confirm"; import { ErrorReportingTool } from "../../app/elements/util/error-reporting-tool/error-reporting-tool"; import { DefaultLink } from "../../app/elements/options/default-link/default-link"; import { CrmApp } from "../../app/elements/options/crm-app/crm-app"; import { ChangeLog } from "../../app/elements/util/change-log/change-log"; import { EchoHtml } from "../../app/elements/util/echo-html/echo-html"; import { PaperArrayInput } from "../../app/elements/options/inputs/paper-array-input/paper-array-input"; import { PaperToggleOption } from "../../app/elements/options/inputs/paper-toggle-option/paper-toggle-option"; import { PaperMenu } from "../../app/elements/options/inputs/paper-menu/paper-menu"; import { NeonAnimationBehaviorScaleUpAnimation } from "../../app/elements/util/animations/scale-up-animation/scale-up-animation"; import { NeonAnimationBehaviorScaleDownAnimation } from "../../app/elements/util/animations/scale-down-animation/scale-down-animation"; import { NeonAnimationBehaviorFadeOutAnimation } from "../../app/elements/util/animations/fade-out-animation/fade-out-animation"; import { DividerEdit } from "../../app/elements/options/editpages/divider-edit/divider-edit"; import { PaperDropdownBehaviorBase } from "../../app/elements/options/inputs/paper-dropdown-behavior/paper-dropdown-behavior"; import { LangSelector } from "../../app/elements/util/lang-selector/lang-selector"; export declare namespace Polymer { interface InitializerProperties { is?: string; properties?: { [key: string]: any; } } interface NeonAnimationConfig { node: Polymer.PolymerElement; name: keyof NeonAnimations; } interface NeonAnimationBehaviorBase { complete(): void; isNeonAnimation: true; created(): void; timingFromConfig(): any; setPrefixedProperty(node: Polymer.PolymerElement, property: string, value: string): void; } type NeonAnimationBehavior<T> = T & NeonAnimationBehaviorBase; export interface Polymer { (proto: InitializerProperties): void; telemetry: { registrations: Array<RootElement & { is: string; }>; } CodeEditBehavior: CodeEditBehaviorBase; NodeEditBehavior: NodeEditBehaviorBase; PaperDropdownBehavior: PaperDropdownBehaviorBase; NeonAnimationBehavior: NeonAnimationBehaviorBase; IronMenuBehavior: { selected: number; }; } interface _Slottable { readonly assignedSlot: HTMLSlotElement | null; } //Basically an HTMLElement with all queryselector methods set to return null type WebcomponentElement = Animatable & GlobalEventHandlers & DocumentAndElementEventHandlers & ElementContentEditable & HTMLOrSVGElement & ElementCSSInlineStyle & NonDocumentTypeChildNode & _Slottable & Animatable & EventTarget & { accessKey: string; readonly accessKeyLabel: string; autocapitalize: string; dir: string; draggable: boolean; hidden: boolean; innerText: string; lang: string; readonly offsetHeight: number; readonly offsetLeft: number; readonly offsetParent: Element | null; readonly offsetTop: number; readonly offsetWidth: number; spellcheck: boolean; title: string; translate: boolean; click(): void; addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; readonly assignedSlot: HTMLSlotElement | null; readonly attributes: NamedNodeMap; readonly classList: DOMTokenList; className: string; readonly clientHeight: number; readonly clientLeft: number; readonly clientTop: number; readonly clientWidth: number; id: string; innerHTML: string; readonly localName: string; readonly namespaceURI: string | null; onfullscreenchange: ((this: Element, ev: Event) => any) | null; onfullscreenerror: ((this: Element, ev: Event) => any) | null; outerHTML: string; readonly prefix: string | null; readonly scrollHeight: number; scrollLeft: number; scrollTop: number; readonly scrollWidth: number; readonly shadowRoot: ShadowRoot | null; slot: string; readonly tagName: string; attachShadow(init: ShadowRootInit): ShadowRoot; closest<K extends keyof HTMLElementTagNameMap>(selector: K): HTMLElementTagNameMap[K] | null; closest<K extends keyof SVGElementTagNameMap>(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; getAttribute(qualifiedName: string): string | null; getAttributeNS(namespace: string | null, localName: string): string | null; getAttributeNames(): string[]; getAttributeNode(name: string): Attr | null; getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getBoundingClientRect(): DOMRect; getClientRects(): DOMRectList; getElementsByClassName(classNames: string): HTMLCollectionOf<Element>; getElementsByTagName<K extends keyof HTMLElementTagNameMap>(qualifiedName: K): HTMLCollectionOf<HTMLElementTagNameMap[K]>; getElementsByTagName<K extends keyof SVGElementTagNameMap>(qualifiedName: K): HTMLCollectionOf<SVGElementTagNameMap[K]>; getElementsByTagName(qualifiedName: string): HTMLCollectionOf<Element>; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf<HTMLElement>; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf<SVGElement>; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf<Element>; hasAttribute(qualifiedName: string): boolean; hasAttributeNS(namespace: string | null, localName: string): boolean; hasAttributes(): boolean; hasPointerCapture(pointerId: number): boolean; insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; matches(selectors: string): boolean; msGetRegionContent(): any; releasePointerCapture(pointerId: number): void; removeAttribute(qualifiedName: string): void; removeAttributeNS(namespace: string | null, localName: string): void; removeAttributeNode(attr: Attr): Attr; requestFullscreen(options?: FullscreenOptions): Promise<void>; requestPointerLock(): void; scroll(options?: ScrollToOptions): void; scroll(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; scrollBy(x: number, y: number): void; scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scrollTo(options?: ScrollToOptions): void; scrollTo(x: number, y: number): void; setAttribute(qualifiedName: string, value: string): void; setAttributeNS(namespace: string | null, qualifiedName: string, value: string): void; setAttributeNode(attr: Attr): Attr | null; setAttributeNodeNS(attr: Attr): Attr | null; setPointerCapture(pointerId: number): void; toggleAttribute(qualifiedName: string, force?: boolean): boolean; webkitMatchesSelector(selectors: string): boolean; addEventListener<K extends keyof ElementEventMap>(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof ElementEventMap>(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; readonly baseURI: string; readonly childNodes: NodeListOf<ChildNode>; readonly firstChild: ChildNode | null; readonly isConnected: boolean; readonly lastChild: ChildNode | null; readonly nextSibling: ChildNode | null; readonly nodeName: string; readonly nodeType: number; nodeValue: string | null; readonly ownerDocument: Document | null; readonly parentElement: HTMLElement | null; readonly parentNode: Node & ParentNode | null; readonly previousSibling: ChildNode | null; textContent: string | null; appendChild<T extends Node>(newChild: T): T; cloneNode(deep?: boolean): Node; compareDocumentPosition(other: Node): number; contains(other: Node | null): boolean; hasChildNodes(): boolean; insertBefore<T extends Node>(newChild: T, refChild: Node | null): T; isDefaultNamespace(namespace: string | null): boolean; isEqualNode(otherNode: Node | null): boolean; isSameNode(otherNode: Node | null): boolean; lookupNamespaceURI(prefix: string | null): string | null; lookupPrefix(namespace: string | null): string | null; normalize(): void; removeChild<T extends Node>(oldChild: T): T; replaceChild<T extends Node>(newChild: Node, oldChild: T): T; readonly ATTRIBUTE_NODE: number; readonly CDATA_SECTION_NODE: number; readonly COMMENT_NODE: number; readonly DOCUMENT_FRAGMENT_NODE: number; readonly DOCUMENT_NODE: number; readonly DOCUMENT_POSITION_CONTAINED_BY: number; readonly DOCUMENT_POSITION_CONTAINS: number; readonly DOCUMENT_POSITION_DISCONNECTED: number; readonly DOCUMENT_POSITION_FOLLOWING: number; readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; readonly DOCUMENT_POSITION_PRECEDING: number; readonly DOCUMENT_TYPE_NODE: number; readonly ELEMENT_NODE: number; readonly ENTITY_NODE: number; readonly ENTITY_REFERENCE_NODE: number; readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; readonly childElementCount: number; readonly children: HTMLCollection; readonly firstElementChild: Element | null; readonly lastElementChild: Element | null; append(...nodes: (Node | string)[]): void; prepend(...nodes: (Node | string)[]): void; after(...nodes: (Node | string)[]): void; before(...nodes: (Node | string)[]): void; remove(): void; replaceWith(...nodes: (Node | string)[]): void; querySelector(selector: string): null; querySelectorAll(selectors: string): null; getElementsByClassName(classNames: string): null; getElementsByTagName(name: string): null; getElementsByTagNameNS(namespaceURI: string, localName: string): null; } & ElementBase; export interface ElementI18N { lang: string|null; langReady: boolean; __(_lang: string, _langReady: boolean, key: string, ...replacements: string[]): string; __async(key: string, ...replacements: string[]): Promise<string>; ___(key: string, ...replacements: string[]): string; } export type RootElement = WebcomponentElement & ElementI18N & { __isAnimationJqueryPolyfill: boolean; disabled: boolean; getRootNode(): ShadowRoot; } type CustomEventNoPath = { detail: { sourceEvent: MouseEvent; }; target: PolymerElement; type: string; stopPropagation(): void; preventDefault(): void; } type CustomEventBase = (CustomEventNoPath & { Aa: EventPath; })|(CustomEventNoPath & { path: EventPath; }); type EventType<T extends string, D> = CustomEventBase & { type: T; detail: { sourceEvent: MouseEvent } & D; } type CustomEvent = PolymerDragEvent|ClickEvent|PolymerKeyDownEvent; export type ClickEvent = CustomEventBase & { type: 'tap'; clientX: number; clientY: number; } export type PolymerKeyDownEvent = CustomEventBase & { type: 'keydown'; srcElement: PolymerElement; key: string; code: string; } export type PolymerDragEvent = CustomEventBase & { detail: { state: 'start'|'end'|'track'; sourceEvent: MouseEvent; x: number; y: number; dx: number; dy: number; } type: 'drag'; } export interface EventMap { 'drag': PolymerDragEvent; 'tap': ClickEvent; } export type PolymerElement = HTMLElement | HTMLPaperIconButtonElement | HTMLPaperDialogElement | HTMLPaperInputElement | HTMLPaperCheckboxElement | CenterElement | HTMLDomRepeatElement | PaperToggleOption | HTMLPaperToastElement | DefaultLink | EchoHtml | DividerEdit | HTMLPaperRadioGroupElement | HTMLDomIfElement | HTMLPaperRipplElement; export type EventPath = Array<PolymerElement|DocumentFragment>; interface ElementBase { $$<K extends keyof ElementTagNameMaps>(selector: K): ElementTagNameMaps[K] | null; $$<S extends keyof SelectorMap>(selector: S): SelectorMap[S] | null; $$(selector: string): HTMLElement | Polymer.RootElement | null; async(callback: () => void, time: number): void; splice<T>(property: string, index: number, toRemove: number, replaceWith?: T): Array<T>; push<T>(property: string, item: any): number; set(property: string, value: any): void; fire(eventName: string, data: any): void; notifyPath(path: string, value: any): void; _logf<T extends any>(...args: Array<T>): Array<string & T>; _warn: typeof console.warn; } interface BehaviorMap { 'node-edit-behavior': ModuleMap[ 'divider-edit'|'link-edit'|'menu-edit'| 'script-edit'|'stylesheet-edit' ]; 'paper-dropdown-behavior': ModuleMap[ 'paper-dropdown-menu'|'paper-get-page-properties'| 'paper-libraries-selector' ]; 'code-edit-behavior': ModuleMap[ 'script-edit'|'stylesheet-edit' ]; } interface NeonAnimations { 'scale-up-animation': NeonAnimationBehaviorScaleUpAnimation; 'scale-down-animation': NeonAnimationBehaviorScaleDownAnimation; 'fade-out-animation': NeonAnimationBehaviorFadeOutAnimation; } type PolymerMap = ModuleMap & BehaviorMap & { 'elementless': {} }; export type El<N extends keyof PolymerMap, T extends InitializerProperties> = RootElement & T & { $: PolymerMap[N] }; export type ElementTagNameMap = { 'paper-icon-button': HTMLPaperIconButtonElement; 'paper-dialog': HTMLPaperDialogElement; 'paper-toast': HTMLPaperToastElement; 'paper-input': HTMLPaperInputElement; 'paper-input-container': HTMLPaperInputContainerElement; 'paper-checkbox': HTMLPaperCheckboxElement; 'dom-repeat': HTMLDomRepeatElement; 'dom-if': HTMLDomIfElement; 'paper-menu': HTMLPaperMenuElement; 'paper-spinner': HTMLPaperSpinnerElement; 'paper-radio-group': HTMLPaperRadioGroupElement; 'paper-radio-button': HTMLPaperRadioButtonElement; 'paper-material': HTMLPaperMaterialElement; 'paper-button': HTMLPaperButtonElement; 'paper-textarea': HTMLPaperTextareaElement; 'paper-item': HTMLPaperItemElement; 'paper-toggle-button': HTMLPaperToggleButtonElement; 'paper-toolbar': HTMLPaperToolbarElement; 'paper-libraries-selector': HTMLPaperLibrariesSelectorElement; 'paper-get-page-properties': HTMLPaperGetPagePropertiesElement; 'crm-edit-page': HTMLCrmEditPageElement; 'paper-toggle-option': HTMLPaperToggleOptionElement; 'edit-crm': HTMLEditCrmElement; 'edit-crm-item': HTMLEditCrmItemElement; 'center-element': HTMLCenterElementElement; 'paper-serach-website-dialog': HTMLPaperSearchWebsiteDialogElement; 'use-external-editor': HTMLUseExternalEditorElement; 'type-switcher': HTMLTypeSwitcherElement; 'paper-dropdown-menu': HTMLPaperDropdownMenuElement; 'paper-array-input': HTMLPaperArrayInputElement; 'paper-ripple': HTMLPaperRipplElement; 'slot': HTMLSlotElement; 'animated-button': HTMLAnimatedButtonElement; }; } declare const Polymer: Polymer.Polymer; export type ElementTagNameMaps = Polymer.ElementTagNameMap & HTMLElementTagNameMap & ElementTagNameMap; declare global { interface AddedPermissionsTabContainer extends HTMLElement { tab: number; maxTabs: number; } interface CodeSettingsDialog extends HTMLPaperDialogElement { item?: CRM.ScriptNode | CRM.StylesheetNode; } type ScriptUpdatesToast = HTMLPaperToastElement & { index: number; scripts: Array<{ name: string; oldVersion: string; newVersion: string; }>; }; type VersionUpdateDialog = HTMLPaperDialogElement & { editorManager: MonacoEditor; }; //Polymer elements interface HTMLPaperIconButtonElement extends Polymer.RootElement { icon: string; } interface PaperDialogBase extends Polymer.RootElement { opened: boolean; toggle(): void; close(): void; open(): void; fit(): void; } interface HTMLPaperDialogElement extends PaperDialogBase { init(): void; } interface HTMLPaperToastElement extends Polymer.RootElement { hide(): void; show(): void; text: string; duration: number; } interface HTMLPaperInputElement extends Polymer.RootElement { invalid: boolean; errorMessage: string; label: string; value: string; } interface HTMLPaperInputContainerElement extends Polymer.RootElement { } interface HTMLPaperCheckboxElement extends Polymer.RootElement { checked: boolean; disabled: boolean; } interface HTMLDomRepeatElement extends Polymer.RootElement { items: Array<any>; as: string; render(): void; } interface HTMLDomIfElement extends Polymer.RootElement { if: boolean; render(): void; } type HTMLPaperMenuElement = PaperMenu; interface HTMLPaperSpinnerElement extends Polymer.RootElement { active: boolean; } interface HTMLPaperRadioGroupElement extends Polymer.RootElement { selected: string; } interface HTMLPaperRadioButtonElement extends Polymer.RootElement { checked: boolean; } interface HTMLPaperMaterialElement extends Polymer.RootElement { elevation: string; } interface HTMLPaperButtonElement extends Polymer.RootElement { } interface HTMLPaperTextareaElement extends Polymer.RootElement { invalid: boolean; value: string; } interface HTMLPaperItemElement extends Polymer.RootElement { } interface HTMLPaperToggleButtonElement extends Polymer.RootElement { checked: boolean; } interface HTMLPaperToolbarElement extends Polymer.RootElement { } interface SVGElement { readonly style: CSSStyleDeclaration; } interface HTMLMetadataElement extends SVGElement {} interface HTMLGElement extends SVGElement {} interface HTMLPathElement extends SVGElement {} interface HTMLRectElement extends SVGElement {} type HTMLPaperLibrariesSelectorElement = PaperLibrariesSelector; type HTMLPaperGetPagePropertiesElement = PaperGetPageProperties; type HTMLCrmEditPageElement = CrmEditPage; type HTMLPaperToggleOptionElement = PaperToggleOption; type HTMLEditCrmElement = EditCrm; type HTMLEditCrmItemElement = EditCrmItem; type HTMLCenterElementElement = CenterElement; type HTMLPaperSearchWebsiteDialogElement = PaperSearchWebsiteDialog; type HTMLUseExternalEditorElement = UseExternalEditor; type HTMLTypeSwitcherElement = TypeSwitcher; type HTMLPaperDropdownMenuElement = PaperDropdownMenu; type HTMLPaperArrayInputElement = PaperArrayInput; type HTMLPaperRipplElement = HTMLElement; type HTMLEchoHtmlElement = EchoHtml; type HTMLMonacoEditorElement = MonacoEditor; type HTMLChangeLogElement = ChangeLog; type HTMLCrmAppElement = CrmApp; type HTMLDefaultLinkElement = DefaultLink; type HTMLDividerEditElement = NodeEditBehaviorDividerInstance; type HTMLErrorReportingToolElement = ErrorReportingTool; type HTMLInstallConfirmElement = InstallConfirm; type HTMLInstallErrorElement = Polymer.El<'install-error', {}>; type HTMLInstallPageElement = InstallPage; type HTMLLinkEditElement = NodeEditBehaviorLinkInstance; type HTMLLogConsoleElement = LogConsole; type HTMLLogPageElement = LogPage; type HTMLMenuEditElement = NodeEditBehaviorMenuInstance; type HTMLScriptEditElement = CodeEditBehaviorScriptInstance; type HTMLStylesheetEditElement = CodeEditBehaviorStylesheetInstance; type HTMLSplashScreenElement = SplashScreen; type HTMLAnimatedButtonElement = AnimatedButton; type HTMLLangSelectorElement = LangSelector; interface GenericNodeList<TNode> { readonly length: number; item(index: number): TNode|null; /** * Performs the specified action for each node in an list. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: TNode, key: number, parent: GenericNodeList<TNode>) => void, thisArg?: any): void; [index: number]: TNode; } interface NodeSelector { querySelector<K extends keyof ElementTagNameMaps>(selectors: K): ElementTagNameMaps[K] | null; querySelector(selectors: string): HTMLElement | null; querySelectorAll<K extends keyof Polymer.ElementTagNameMap>(selectors: K): GenericNodeList<Polymer.ElementTagNameMap[K]> | null; } interface ParentNode { querySelector<K extends keyof ElementTagNameMaps>(selectors: K): ElementTagNameMaps[K] | null; querySelector(selectors: string): HTMLElement | null; querySelectorAll<K extends keyof Polymer.ElementTagNameMap>(selectors: K): GenericNodeList<Polymer.ElementTagNameMap[K]> | null; } }
the_stack
import * as path from 'path'; import {Label} from '@microsoft/bf-dispatcher'; import {LabelType} from '@microsoft/bf-dispatcher'; import {LabelStructureUtility} from '@microsoft/bf-dispatcher'; import {OrchestratorHelper} from './orchestratorhelper'; import {Utility} from './utility'; import {Utility as UtilityDispatcher} from '@microsoft/bf-dispatcher'; const oc: any = require('@microsoft/orchestrator-core'); export class LabelResolver { public static Orchestrator: any; public static LabelResolver: any; public static async loadNlrAsync(baseModelPath: string, entityBaseModelPath: string = '') { Utility.debuggingLog('LabelResolver.loadNlrAsync(): creating Orchestrator.'); Utility.debuggingLog(`LabelResolver.loadNlrAsync(): baseModelPath=${baseModelPath}`); Utility.debuggingLog(`LabelResolver.loadNlrAsync(): entityBaseModelPath=${entityBaseModelPath}`); if (baseModelPath) { baseModelPath = path.resolve(baseModelPath); } if (entityBaseModelPath) { entityBaseModelPath = path.resolve(entityBaseModelPath); } Utility.debuggingLog(`LabelResolver.loadNlrAsync(): baseModelPath-resolved=${baseModelPath}`); Utility.debuggingLog(`LabelResolver.loadNlrAsync(): entityBaseModelPath-resolved=${entityBaseModelPath}`); const hasBaseModel: boolean = !Utility.isEmptyString(baseModelPath); const hasEntityBaseModel: boolean = !Utility.isEmptyString(entityBaseModelPath); LabelResolver.Orchestrator = new oc.Orchestrator(); if (hasBaseModel) { if (hasEntityBaseModel) { Utility.debuggingLog('LabelResolver.loadNlrAsync(): loading intent and entity base model'); if (await LabelResolver.Orchestrator.loadAsync(baseModelPath, entityBaseModelPath) === false) { throw new Error(`Failed calling LabelResolver.Orchestrator.loadAsync("${baseModelPath}, ${entityBaseModelPath}")!`); } } else { Utility.debuggingLog('LabelResolver.loadNlrAsync(): loading intent base model'); if (await LabelResolver.Orchestrator.loadAsync(baseModelPath) === false) { throw new Error(`Failed calling LabelResolver.Orchestrator.loadAsync("${baseModelPath}")!`); } } } else if (LabelResolver.Orchestrator.load() === false) { Utility.debuggingLog('LabelResolver.loadNlrAsync(): no intent or entity base model'); throw new Error('Failed calling LabelResolver.Orchestrator.load()!'); } Utility.debuggingLog('LabelResolver.loadNlrAsync(): leaving.'); return LabelResolver.Orchestrator; } public static createLabelResolver(snapshot?: Uint8Array) { if (snapshot) { return LabelResolver.Orchestrator.createLabelResolver(snapshot); } return LabelResolver.Orchestrator.createLabelResolver(); } public static async createAsync(baseModelPath: string, entityBaseModelPath: string = '', useLoadedNlr: boolean = false) { Utility.debuggingLog(`LabelResolver.createAsync(): baseModelPath=${baseModelPath}, entityBaseModelPath=${entityBaseModelPath}`); // don't need to reload base model again if one is already loaded if (useLoadedNlr && LabelResolver.Orchestrator && LabelResolver.LabelResolver) { return LabelResolver.LabelResolver; } const hasEntityBaseModel: boolean = !Utility.isEmptyString(entityBaseModelPath); if (hasEntityBaseModel) { await LabelResolver.loadNlrAsync(baseModelPath, entityBaseModelPath); } else { await LabelResolver.loadNlrAsync(baseModelPath); } Utility.debuggingLog('LabelResolver.createAsync(): Creating label resolver.'); LabelResolver.LabelResolver = LabelResolver.Orchestrator.createLabelResolver(); Utility.debuggingLog('LabelResolver.createAsync(): Finished creating label resolver.'); return LabelResolver.LabelResolver; } public static async createWithSnapshotFileAsync(baseModelPath: string, snapshotPath: string, entityBaseModelPath: string = '') { Utility.debuggingLog('LabelResolver.createWithSnapshotAsync(): loading a snapshot.'); const snapshot: Uint8Array = OrchestratorHelper.getSnapshotFromFile(snapshotPath); return LabelResolver.createWithSnapshotAsync(baseModelPath, snapshot, entityBaseModelPath); } public static async createWithSnapshotAsync(baseModelPath: string, snapshot: Uint8Array, entityBaseModelPath: string = '') { Utility.debuggingLog(`LabelResolver.createWithSnapshotAsync(): baseModelPath=${baseModelPath}, entityBaseModelPath=${entityBaseModelPath}`); await LabelResolver.loadNlrAsync(baseModelPath, entityBaseModelPath); Utility.debuggingLog(`LabelResolver.createWithSnapshotAsync(): typeof(snapshot)=${typeof snapshot}`); Utility.debuggingLog(`LabelResolver.createWithSnapshotAsync(): snapshot.byteLength=${snapshot.byteLength}`); Utility.debuggingLog('LabelResolver.createWithSnapshotAsync(): creating label resolver.'); LabelResolver.LabelResolver = await LabelResolver.Orchestrator.createLabelResolver(snapshot); if (!LabelResolver.LabelResolver) { throw new Error('FAILED to create a LabelResolver object'); } Utility.debuggingLog('LabelResolver.createWithSnapshotAsync(): finished creating label resolver.'); return LabelResolver.LabelResolver; } public static createSnapshot(labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.createSnapshot(); } public static addSnapshot(snapshot: any, prefix: string = '', labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.addSnapshot(snapshot, prefix); } public static addExample(example: any, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.addExample(example); } public static removeExample(example: any, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.removeExample(example); } public static removeLabel(label: string, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.removeLabel(label); } public static getExamples(labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.getExamples(); } public static getExamplesWithLabelName(labelName: string, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.getExamples(labelName); } public static getExamplesWithLabelType(labelType: LabelType, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); const labelTypeInNumber: number = LabelStructureUtility.labelTypeToNumber(labelType); Utility.debuggingLog(`LabelResolver.getExamplesWithLabelType(), labelTypeInNumber=${labelTypeInNumber}`); return labelResolver.getExamples(labelTypeInNumber); } public static getLabels(labelType: LabelType, labelResolver: any = null) { Utility.debuggingLog('CALLING LabelResolver.getLabels()'); labelResolver = LabelResolver.ensureLabelResolver(labelResolver); Utility.debuggingLog('LabelResolver.getLabels(), after calling LabelResolver.ensureLabelResolver()'); Utility.debuggingLog(`LabelResolver.getLabels(), labelResolver=${labelResolver}`); const labels: any = labelResolver.getLabels(labelType); Utility.debuggingLog(`LabelResolver.getLabels(), labels=${labels}`); Utility.debuggingLog('LEAVING LabelResolver.getLabels()'); return labels; } public static score(utterance: string, labelType: LabelType, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.score(utterance, labelType); } public static scoreBatch(utterances: string[], labelType: LabelType, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.scoreBatch(utterances, labelType); } public static getConfigJson(labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.getConfigJson(); } public static setRuntimeParams(config: string, resetAll: boolean, labelResolver: any = null) { labelResolver = LabelResolver.ensureLabelResolver(labelResolver); return labelResolver.setRuntimeParams(config, resetAll); } // eslint-disable-next-line complexity public static addBatch( utteranceIntentEntityLabels: { utteranceLabelsMap: Map<string, Set<string>>; utteranceLabelDuplicateMap: Map<string, Set<string>>; utteranceEntityLabelsMap: Map<string, Label[]>; utteranceEntityLabelDuplicateMap: Map<string, Label[]>; }, labelResolver: any = null, addBatchOption: number = 2): any { Utility.debuggingLog('CALLING LabelResolver.addBatch()'); if (labelResolver === null) { labelResolver = LabelResolver.LabelResolver; } Utility.debuggingLog(`LabelResolver.addBatch(): utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.addBatch(): utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); Utility.debuggingLog(`LabelResolver.addBatch(): utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.addBatch(): utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); // ----------------------------------------------------------------------- UtilityDispatcher.debuggingLog('LabelResolver.addBatch(): ready to call LabelResolver.utteranceLabelsToJsonString()'); const batchJsonified: string = LabelResolver.utteranceLabelsToJsonString( utteranceIntentEntityLabels); UtilityDispatcher.debuggingLog('LabelResolver.addBatch(): finished calling LabelResolver.utteranceLabelsToJsonString()'); if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('LabelResolver.addBatch(): batchJsonified', batchJsonified, 'batchJsonified'); } // ----------------------------------------------------------------------- UtilityDispatcher.debuggingNamedLog1('LabelResolver.addBatch(): ready to call TextEncoder().encode()', batchJsonified.length, 'batchJsonified.length'); const batchUint8Array: Uint8Array = UtilityDispatcher.stringToUtf8EncodedUint8Array(batchJsonified); UtilityDispatcher.debuggingNamedLog1('LabelResolver.addBatch(): finished calling TextEncoder().encode()', batchJsonified.length, 'batchJsonified.length'); if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingLog(`LabelResolver.addBatch(): batchUint8Array=${batchUint8Array}`); } // ----------------------------------------------------------------------- let batchResults: any; try { UtilityDispatcher.debuggingNamedLog1('LabelResolver.addBatch(): ready to call labelResolver.addBatch()', addBatchOption, 'addBatchOption'); batchResults = labelResolver.addBatch(batchUint8Array, '', addBatchOption); UtilityDispatcher.debuggingNamedLog1('LabelResolver.addBatch(): finished calling labelResolver.addBatch()', batchResults, 'batchResults'); } catch (error) { UtilityDispatcher.debuggingNamedThrow1('LabelResolver.addBatch(): Failed adding error:', error, 'error'); } // ----------------------------------------------------------------------- Utility.debuggingLog('LEAVING LabelResolver.addBatch()'); return batchResults; } // eslint-disable-next-line complexity public static utteranceLabelsToJsonString( utteranceIntentEntityLabels: { utteranceLabelsMap: Map<string, Set<string>>; utteranceLabelDuplicateMap: Map<string, Set<string>>; utteranceEntityLabelsMap: Map<string, Label[]>; utteranceEntityLabelDuplicateMap: Map<string, Label[]>; }): string { Utility.debuggingLog('CALLING LabelResolver.utteranceLabelsToJsonString()'); Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); // ----------------------------------------------------------------------- const utteranceLabelsMap: Map<string, Set<string>> = utteranceIntentEntityLabels.utteranceLabelsMap; Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); let numberUtterancesProcessedUtteranceLabelsMap: number = 0; // ----------------------------------------------------------------------- const utteranceEntityLabelsMap: Map<string, Label[]> = utteranceIntentEntityLabels.utteranceEntityLabelsMap; Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); let numberUtterancesProcessedUtteranceEntityLabelsMap: number = 0; // ----------------------------------------------------------------------- // ---- Utility.toPrintDetailedDebuggingLogToConsole = true; // ---- NOTE ---- disable after detailed tracing is done. const batchJsonifiedStringArray: string[] = []; batchJsonifiedStringArray.push('{"examples": ['); let isFirstUtterance: boolean = true; for (const utterance of utteranceLabelsMap.keys()) { if (isFirstUtterance) { isFirstUtterance = false; } else { batchJsonifiedStringArray.push(','); } batchJsonifiedStringArray.push(`{"text": ${JSON.stringify(utterance)},`); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): processing utterance='${utterance}'`); } batchJsonifiedStringArray.push('"intents": ['); { const labels: Set<string> = utteranceLabelsMap.get(utterance) as Set<string>; if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString()-Intent: Adding { labels.size: ${labels.size}, text: ${utterance} }`); } if (labels && (labels.size > 0)) { let isFirst: boolean = true; for (const label of labels) { if (isFirst) { isFirst = false; } else { batchJsonifiedStringArray.push(','); } batchJsonifiedStringArray.push(`{"name": ${JSON.stringify(label)}, "offset": 0, "length": 0}`); } } numberUtterancesProcessedUtteranceLabelsMap++; if ((numberUtterancesProcessedUtteranceLabelsMap % Utility.NumberOfInstancesPerProgressDisplayBatchForIntent) === 0) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): Added numberUtterancesProcessedUtteranceLabelsMap=${numberUtterancesProcessedUtteranceLabelsMap}`); } } batchJsonifiedStringArray.push('],'); // ---- "intents" batchJsonifiedStringArray.push('"entities": ['); // eslint-disable-next-line no-lone-blocks { if (utteranceEntityLabelsMap.has(utterance)) { const labelsEntities: Label[] = utteranceEntityLabelsMap.get(utterance) as Label[]; if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString()-Entity: Adding { labelsEntities.length: ${labelsEntities.length}, text: ${utterance} }`); } if (labelsEntities && (labelsEntities.length > 0)) { let isFirst: boolean = true; for (const labelEntity of labelsEntities) { // eslint-disable-next-line max-depth if (isFirst) { isFirst = false; } else { batchJsonifiedStringArray.push(','); } batchJsonifiedStringArray.push(`{"name": ${JSON.stringify(labelEntity.name)}, "offset": ${labelEntity.span.offset}, "length": ${labelEntity.span.length}}`); } } numberUtterancesProcessedUtteranceEntityLabelsMap++; if ((numberUtterancesProcessedUtteranceEntityLabelsMap % Utility.NumberOfInstancesPerProgressDisplayBatchForEntity) === 0) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): Added numberUtterancesProcessedUtteranceEntityLabelsMap=${numberUtterancesProcessedUtteranceEntityLabelsMap}`); } } } batchJsonifiedStringArray.push(']'); // ---- "entities" batchJsonifiedStringArray.push('}'); // ---- example / "text" } batchJsonifiedStringArray.push(']}'); // ---- "examples" Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): Added numberUtterancesProcessedUtteranceLabelsMap=${numberUtterancesProcessedUtteranceLabelsMap}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToJsonString(): Added numberUtterancesProcessedUtteranceEntityLabelsMap=${numberUtterancesProcessedUtteranceEntityLabelsMap}`); // ----------------------------------------------------------------------- Utility.debuggingLog('LEAVING LabelResolver.utteranceLabelsToJsonString()'); return batchJsonifiedStringArray.join(' '); } // eslint-disable-next-line complexity public static utteranceLabelsToObjectJsonString( utteranceIntentEntityLabels: { utteranceLabelsMap: Map<string, Set<string>>; utteranceLabelDuplicateMap: Map<string, Set<string>>; utteranceEntityLabelsMap: Map<string, Label[]>; utteranceEntityLabelDuplicateMap: Map<string, Label[]>; }): string { Utility.debuggingLog('CALLING LabelResolver.utteranceLabelsToObjectJsonString()'); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObjectJsonString(): utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObjectJsonString(): utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObjectJsonString(): utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObjectJsonString(): utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); // ----------------------------------------------------------------------- const batch: { 'examples': Array<{ 'text': string; 'intents': Array<{ 'name': string; 'offset': number; 'length': number; }>; 'entities': Array<{ 'name': string; 'offset': number; 'length': number; }>; }>; } = LabelResolver.utteranceLabelsToObject(utteranceIntentEntityLabels); // ----------------------------------------------------------------------- UtilityDispatcher.debuggingLog('LabelResolver.utteranceLabelsToObjectJsonString(): ready to call JSON.stringify()'); const batchJsonified: string = JSON.stringify(batch); UtilityDispatcher.debuggingLog('LabelResolver.utteranceLabelsToObjectJsonString(): finished calling JSON.stringify()'); if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('LabelResolver.utteranceLabelsToObjectJsonString(): batchJsonified', batchJsonified, 'batchJsonified'); } // ----------------------------------------------------------------------- Utility.debuggingLog('LEAVING LabelResolver.utteranceLabelsToObjectJsonString()'); return batchJsonified; } // eslint-disable-next-line complexity public static utteranceLabelsToObject( utteranceIntentEntityLabels: { utteranceLabelsMap: Map<string, Set<string>>; utteranceLabelDuplicateMap: Map<string, Set<string>>; utteranceEntityLabelsMap: Map<string, Label[]>; utteranceEntityLabelDuplicateMap: Map<string, Label[]>; }): { 'examples': Array<{ 'text': string; 'intents': Array<{ 'name': string; 'offset': number; 'length': number; }>; 'entities': Array<{ 'name': string; 'offset': number; 'length': number; }>; }>; } { Utility.debuggingLog('CALLING LabelResolver.utteranceLabelsToObject()'); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); // ----------------------------------------------------------------------- const examples: Array<{ 'text': string; 'intents': Array<{ 'name': string; 'offset': number; 'length': number; }>; 'entities': Array<{ 'name': string; 'offset': number; 'length': number; }>; }> = new Array<{ text: string; intents: Array<{ name: string; offset: number; length: number; }>; entities: Array<{ name: string; offset: number; length: number; }>; }>(); const batch: { 'examples': Array<{ 'text': string; 'intents': Array<{ 'name': string; 'offset': number; 'length': number; }>; 'entities': Array<{ 'name': string; 'offset': number; 'length': number; }>; }>; } = { examples, }; // ----------------------------------------------------------------------- UtilityDispatcher.debuggingNamedLog1('LabelResolver.utteranceLabelsToObject(), empty batch', batch, 'batch'); // ----------------------------------------------------------------------- const utteranceLabelsMap: Map<string, Set<string>> = utteranceIntentEntityLabels.utteranceLabelsMap; Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); let numberUtterancesProcessedUtteranceLabelsMap: number = 0; // ----------------------------------------------------------------------- const utteranceEntityLabelsMap: Map<string, Label[]> = utteranceIntentEntityLabels.utteranceEntityLabelsMap; Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); let numberUtterancesProcessedUtteranceEntityLabelsMap: number = 0; // ----------------------------------------------------------------------- // ---- Utility.toPrintDetailedDebuggingLogToConsole = true; // ---- NOTE ---- disable after detailed tracing is done. for (const utterance of utteranceLabelsMap.keys()) { if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): processing utterance='${utterance}'`); } const intents: Array<{ 'name': string; 'offset': number; 'length': number; }> = []; { const labels: Set<string> = utteranceLabelsMap.get(utterance) as Set<string>; if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject()-Intent: Adding { labels.size: ${labels.size}, text: ${utterance} }`); } if (labels && (labels.size > 0)) { for (const label of labels) { intents.push({ name: label, offset: 0, length: 0, }); } } numberUtterancesProcessedUtteranceLabelsMap++; if ((numberUtterancesProcessedUtteranceLabelsMap % Utility.NumberOfInstancesPerProgressDisplayBatchForIntent) === 0) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): Added numberUtterancesProcessedUtteranceLabelsMap=${numberUtterancesProcessedUtteranceLabelsMap}`); } } const entities: Array<{ 'name': string; 'offset': number; 'length': number; }> = []; // eslint-disable-next-line no-lone-blocks { if (utteranceEntityLabelsMap.has(utterance)) { const labelsEntities: Label[] = utteranceEntityLabelsMap.get(utterance) as Label[]; if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject()-Entity: Adding { labelsEntities.length: ${labelsEntities.length}, text: ${utterance} }`); } if (labelsEntities && (labelsEntities.length > 0)) { for (const labelEntity of labelsEntities) { entities.push({ name: labelEntity.name, offset: labelEntity.span.offset, length: labelEntity.span.length, }); } } numberUtterancesProcessedUtteranceEntityLabelsMap++; if ((numberUtterancesProcessedUtteranceEntityLabelsMap % Utility.NumberOfInstancesPerProgressDisplayBatchForEntity) === 0) { Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): Added numberUtterancesProcessedUtteranceEntityLabelsMap=${numberUtterancesProcessedUtteranceEntityLabelsMap}`); } } } examples.push({ text: utterance, intents: intents, entities: entities, }); } Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): Added numberUtterancesProcessedUtteranceLabelsMap=${numberUtterancesProcessedUtteranceLabelsMap}`); Utility.debuggingLog(`LabelResolver.utteranceLabelsToObject(): Added numberUtterancesProcessedUtteranceEntityLabelsMap=${numberUtterancesProcessedUtteranceEntityLabelsMap}`); // ----------------------------------------------------------------------- Utility.debuggingLog('LEAVING LabelResolver.utteranceLabelsToObject()'); return batch; } // eslint-disable-next-line complexity public static addExamples( utteranceIntentEntityLabels: { utteranceLabelsMap: Map<string, Set<string>>; utteranceLabelDuplicateMap: Map<string, Set<string>>; utteranceEntityLabelsMap: Map<string, Label[]>; utteranceEntityLabelDuplicateMap: Map<string, Label[]>; }, labelResolver: any = null) { Utility.debuggingLog('CALLING LabelResolver.addExamples()'); if (labelResolver === null) { labelResolver = LabelResolver.LabelResolver; } Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); // ----------------------------------------------------------------------- const utteranceLabelsMap: Map<string, Set<string>> = utteranceIntentEntityLabels.utteranceLabelsMap; Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceLabelsMap.size=${utteranceIntentEntityLabels.utteranceLabelsMap.size}`); Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceLabelDuplicateMap.size}`); let numberUtterancesProcessedUtteranceLabelsMap: number = 0; Utility.debuggingLog(`READY to call labelResolver.addExample() on utteranceLabelsMap utterances and labels, utteranceLabelsMap.size=${utteranceLabelsMap.size}`); // ---- Utility.toPrintDetailedDebuggingLogToConsole = true; // ---- NOTE ---- disable after detailed tracing is done. // eslint-disable-next-line guard-for-in for (const utterance of utteranceLabelsMap.keys()) { if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`processing utterance=${utterance}`); } const labels: Set<string> = utteranceLabelsMap.get(utterance) as Set<string>; if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.addExample()-Intent: Adding { labels.size: ${labels.size}, text: ${utterance} }`); } if (labels && (labels.size > 0)) { for (const label of labels) { try { const success: any = labelResolver.addExample({label: label, text: utterance}); // eslint-disable-next-line max-depth if (success) { // eslint-disable-next-line max-depth if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.addExample()-Intent: Added { label: ${label}, text: ${utterance} }`); } } else { Utility.debuggingLog(`LabelResolver.addExample()-Intent: Failed adding { label: ${label}, text: ${utterance} }`); } } catch (error) { Utility.debuggingThrow(`LabelResolver.addExample()-Intent: Failed adding { label: ${label}, text: ${utterance} }\n${error}`); } } } numberUtterancesProcessedUtteranceLabelsMap++; if ((numberUtterancesProcessedUtteranceLabelsMap % Utility.NumberOfInstancesPerProgressDisplayBatchForIntent) === 0) { Utility.debuggingLog(`LabelResolver.addExamples(): Added numberUtterancesProcessedUtteranceLabelsMap=${numberUtterancesProcessedUtteranceLabelsMap}`); } } // ----------------------------------------------------------------------- const utteranceEntityLabelsMap: Map<string, Label[]> = utteranceIntentEntityLabels.utteranceEntityLabelsMap; Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceEntityLabelsMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`processed utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size=${utteranceIntentEntityLabels.utteranceEntityLabelDuplicateMap.size}`); let numberUtterancesProcessedUtteranceEntityLabelsMap: number = 0; Utility.debuggingLog(`READY to call labelResolver.addExample() on utteranceEntityLabelsMap utterances and labels, utteranceEntityLabelsMap.size=${utteranceEntityLabelsMap.size}`); // eslint-disable-next-line guard-for-in for (const utterance of utteranceEntityLabelsMap.keys()) { if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`processing utterance=${utterance}`); } const labels: Label[] = utteranceEntityLabelsMap.get(utterance) as Label[]; if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.addExample()-Entity: Added { labels.length: ${labels.length}, text: ${utterance} }`); } if (labels && (labels.length > 0)) { for (const label of labels) { const entity: string = label.name; const spanOffset: number = label.span.offset; const spanLength: number = label.span.length; try { const success: any = labelResolver.addExample({ text: utterance, labels: [{ name: entity, label_type: 2, span: { offset: spanOffset, length: spanLength}}]}); // eslint-disable-next-line max-depth if (success) { // eslint-disable-next-line max-depth if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`LabelResolver.addExample()-Entity: Added { label: ${label}, text: ${utterance}, offset: ${spanOffset}, length: ${spanLength} }`); } } else { Utility.debuggingLog(`LabelResolver.addExample()-Entity: Failed adding { label: ${label}, text: ${utterance}, offset: ${spanOffset}, length: ${spanLength} }`); } } catch (error) { Utility.debuggingThrow(`LabelResolver.addExample()-Entity: Failed adding { label: ${label}, text: ${utterance}, offset: ${spanOffset}, length: ${spanLength} }\n${error}`); } } } numberUtterancesProcessedUtteranceEntityLabelsMap++; if ((numberUtterancesProcessedUtteranceEntityLabelsMap % Utility.NumberOfInstancesPerProgressDisplayBatchForEntity) === 0) { Utility.debuggingLog(`LabelResolver.addExamples(): Added numberUtterancesProcessedUtteranceEntityLabelsMap=${numberUtterancesProcessedUtteranceEntityLabelsMap}`); } } // ----------------------------------------------------------------------- Utility.debuggingLog('LEAVING LabelResolver.addExamples()'); } private static ensureLabelResolver(labelResolver: any) { if (!labelResolver) { labelResolver = LabelResolver.LabelResolver; } if (!labelResolver) { throw new Error('LabelResolver was not initialized'); } return labelResolver; } }
the_stack
import {async, TestBed, ComponentFixture} from '@angular/core/testing'; import {Component, Renderer, RootRenderer, CUSTOM_ELEMENTS_SCHEMA, ViewEncapsulation} from '@angular/core'; import {PolymerModule} from '../polymer-module'; import {DefaultPolymerRenderer, EmulatedEncapsulationPolymerRenderer, ShadowDomPolymerRenderer, PolymerRootRenderer} from './polymer-renderer'; const Polymer: any = (<any>window).Polymer; @Component({ template: `<test-element [(value)]="value" [(nestedObject)]="nestedObject" [(arrayObject)]="arrayObject" boolean-value></test-element>` }) class RendererTestComponent { constructor(public renderer: Renderer, public rootRenderer: RootRenderer) { } value = 'foo'; nestedObject = {value: undefined}; arrayObject = []; barVisible = false; } @Component({ template: `<p>encapsulation: none</p>`, styles: [`p { order: 1; }`], encapsulation: ViewEncapsulation.None }) class StyleEncapsulationNoneComponent {} @Component({ template: `<p>encapsulation: native</p>`, styles: [`p { order: 2; }`], encapsulation: ViewEncapsulation.Native }) class StyleEncapsulationNativeComponent {} @Component({ template: `<p>encapsulation: emulated</p>`, styles: [`p { order: 3; }`], encapsulation: ViewEncapsulation.Emulated }) class StyleEncapsulationEmulatedComponent {} describe('DefaultPolymerRenderer', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [PolymerModule], declarations: [ RendererTestComponent, StyleEncapsulationNoneComponent ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }); TestBed.compileComponents(); })); let testElement: Element; let testDomApi: any; let renderer: DefaultPolymerRenderer; let rootRenderer: PolymerRootRenderer; beforeEach(() => { const fixture = TestBed.createComponent(RendererTestComponent); const testComponent = fixture.componentInstance; testElement = fixture.nativeElement.firstElementChild; renderer = <DefaultPolymerRenderer> testComponent.renderer; testDomApi = Polymer.dom(testElement); rootRenderer = <PolymerRootRenderer> testComponent.rootRenderer; }); it('is in use', () => { expect(renderer instanceof DefaultPolymerRenderer).toBe(true); }); describe('selectRootElement method', () => { let expectedRoot: Element; beforeEach(() => { expectedRoot = document.createElement('div'); expectedRoot.classList.add('test-root'); // should be selected as root document.body.appendChild(expectedRoot); }); afterEach(() => { document.body.removeChild(expectedRoot); }); it('respects shadow DOM boundaries', () => { (<any> testElement).$.nested.classList.add('test-root'); // should not be selected as root const testRoot = renderer.selectRootElement('.test-root'); expect(testRoot).toBe(expectedRoot); }); it('clears previous content using Polymer.dom API', () => { const spy = jasmine.createSpy('textContentSetterSpy'); const domApi: any = Polymer.dom(expectedRoot); Object.defineProperty(domApi, 'textContent', {set: spy}); renderer.selectRootElement('.test-root'); expect(spy).toHaveBeenCalledWith(''); }); }); describe('tree manipulation', () => { beforeEach(() => { spyOn(testDomApi, 'appendChild').and.callThrough(); spyOn(testDomApi, 'insertBefore').and.callThrough(); spyOn(testDomApi, 'removeChild').and.callThrough(); }); it('implements createElement method', () => { const el = renderer.createElement(testElement, 'foo-element'); expect(el instanceof Element).toBe(true); expect(el.localName).toBe('foo-element'); expect(testDomApi.appendChild).toHaveBeenCalledWith(el); }); it('implements createViewRoot method', () => { const viewRoot = renderer.createViewRoot(testElement); expect(viewRoot).toBe(testElement); }); it('implements createTemplateAnchor method', () => { const anchor = renderer.createTemplateAnchor(testElement); expect(anchor instanceof Node).toBe(true); expect(testDomApi.appendChild).toHaveBeenCalledWith(anchor); }); it('implements createText method', () => { const node = renderer.createText(testElement, 'foo'); expect(node instanceof Node).toBe(true); expect(node.textContent).toBe('foo'); expect(testDomApi.appendChild).toHaveBeenCalledWith(node); }); it('implements projectNodes method', () => { const nodeFoo = document.createTextNode('foo'); const nodeBar = document.createTextNode('bar'); renderer.projectNodes(testElement, [nodeFoo, nodeBar]); expect(Polymer.dom(nodeFoo).parentNode).toBe(testElement); expect(Polymer.dom(nodeBar).parentNode).toBe(testElement); expect(testDomApi.appendChild).toHaveBeenCalledWith(nodeFoo); expect(testDomApi.appendChild).toHaveBeenCalledWith(nodeBar); }); it('implements attachViewAfter method, target node is last child case', () => { const nodeFoo = document.createTextNode('foo'); Polymer.dom(testElement).appendChild(nodeFoo); const viewRootBaz = document.createTextNode('baz'); const viewRootQux = document.createTextNode('qux'); renderer.attachViewAfter(nodeFoo, [viewRootBaz, viewRootQux]); expect(Polymer.dom(viewRootBaz).parentNode).toBe(testElement); expect(Polymer.dom(viewRootQux).parentNode).toBe(testElement); expect(testDomApi.appendChild).toHaveBeenCalledWith(viewRootBaz); expect(testDomApi.appendChild).toHaveBeenCalledWith(viewRootQux); }); it('implements attachViewAfter method, target node is non-last child case', () => { const nodeFoo = document.createTextNode('foo'); const nodeBar = document.createTextNode('bar'); Polymer.dom(testElement).appendChild(nodeFoo); Polymer.dom(testElement).appendChild(nodeBar); const viewRootBaz = document.createTextNode('baz'); const viewRootQux = document.createTextNode('qux'); renderer.attachViewAfter(nodeFoo, [viewRootBaz, viewRootQux]); expect(Polymer.dom(viewRootBaz).parentNode).toBe(testElement); expect(Polymer.dom(viewRootQux).parentNode).toBe(testElement); expect(testDomApi.insertBefore).toHaveBeenCalledWith(viewRootBaz, nodeBar); expect(testDomApi.insertBefore).toHaveBeenCalledWith(viewRootQux, nodeBar); }); it('implements detachView method', () => { const nodeFoo = document.createTextNode('foo'); Polymer.dom(testElement).appendChild(nodeFoo); const viewRootBaz = document.createTextNode('baz'); const viewRootQux = document.createTextNode('qux'); renderer.attachViewAfter(nodeFoo, [viewRootBaz, viewRootQux]); renderer.detachView([viewRootBaz, viewRootQux]); expect(Polymer.dom(viewRootBaz).parentNode).toBe(null); expect(Polymer.dom(viewRootQux).parentNode).toBe(null); expect(testDomApi.removeChild).toHaveBeenCalledWith(viewRootBaz); expect(testDomApi.removeChild).toHaveBeenCalledWith(viewRootQux); }); }); describe('listen', () => { const callbacks = { returnTrue: () => true, returnFalse: () => false }; let fakeClickEvent: CustomEvent; beforeEach(() => { spyOn(callbacks, 'returnTrue').and.callThrough(); spyOn(callbacks, 'returnFalse').and.callThrough(); fakeClickEvent = new CustomEvent('click', { bubbles: true, cancelable: true }); spyOn(fakeClickEvent, 'preventDefault').and.callThrough(); }); it('implements listen method, with default action', () => { renderer.listen(testElement, 'click', callbacks.returnTrue); testElement.dispatchEvent(fakeClickEvent); expect(callbacks.returnTrue).toHaveBeenCalledWith(fakeClickEvent); expect(fakeClickEvent.returnValue).not.toBe(false); expect(fakeClickEvent.preventDefault).not.toHaveBeenCalled(); }); it('implements listen method, without default action', () => { renderer.listen(testElement, 'click', callbacks.returnFalse); testElement.dispatchEvent(fakeClickEvent); expect(callbacks.returnFalse).toHaveBeenCalledWith(fakeClickEvent); expect(fakeClickEvent.returnValue).toBe(false); expect(fakeClickEvent.preventDefault).toHaveBeenCalled(); }); it('implements listenGlobal method, with default action', () => { renderer.listenGlobal('window', 'click', callbacks.returnTrue); testElement.dispatchEvent(fakeClickEvent); expect(callbacks.returnTrue).toHaveBeenCalledWith(fakeClickEvent); expect(fakeClickEvent.returnValue).not.toBe(false); expect(fakeClickEvent.preventDefault).not.toHaveBeenCalled(); }); it('implements listenGlobal method, without default action', () => { renderer.listenGlobal('window', 'click', callbacks.returnFalse); testElement.dispatchEvent(fakeClickEvent); expect(callbacks.returnFalse).toHaveBeenCalledWith(fakeClickEvent); expect(fakeClickEvent.returnValue).toBe(false); expect(fakeClickEvent.preventDefault).toHaveBeenCalled(); }); }); it('implements setElementProperty method', () => { renderer.setElementProperty(testElement, 'foo', 'bar'); expect(testElement['foo']).toBe('bar'); }); it('implements setElementAttribute method', () => { spyOn(testDomApi, 'setAttribute'); spyOn(testDomApi, 'removeAttribute'); renderer.setElementAttribute(testElement, 'foo', 'bar'); renderer.setElementAttribute(testElement, 'baz', ''); renderer.setElementAttribute(testElement, 'qux', null); expect(testDomApi.setAttribute).toHaveBeenCalledWith('foo', 'bar'); expect(testDomApi.setAttribute).toHaveBeenCalledWith('baz', ''); expect(testDomApi.removeAttribute).toHaveBeenCalledWith('qux'); }); it('implements setBindingDebugInfo method', () => { spyOn(testDomApi, 'setAttribute'); spyOn(testDomApi, 'removeAttribute'); renderer.setBindingDebugInfo(testElement, 'foo', 'bar'); renderer.setBindingDebugInfo(testElement, 'baz', ''); renderer.setBindingDebugInfo(testElement, 'qux', null); expect(testDomApi.setAttribute).toHaveBeenCalledWith('foo', 'bar'); expect(testDomApi.setAttribute).toHaveBeenCalledWith('baz', ''); expect(testDomApi.removeAttribute).toHaveBeenCalledWith('qux'); }); it('implements setElementClass method', () => { spyOn(testDomApi.classList, 'add'); spyOn(testDomApi.classList, 'remove'); renderer.setElementClass(testElement, 'foo', true); renderer.setElementClass(testElement, 'bar', false); expect(testDomApi.classList.add).toHaveBeenCalledWith('foo'); expect(testDomApi.classList.remove).toHaveBeenCalledWith('bar'); }); it('implements setElementStyle method', () => { const testHtmlElement = testElement as HTMLElement; spyOn(testHtmlElement.style, 'setProperty'); spyOn(testHtmlElement.style, 'removeProperty'); renderer.setElementStyle(testHtmlElement, '--foo', 'none'); renderer.setElementStyle(testHtmlElement, '--bar', ''); expect(testHtmlElement.style.setProperty).toHaveBeenCalledWith('--foo', 'none'); expect(testHtmlElement.style.removeProperty).toHaveBeenCalledWith('--bar'); }); it('implements invokeElementMethod method', () => { spyOn(testElement, (<any> 'click')); const callArgs = [1, 'foo']; renderer.invokeElementMethod(testElement, 'click', callArgs); const calls = testElement['click'].calls.all(); expect(calls.length).toBe(1); expect(calls[0].object).toBe(testElement); expect(calls[0].args).toEqual(callArgs); expect(calls[0].returnValue).toBeUndefined; }); it('implements setText method', () => { const textNode = renderer.createText(testElement, ''); renderer.setText(textNode, 'foo'); expect(textNode.nodeValue).toBe('foo'); }); it('implements animate method', () => { spyOn(rootRenderer.animationDriver, 'animate'); const animateArgs = [ testElement, {}, // startingStyles: any [], // keyframes: any[] 0, // duration: number 0, // delay: number '', // easing: string [] // previousPlayers: AnimationPlayer[] ]; renderer.animate.apply(renderer, animateArgs); expect( (<any>rootRenderer.animationDriver.animate).calls.mostRecent().args ).toEqual(animateArgs); }); describe('PolymerRootRenderer', () => { it('is injectable', () => { expect(rootRenderer instanceof PolymerRootRenderer).toBe(true); }); }); describe('setElementAttribute', () => { it('supports boolean attributes with no value', () => { expect((<any> testElement).booleanValue).toBe(true); }); }); describe('setElementProperty', () => { it('updates the value of angular component and polymer component', () => { (<any> testElement).value = 'Should change'; expect((<any> testElement).value).toBe('Should change'); }); }); it('applies component styles', () => { const fixture = TestBed.createComponent(StyleEncapsulationNoneComponent); const testElement = fixture.nativeElement.firstElementChild; expect(window.getComputedStyle(testElement).order).toBe('1'); }); }); describe('ShadowDomPolymerRenderer', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [PolymerModule], declarations: [ StyleEncapsulationNativeComponent ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }); TestBed.compileComponents(); })); let testElement: Element; beforeEach(() => { const fixture = TestBed.createComponent(StyleEncapsulationNativeComponent); testElement = fixture.nativeElement.shadowRoot.querySelector('p'); }); it('applies component styles', () => { expect(window.getComputedStyle(testElement).order).toBe('2'); }); it('encapsulates component styles', () => { const p = document.createElement('p'); document.body.appendChild(p); expect(window.getComputedStyle(p).order).not.toBe('2'); }); }); describe('EmulatedEncapsulationPolymerRenderer', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [PolymerModule], declarations: [ StyleEncapsulationEmulatedComponent ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }); TestBed.compileComponents(); })); let testElement: Element; beforeEach(() => { const fixture = TestBed.createComponent(StyleEncapsulationEmulatedComponent); testElement = fixture.nativeElement.firstElementChild; }); it('applies component styles', () => { expect(window.getComputedStyle(testElement).order).toBe('3'); }); it('encapsulates component styles', () => { const p = document.createElement('p'); document.body.appendChild(p); expect(window.getComputedStyle(p).order).not.toBe('3'); document.body.removeChild(p); }); });
the_stack
 module GUI { /////////////////////// Elements /////////////////////// export interface GUIElement { getElement(): JQuery; updateUI(); } export interface GUIElementWithContent extends GUIElement { getContent(): JQuery; } export function empty(element = 'div'): JQuery { return $('<' + element + '></' + element + '>'); } // Helper function to remove placeholders export function showPlaceholder(dropFields: JQuery, size: number) { dropFields.css('min-height', size); if (size == 19) dropFields.addClass('hoveredPlaceholder'); else dropFields.removeClass('hoveredPlaceholder'); } export function hideAllPlaceholders() { $('.dropListPlaceholder, .dropField').css('min-height', 0).css('height', '').css('width', '').removeClass('hoveredPlaceholder'); } export interface Replecable { replaceWith(element: E.Element); } export function focusOn(element: JQuery) { element.addClass('underEdition'); element.focus(); document.execCommand('selectAll', false, null); } export function makeEditable( element: JQuery, removable: E.Element, // element to be removed when delete button pressed keydown: (e: JQueryKeyEventObject) => void = () => { }, keyup: (e: JQueryKeyEventObject) => boolean = () => { return true }, edited: () => any = () => { }) { element.attr('contenteditable', 'true'); element.attr('spellcheck', 'false'); element.addClass('contenteditable'); element.click((e) => { if (!isEditable(element)) return true; var event = <any> e.originalEvent; if (event.editableHandled) return true; event.editableHandled = true; e.stopPropagation(); element.focus(); document.execCommand('selectAll', false, null); }); element.keydown((e) => { if (!isEditable(element)) return true; var event = <any> e.originalEvent; if (event.editableHandled) return true; event.editableHandled = true; keydown(e); if (e.which == 13 || e.which == 9 || e.which == 38 || e.which == 40) { e.preventDefault(); } }); element.keyup((e) => { if (!isEditable(element)) return true; var event = <any> e.originalEvent; if (event.editableHandled) return true; event.editableHandled = true; if (!element.hasClass('underEdition')) return; if (!keyup(e)) return; if (e.which == 13 || e.which == 9 || e.which == 38 || e.which == 40) { var inputs = $("#codeField [contenteditable='true']"); var index: number; if (e.which == 13 || e.which == 9 || e.which == 40) { index = inputs.index(element) + 1; if (index >= inputs.length) index = 0; } else { index = inputs.index(element) - 1; if (index < 0) index = inputs.length - 1; } var next = inputs.eq(index); element.blur(); focusOn(next); } }); element.focus(() => { element.addClass('underEdition'); }); element.blur(() => { element.removeClass('underEdition'); if (isEditable(element)) edited(); }); } export interface IDisplayable { getElement(): JQuery; } export class ElementHelper implements IDisplayable { private element: JQuery; private holder: JQuery; constructor(private helper: E.Element) { this.element = $('<div></div>').addClass('elementHelper'); this.holder = $('<div></div>').addClass('helperHolder'); this.element.append(this.holder); this.holder.append(helper.getElement()); } getElement(): JQuery { return this.element; } getHelper(): E.Element { return this.helper; } } export class StringHelper implements IDisplayable { private element: JQuery; private nameElement: JQuery; private descriptionElement: JQuery; constructor(public name: string, public description: string) { this.element = $('<div></div>').addClass('stringHelper'); this.nameElement = $('<div></div>').addClass('stringHelperName'); this.descriptionElement = $('<div></div>').addClass('stringHelperDescription'); this.element.append(this.nameElement); this.element.append(this.descriptionElement); this.nameElement.text(name); this.descriptionElement.text(description); } getElement(): JQuery { return this.element; } } class EditableHelpersList { private element: JQuery = $('<div></div>').addClass('elementHelpersList'); private currentHelpers: IDisplayable[] = []; private currnet: number = 0; constructor() { $('body').append(this.element); window.setInterval(() => { this.updateOffset(true); }, 1000); } getElement(): JQuery { return this.element; } clear() { this.element.empty(); } fill(currentHelpers: IDisplayable[]) { this.clear(); this.currentHelpers = currentHelpers; for (var i in currentHelpers) { var helper = currentHelpers[i]; this.element.append(helper.getElement()); } this.element.append($('<div></div>').addClass('hintSeparator')); var hint1 = $('<div></div>').addClass('hint').html('Press &#8593; or &#8595; to navigate'); var hint2 = $('<div></div>').addClass('hint').html('Press [Tab] or [Enter] to select'); this.element.append(hint1).append(hint2); this.currnet = -1; this.setCurrentIndex(0); } getCurrent(): IDisplayable { if (!this.currentHelpers.length) throw 'No helper to return'; return this.currentHelpers[this.currnet]; } incrementSelectedIndex() { if (!this.currentHelpers.length) return; this.setCurrentIndex(this.currnet + 1); } decrementSelectedIndex() { if (!this.currentHelpers.length) return; this.setCurrentIndex(this.currnet - 1); } private setCurrentIndex(index: number) { if (this.currnet >= 0) { this.currentHelpers[this.currnet].getElement().removeClass('selected'); } if (index < 0) index = this.currentHelpers.length - 1; if (index >= this.currentHelpers.length) index = 0; this.currnet = index; this.currentHelpers[this.currnet].getElement().addClass('selected'); } private hovered: JQuery = null; hide() { this.hovered = null; this.element.hide(); } focusOn(hovered: JQuery) { if (this.hovered != hovered) { this.hovered = hovered; this.updateOffset(); this.element.show(); } } updateOffset(animated = false) { if (this.hovered) { var offset = this.hovered.offset(); offset.top += this.hovered.outerHeight(); var thisOffset = this.element.offset(); if (offset.top != thisOffset.top || offset.left != thisOffset.left) this.element.stop().animate({ top: offset.top, left: offset.left }, animated ? 200 : 0); } } } var _editableHelpersList: EditableHelpersList; function getEditableHelpersList(): EditableHelpersList { if (!_editableHelpersList) _editableHelpersList = new EditableHelpersList(); return _editableHelpersList; } export interface IEditableHelpresSource { getHelpers(text: string): IDisplayable[]; helperSelected(helper: IDisplayable); } export function makeEditableWithHelpers( editable: JQuery, removable: E.Element, source: IEditableHelpresSource, keydown: (e: JQueryKeyEventObject) => void = () => { }, keyup: (e: JQueryKeyEventObject) => boolean = () => { return true }, edited: () => any = () => { }) { var textChanged = false; makeEditable( editable, removable, (e) => { keydown(e); }, (e) => { if (!keyup(e)) return false; var helpersList = getEditableHelpersList(); var text = editable.text(); var hasContent = text != ""; textChanged = textChanged || (e.which != 38 && e.which != 40 && e.which != 13 && e.which != 9); if (textChanged && hasContent) { helpersList.focusOn(editable); if (e.which == 38) { helpersList.decrementSelectedIndex(); return false; } if (e.which == 40) { helpersList.incrementSelectedIndex(); return false; } if (e.which == 13 || e.which == 9) { editable.blur(); return false; } helpersList.fill(source.getHelpers(text)); } else { textChanged = false; getEditableHelpersList().hide(); } return true; }, () => { edited(); var helpersList = getEditableHelpersList(); var index = $("#codeField [contenteditable='true']").index(editable); var hasContent = editable.text() != ""; helpersList.hide(); if (textChanged && hasContent) { source.helperSelected(helpersList.getCurrent()); var input = editable.find("[contenteditable='true']").first(); if (input.length) focusOn(input); else if (editable.attr('contenteditable')) { focusOn($("#codeField [contenteditable='true']").eq(index + 1)); } else { focusOn($("#codeField [contenteditable='true']").eq(index)); } } textChanged = false; helpersList.clear(); } ); } export function setEditable(element: JQuery, editable: boolean = true) { if (editable) element.attr('contenteditable', 'true'); else { element.removeAttr('contenteditable'); element.removeClass('underEdition'); } } export function isEditable(element: JQuery) { return element.attr('contenteditable') == 'true'; } // Adds events like dropping to the element (should be called only if element is in "code" filed) export function addDynamicEvants(elem: JQuery) { } // Adds static events to the object that are required for "code" and "helpers" sections as well export function addStaticEvents(elem: JQuery) { elem.find('.codeElement').addBack('.codeElement').draggable(<any>{ stack: '.codeElement', helper: function() { return $(this).clone().css("pointer-events", "none").appendTo("body").show(); }, opacity: 0.5, start: function (event, ui) { $(this).css('pointer-events', 'none'); $(this).css('opacity', '0.5'); //$('body').css('cursor', 'url(images/elementPointer.png), auto'); }, drag: function (event, ui) { $(this).css('bottom', ''); $(this).css('right', ''); $(this).css('width', ''); $(this).css('height', ''); $(this).parent().css('width', $(this).css('width')); $(this).parent().css('height', $(this).outerHeight()); }, stop: function (event, ui) { $(this).css({ 'pointer-events': 'auto', left: 0, top: 0 }); $(this).css('opacity', '1'); $(this).css('bottom', ''); $(this).css('right', ''); $(this).css('width', ''); $(this).css('height', ''); $(this).parent().css('width', ''); $(this).parent().css('height', ''); }, scroll: false, }); // .on('click', function () { // var element: JQuery = this; // element.focus(); //}); } export function getRawData(elem: JQuery): string { return elem.text(); } /////////////////////// Element /////////////////////// export function extractElement(element: JQuery): E.Element { return element.data(Commons.data_ElementObject); } /////////////////////// Memory /////////////////////// export interface MomoryElement { addValue(value: JQuery); element: JQuery; } export class StackElement implements MomoryElement { element: JQuery; elementName: JQuery; elementEqual: JQuery; elementValue: JQuery; constructor(private name: string) { this.element = $('<div></div>'); this.element.addClass('onStackElement'); this.elementName = $('<div></div>'); this.elementName.addClass('onStackElementName'); this.elementEqual = $('<div>=</div>'); this.elementValue = $('<div></div>'); this.elementValue.addClass('onStackElementValue'); this.elementName.append(name); this.element.append(this.elementName); this.element.append(this.elementEqual); this.element.append(this.elementValue); } addValue(value: JQuery) { this.elementValue.empty(); this.elementValue.append(value); } } export class HeapElement implements MomoryElement { element: JQuery; elementName: JQuery; elementEqual: JQuery; elementValue: JQuery; constructor() { this.element = $('<div></div>'); this.element.addClass('onHeapElement'); this.elementValue = $('<div></div>'); this.elementValue.addClass('onHeapElementValue'); this.element.append(this.elementValue); } addValue(value: JQuery) { this.elementValue.empty(); this.elementValue.append(value); } } export function getObjectElementForSimpleType(value: any): JQuery { var element = $('<div></div>'); element.addClass('objectElement'); element.append(value); return element; } export function getObjectElementForFunction(): JQuery { var element = $('<div></div>'); element.addClass('objectElement'); element.text('<fun>'); return element; } export function getObjectElementForType(): JQuery { var element = $('<div></div>'); element.addClass('objectElement'); element.text('<type>'); return element; } export function getObjectElementForReference(reference: JQuery): JQuery { var element = $('<div></div>'); element.addClass('objectElement'); var canvas = $('<canvas></canvas>'); canvas.addClass('connection'); element.append(canvas); element.append('o'); //element.onPo var context = (<any> canvas.get(0)).getContext('2d'); context.canvas.height = window.outerHeight; context.canvas.width = window.outerWidth; context.beginPath(); context.moveTo(element.offset().left, element.offset().top); context.lineTo(reference.offset().left, reference.offset().top); context.lineCap = 'round'; context.strokeStyle = '#ff0000'; context.lineWidth = 15; context.stroke(); return element; } /////////////////////// References /////////////////////////// export function linkObjects(canvas: JQuery, first: JQuery, second: JQuery) { } /////////////////////// User interface /////////////////////// export class Scrollable implements GUIElementWithContent { private internalHolder: JQuery; private contentWrapper: JQuery; private scrollBar: JQuery; private scrollButton: JQuery; onScroll: ()=>void; private topOffset = 0; constructor(private externalHolder: JQuery) { var children = externalHolder.children().detach(); externalHolder.addClass('scrollExternalHolder'); this.internalHolder = $('<div></div>').addClass('scrollInternalHolder').appendTo(this.externalHolder); this.contentWrapper = $('<div></div>').addClass('scrollContentWrapper').append(children).appendTo(this.internalHolder); this.scrollBar = $('<div></div>').addClass('scrollBar').appendTo(this.externalHolder); this.scrollButton = $('<div></div>').addClass('scrollBarButton').appendTo(this.scrollBar); this.scrollButton.draggable(<any>{ stop: (event, ui) => { this.updateUI(); }, drag: (event, ui) => { var holderHeight = this.internalHolder.innerHeight(); var contentHeight = this.contentWrapper.outerHeight(); var scrollbarHeight = this.scrollBar.innerHeight(); var buttonHeight = this.scrollButton.outerHeight(); var buttonTop = parseFloat(this.scrollButton.css('top')); this.topOffset = contentHeight > holderHeight ? (contentHeight - holderHeight) * buttonTop / (scrollbarHeight - buttonHeight) : 0; ui.position = { 'top': Math.max(0, Math.min(ui.position.top, scrollbarHeight - buttonHeight)) }; this.updateUI(); }, scroll: false, }); externalHolder.bind('mousewheel DOMMouseScroll',(e) => { var offset = parseInt(this.contentWrapper.css('margin-top')); var orginalEvent = <any> e.originalEvent; var delta = parseInt(orginalEvent.wheelDelta || -orginalEvent.detail); this.topOffset += delta > 0 ? -60 : 60; this.updateUI(); }); //this.contentWrapper.on('DOMSubtreeModified', () => { // this.updateUI(); //}); this.updateUI(); } updateUI() { var holderHeight = this.internalHolder.innerHeight(); var contentHeight = this.contentWrapper.outerHeight(); this.topOffset = Math.min(this.topOffset, contentHeight - holderHeight); this.topOffset = Math.max(this.topOffset, 0); this.contentWrapper.css('top', -this.topOffset); var scrollbarHeight = this.scrollBar.innerHeight(); var buttonHeight = contentHeight > holderHeight ? scrollbarHeight * holderHeight / contentHeight : scrollbarHeight; var buttonOffset = contentHeight > holderHeight ? (scrollbarHeight - buttonHeight) * this.topOffset / (contentHeight - holderHeight) : 0; this.scrollButton.outerHeight(buttonHeight); this.scrollButton.css('top', buttonOffset); if (this.onScroll) this.onScroll(); } scrollDown() { this.topOffset = this.contentWrapper.outerHeight(); this.updateUI(); } getContent(): JQuery { return this.contentWrapper; } getElement(): JQuery { return this.externalHolder; } } class PickableButton { private selected = true; constructor( public button: JQuery, public indicator: JQuery, public relatedElement: GUIElement) { } } export class Pickable implements GUIElement { private buttonsPerRow : number = 4; private options: PickableButton[] = []; private buttonsHolders: JQuery[] = []; private selectionIndicator: JQuery; private pickerHolder: JQuery; private pickerContent: JQuery; private selectedIndex = -1; constructor(private externalHolder: JQuery) { externalHolder.empty(); externalHolder.addClass('pickerExternalHolder'); this.selectionIndicator = $('<div></div>'); this.selectionIndicator.addClass('pickerIndicator'); this.pickerHolder = $('<div></div>').addClass('pickerHeader'); this.externalHolder.append(this.pickerHolder); this.pickerContent = $('<div></div>').addClass('pickerContent'); this.externalHolder.append(this.pickerContent); this.pickerHolder.append(this.selectionIndicator); } getElement(): JQuery { return this.externalHolder; } updateUI() { if (this.selectedIndex != -1) this.options[this.selectedIndex].relatedElement.updateUI(); } addPickable(name: string, element: GUIElement) { var buttonsHolder: JQuery; if (this.options.length % this.buttonsPerRow == 0) { buttonsHolder = $('<div></div>'); buttonsHolder.addClass('pickerHolder'); this.buttonsHolders.push(buttonsHolder); this.selectionIndicator.before(buttonsHolder); } else { buttonsHolder = this.buttonsHolders[this.buttonsHolders.length - 1]; } this.pickerContent.append(element.getElement()); var button = $('<div></div>'); button.addClass('pickerButton'); var buttonText = $('<div></div>'); buttonText.addClass('pickerButtonText'); buttonText.text(name); button.append(buttonText); var indicator = $('<div></div>'); indicator.addClass('pickerButtonIndicator'); button.append(indicator); this.options.push(new PickableButton(button, indicator, element)); var index = this.options.length - 1; button.click(() => { this.select(index); }); buttonsHolder.append(button); } select(index: number) { this.selectedIndex = index; var row = Math.floor(index / this.buttonsPerRow); this.buttonsHolders[row].insertBefore(this.selectionIndicator); for (var i = 0; i < this.options.length; i++) { var pickable = this.options[i]; if (i != index) { pickable.relatedElement.getElement().detach(); pickable.button.removeClass('pickerButtonSelected'); pickable.indicator.hide(); } else { this.pickerContent.append(pickable.relatedElement.getElement()); pickable.button.addClass('pickerButtonSelected'); pickable.indicator.show(); pickable.relatedElement.updateUI(); } } this.updateUI(); } } export function makeResizable(toResize: JQuery, horizontal: boolean, shouldUpdate: GUIElement[] = []) { var buttonContainer = $('<div></div>').addClass('resizer').insertAfter(toResize); var button = $('<div><div></div></div>').addClass('resizable').appendTo(buttonContainer); var resizedPrev = buttonContainer.prev(); var resizedNext = buttonContainer.next(); var resizePrev = resizedPrev.css('flex') != '1'; var resizeNext = resizedNext.css('flex') != '1'; if (horizontal) { var left = 'left'; var width = 'width'; button.addClass('resizableHor'); } else { var left = 'top'; var width = 'height'; button.addClass('resizableVer'); } button.draggable(<any>{ stop: (event, ui) => { var offset = parseInt(button.css(left)); button.css(left, 0); var prevWidth = (resizedPrev[width]() + offset) / toResize.parent()[width]() * 100 + '%'; var nextWidth = (resizedNext[width]() - offset) / toResize.parent()[width]() * 100 + '%'; if (offset >= 0) { if (resizedNext) resizedNext[width](nextWidth); if (resizedPrev) resizedPrev[width](prevWidth); } else { if (resizedPrev) resizedPrev[width](prevWidth); if (resizedNext) resizedNext[width](nextWidth); } //button.css('left', ui.originalPosition.left); shouldUpdate.forEach((e) => { e.updateUI(); }); }, scroll: false, }) } class Console { private _console: Scrollable; private _button: JQuery = $('#consoleSubimt'); private _input: JQuery = $('#consoleInput'); private _holder: JQuery = $('#consoleInputHolder'); constructor() { this._console = new Scrollable($('#consoleLog')); this._button.click((e) => { var message = this._input.text(); this._input.empty(); this.input(message); BufferManager.getBuffer().addConsoleInput(message); return false; }); this._input.keydown((e) => { if (e.which == 13) { this._button.click(); e.preventDefault(); } }) } private addMessage(message: string, delimiterChar: string): JQuery { var holder = $('<div></div>').addClass('consoleMessage'); var now = new Date; var date = $('<div></div>') .addClass('consoleMessageDate') .text(now.toTimeString().substr(0, 8)); holder.append(date); var delimiter = $('<div></div>') .addClass('consoleMessageDelimiter') .text(delimiterChar); holder.append(delimiter); var text = $('<div></div>') .addClass('consoleMessageText') .text(message); holder.append(text); this._console.getContent().append(holder); this._console.scrollDown(); return holder; } print(message: string): JQuery { return this.addMessage(message, '\|').animate({ backgroundColor: '#C0C0C0' }, 100).animate({ backgroundColor: 'transparent' }, 1000); } input(message: string): JQuery { return this.addMessage(message, '>'); } printError(message: string): JQuery { return this.print(message).css('color', 'red'); } printSuccess(message: string): JQuery { return this.print(message).css('color', 'green'); } printInternalMessage(message: string): JQuery { return this.print(message).css('color', 'gray'); } clear() { this._console.getContent().empty(); } requestConsoleInput() { if (this._holder.queue().length == 0) this._holder.animate({ backgroundColor: '#FF4500' }, 100).animate({ backgroundColor: 'transparent' }, 2000).delay(1000); } updateUI() { this._console.updateUI(); } } var progremConsole = null; export function getConsole(): Console { if (progremConsole == null) progremConsole = new Console(); return progremConsole; } export function setAsTrash(element: JQuery) { element.droppable({ accept: '#codeField .codeElement', drop: function (event, ui) { var drag = extractElement(ui.draggable); drag.detachElement(); hideAllPlaceholders(); }, greedy: true, tolerance: 'pointer', }); } export class Help { private element = $('<div></div>').addClass('help'); private descriptions: { element: JQuery; content: JQuery }[] = []; private displayed = false; constructor(button: JQuery) { button.click(() => this.showHelp()); this.element.click(() => this.hideHelp()); } showHelp() { this.displayed = true; this.element.empty(); for (var i = 0; i < this.descriptions.length; i++) { var description = this.descriptions[i]; var element = $('<div></div>').addClass('helpField'); element.offset(description.element.offset()); element.width(description.element.outerWidth()); element.height(description.element.outerHeight()); element.append(description.content); this.element.append(element); } $('body').append(this.element); } hideHelp() { this.displayed = false; this.element.detach(); this.element.empty(); } addDescription(relatedElement: JQuery, content: JQuery) { this.descriptions.push({ element: relatedElement, content: content }); } } class Indicator implements GUIElement { private element: JQuery = GUI.empty(); private indicator: JQuery = $('<div></div>').addClass('indicator'); constructor(_class: string) { this.indicator.addClass(_class); this.element.append(this.indicator); window.setInterval(() => { this.updateUI(); }, 1000); } private indicatedElement: L.LogicElementObserver; indicate(element: L.LogicElementObserver) { this.indicatedElement = element; this.updateUI(); } hide() { this.indicatedElement = null; this.updateUI(); } getElement(): JQuery { return this.element; } updateUI() { if (this.indicatedElement) { var toIndicate = this.indicatedElement.getElement(); this.indicator.css('opacity', 0.4); this.indicator.offset(toIndicate.offset()); this.indicator.outerWidth(toIndicate.outerWidth()); this.indicator.outerHeight(toIndicate.outerHeight()); this.indicator.css('border-radius', toIndicate.css('borderTopLeftRadius')); } else { this.indicator.css('opacity', 0.0); } } } var executionIndicator: Indicator; export function getExecutionIndicator(): Indicator { if (executionIndicator == null) executionIndicator = new Indicator('executionIndicator'); return executionIndicator; } export class Slider { holder = $('<div></div>').addClass('sliderHolder'); button = $('<div></div>').addClass('sliderButton'); constructor( private min: number, private max: number, private value: number, private onValueChenge: (newValue: number) => any) { this.holder.append(this.button); this.button.draggable(<any>{ stop: (event, ui) => { var left = this.button.position().left; var width = this.holder.width(); this.value = min + (max - min) * left / width; onValueChenge(this.value); }, scroll: false, containment: 'parent' }); this.button.css('left', ((value - min) * 100 / (max - min)) + '%'); onValueChenge(value); } getElement(): JQuery { return this.holder; } } export class CheckBox { button = $('<div></div>').addClass('checkBoxButton'); tick = $('<p class="glyphicon glyphicon-ok"></p>').addClass('checkBoxButtonTick'); private setValue(value: boolean) { this.value = value; if (this.value) this.tick.show(); else this.tick.hide(); this.onValueChenge(value); } constructor( private value: boolean, private onValueChenge: (newValue: boolean) => any) { this.button.append(this.tick); this.button.click(() => { this.setValue(!this.value); }); this.setValue(value); } getElement(): JQuery { return this.button; } } class ElementInfo { private element: JQuery; constructor() { this.element = $('<div></div>'); this.element.addClass('elementInfo'); $('body').append(this.element); window.setInterval(() => { this.updateOffser(true); }, 1000); } private hovered: L.LogicElementObserver = null; hideInfo() { this.hovered = null; this.element.hide(); } infoFor(hovered: L.LogicElementObserver) { if (this.hovered != hovered) { this.hovered = hovered; this.element.empty(); var text = hovered.getDescription(); var errors = hovered.getErrors(); if (text == '' && errors.length == 0) { this.hideInfo(); return; } var description = $('<div></div>').addClass('standardInfo'); description.text(text) this.element.append(description); for (var i = 0; i < errors.length; i++) { var error = $('<div></div>').addClass('errorInfo'); error.text(errors[i]); this.element.append(error); } this.updateOffser(); this.element.show(); } } updateOffser(animated = false) { if (this.hovered) { var offset = this.hovered.getElement().offset(); offset.top += this.hovered.getElement().outerHeight(); var thisOffset = this.element.offset(); if (offset.top != thisOffset.top || offset.left != thisOffset.left) this.element.stop().animate({ top: offset.top, left: offset.left }, animated ? 200 : 0); } } } var elementInfo: ElementInfo = null; export function getElementInfo(): ElementInfo { if (!elementInfo) elementInfo = new ElementInfo(); return elementInfo; } export function disableMenuButton(button: JQuery) { button.addClass('menuButtonDisabled'); } export function enableMenuButton(button: JQuery) { button.removeClass('menuButtonDisabled'); } //export function getKetOfColor(color: string, borderColor: string) : JQuery { // var key = $('<div></div>').addClass('key'); // var left = $('<div></div>').addClass('leftKey'); // var center = $('<canvas></canvas>').addClass('centerKey'); // var right = $('<div></div>').addClass('rightKey'); // key.append(left).append(center).append(right); // var context = (<any> center.get(0)).getContext("2d"); // context.canvas.height = 10; // context.canvas.width = 15; // context.beginPath(); // context.strokeStyle = borderColor; // context.fillStyle = color; // context.lineWidth = 2; // context.moveTo(0, 10); // context.lineTo(5, 5); // context.lineTo(10, 5); // context.lineTo(15, 10); // context.stroke(); // context.lineTo(15, 0); // context.lineTo(0, 0); // context.fill(); // return key; //} export function svgElement(tagName): JQuery { return $(document.createElementNS("http://www.w3.org/2000/svg", tagName)); } }
the_stack
import { Component, Element, Prop, h, Watch, EventEmitter, Event } from '@stencil/core'; import { select, event } from 'd3-selection'; import { scalePow, scaleOrdinal } from 'd3-scale'; import { max, min } from 'd3-array'; import { forceCollide, forceSimulation, forceManyBody, forceX, forceY } from 'd3-force'; // import { interpolate } from 'd3-interpolate'; import { drag } from 'd3-drag'; import { v4 as uuid } from 'uuid'; import 'd3-transition'; import { IBoxModelType } from '@visa/charts-types'; import Utils from '@visa/visa-charts-utils'; const { formatStats, getLicenses, checkInteraction, checkClicked, checkHovered, getColors, outlineColor, visaColors, drawTooltip, initTooltipStyle } = Utils; @Component({ tag: 'clustered-force-layout' }) export class ClusteredForceLayout { @Event() clickFunc: EventEmitter; @Event() hoverFunc: EventEmitter; @Event() mouseOutFunc: EventEmitter; @Prop() width: any = 400; @Prop() height: any = 400; // @Prop() nodePadding: number = 1.5; // separation between same-color nodes // @Prop() clusterPadding: number = 6; // separation between different-color nodes @Prop({ mutable: true }) maxRadius: number = 0; // maximum size of circles to allow @Prop() data: any; @Prop() uniqueID; @Prop() colors: any; @Prop({ mutable: true }) colorPalette = 'sequential_suppPurple'; // accessors @Prop() clusterAccessor: string; @Prop() nodeAccessor: string; @Prop() nodeSizeAccessor: string; @Prop() mainTitle: string; @Prop() subTitle: string; @Prop() drag: boolean = true; // data label props object @Prop({ mutable: true }) showTooltip = true; @Prop({ mutable: true }) tooltipLabel; @Prop({ mutable: true }) cursor = 'cursor'; @Prop() dataLabel: any = { visible: true, placement: 'center', content: 'nodeSizeAccessor', format: '0,0.00' }; @Prop() margin: IBoxModelType = { top: this.height * 0.02, bottom: this.height * 0.02, right: this.width * 0.02, left: this.width * 0.02 }; @Prop({ mutable: true }) padding: IBoxModelType = { top: this.height * 0.02, bottom: this.height * 0.02, right: this.width * 0.02, left: this.width * 0.02 }; // Interactivity @Prop({ mutable: true }) hoverStyle: any = { color: 'comp_blue', strokeWidth: 2 }; @Prop({ mutable: true }) clickStyle: any = { color: 'supp_purple', strokeWidth: 2 }; @Prop({ mutable: true }) hoverOpacity = 1; @Prop({ mutable: true }) hoverHighlight: any; @Prop({ mutable: true }) clickHighlight: any = []; @Prop({ mutable: true }) interactionKeys: string[]; @Element() clusterChartEl: HTMLElement; svg: any; rootG: any; tooltipG: any; innerHeight: number; innerWidth: number; innerPaddedHeight: number; innerPaddedWidth: number; innerXAxis: any; innerYAxis: any; circle: any; prepareLoading: any = true; colorArr: any; chartID: string; @Watch('uniqueID') idWatcher(newID, _oldID) { this.chartID = newID; this.clusterChartEl.id = this.chartID; } @Watch('data') dataWatcher(_newData, _oldData) { this.prepareLoading = true; } componentWillLoad() { this.chartID = this.uniqueID || 'cluster-force-layout-chart-' + uuid(); this.clusterChartEl.id = this.chartID; // default interaction keys if not provided this.interactionKeys ? '' : (this.interactionKeys = [this.clusterAccessor || this.nodeAccessor]); // before we render/load we need to set our height and width based on props this.innerHeight = this.height - this.margin.top - this.margin.bottom; this.innerWidth = this.width - this.margin.left - this.margin.right; this.innerPaddedHeight = this.innerHeight - this.padding.top - this.padding.bottom; this.innerPaddedWidth = this.innerWidth - this.padding.left - this.padding.right; // default tooltip label vs updating tooltip util for default for this chart if (!this.tooltipLabel) { if (this.clusterAccessor) { this.tooltipLabel = { labelAccessor: [this.clusterAccessor, this.nodeAccessor, this.nodeSizeAccessor], labelTitle: ['', '', ''], format: ['', '', '0,0[.][0][a]'] }; } else { this.tooltipLabel = { labelAccessor: [this.nodeAccessor, this.nodeSizeAccessor], labelTitle: ['', ''], format: ['', '0,0[.][0][a]'] }; } } } componentDidLoad() { this.drawChart(); this.setTooltipInitialStyle(); } componentDidUpdate() { this.drawCircle(this.circle); if (this.data.length > 0 && this.prepareLoading) { this.prepareLoading = false; this.drawChart(); } } reSetRoot() { if (this.svg) { this.svg.remove(); } // assign the svg to this.svg use barChartEL to make it specific to this instance this.svg = select(this.clusterChartEl) .select('#visa-viz-d3-force-cluster-container') .append('svg') .attr('id', 'visa-viz-d3-svg-container') .attr('width', this.width) .attr('height', this.height) .attr('viewBox', '0 0 ' + this.width + ' ' + this.height); // .style("border", "2px solid black") this.svg .append('g') .attr('id', 'visa-viz-margin-container-g') .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`); this.rootG = select(this.clusterChartEl) .select('#visa-viz-margin-container-g') .append('g') .attr('id', 'visa-viz-padding-container-g') .attr('transform', `translate(${this.padding.left}, ${this.padding.top})`); this.tooltipG = select(this.clusterChartEl).select('.clustered-force-layout-tooltip'); } drawChart() { this.reSetRoot(); // step 1 is to determine the number of clusters // 1. find max const maxAmount = max(this.data, d => d[this.nodeSizeAccessor]); const minAmount = min(this.data, d => d[this.nodeSizeAccessor]); // 2. Optimize the estimation of max Radius: // Compare the max & 2nd max value -> get a ratio "secondFirstRatio" m2 = maxAmount / secondMax // Get max, max2, max3.... until sqrt(n) max // e.g. if there are 100 circles, get until 10th max // Get all the ratio comparing to the max -> m2, m3= (max3 / maxAmount), m4,... m10 // (1 + m2 + m3 + ... + m10) * r * 2 = min(w, h) // get the maximum possible radius r = min(w,h) / (2 * (1 + m2 + m3 + ....) const valueArr = []; const ratioArr = []; const ratioToMax = [1]; let ratioToMaxSum = 1; this.data.map(d => { valueArr.push(d[this.nodeSizeAccessor]); ratioArr.push(d[this.nodeSizeAccessor] / maxAmount); }); this.colorArr = this.clusterAccessor ? getColors( this.colors || this.colorPalette, scaleOrdinal() .domain(this.data.map(d => d[this.clusterAccessor])) .domain() ) : getColors(this.colors || this.colorPalette, [minAmount, maxAmount]); for (var i = 0; i < Math.sqrt(this.data.length); i++) { var currentMax = Math.max.apply(null, valueArr); // get the max of the array valueArr.splice(valueArr.indexOf(currentMax), 1); // remove max from the array var secondMax = Math.max.apply(null, valueArr); // get the 2nd max ratioToMax.push(secondMax / maxAmount); ratioToMaxSum += secondMax / maxAmount; } // const maxAllowableRadius = Math.min(this.innerPaddedWidth,this.innerPaddedHeight) / (Math.sqrt(this.data.length) * 2) const maxAllowableRadius = Math.min(this.innerPaddedWidth, this.innerPaddedHeight) / (ratioToMaxSum * 2); // Reset max Radius to the min of allowable or prop provided this.maxRadius = this.maxRadius !== 0 ? Math.min(this.maxRadius, maxAllowableRadius) : maxAllowableRadius; const radiusScale = scalePow() .exponent(0.5) .range([0, this.maxRadius]) .domain([0, maxAmount]); const clusters = new Array(); const myNodes = this.data.map(d => { return { id: d[this.nodeAccessor], cluster: d[this.clusterAccessor], radius: radiusScale(+d[this.nodeSizeAccessor]), value: d[this.nodeSizeAccessor], x: Math.random() * 900, y: Math.random() * 800, ...d }; }); myNodes.map(d => { if ( !clusters[d[this.clusterAccessor]] || radiusScale(+d[this.nodeSizeAccessor]) > clusters[d[this.clusterAccessor]].radius ) { clusters[d[this.clusterAccessor]] = d; } }); const _forceCluster = alpha => { // cluster spacing depends on k below, lower the value, lesser the gap for (let i = 0, n = myNodes.length, node, cluster, k = alpha * 0.43; i < n; ++i) { node = myNodes[i]; cluster = clusters[node.cluster]; node.vx -= (node.x - cluster.x) * k; node.vy -= (node.y - cluster.y) * k; } }; // const _tick = () => { // this.circle.attr('cx', d => d.x).attr('cy', d => d.y); // }; // circle drag start const _dragstarted = () => { if (!event.active) { forceLayout.alphaTarget(0.3).restart(); } select(this) .raise() .classed('active', true); forceLayout.force('collide').strength(1); }; // circle drag in progress const _dragged = d => { select(this) .attr('cx', (d.x = event.x)) .attr('cy', (d.y = event.y)); forceLayout.force('collide').strength(1); }; // circle drag stop const _dragended = () => { if (!event.active) { forceLayout.alphaTarget(0); } select(this).classed('active', false); forceLayout.force('collide').strength(); }; const forceLayout = forceSimulation() .nodes(myNodes) // .force("center", forceCenter([this.innerPaddedWidth / 2, this.innerPaddedHeight / 2])) .velocityDecay(0.9) .force('gravity', forceManyBody(30)) .force( 'x', forceX() .strength(0.9) .x(this.innerPaddedWidth / 2) ) .force( 'y', forceY() .strength(0.9) .y(this.innerPaddedHeight / 2) ) .force( 'collide', forceCollide() .radius(d => d.radius + 1) .iterations(2) ) .force('cluster', _forceCluster) .stop(); // .on('tick', _tick); setTimeout(() => { // See https://github.com/d3/d3-force/blob/master/README.md#simulation_tick // for (var i = 0, n = Math.ceil(Math.log(forceLayout.alphaMin()) / Math.log(1 - forceLayout.alphaDecay())); i < n; ++i) { for (var i = 0, n = 500; i < n; ++i) { forceLayout.tick(); } // create circles this.circle = this.rootG .selectAll('circle') .data(myNodes) .enter() .append('circle') .attr('class', d => checkClicked(d, this.clickHighlight, this.interactionKeys) ? 'circle highlight' : 'circle' ) .attr('cursor', this.cursor) .attr('r', d => d.radius) .attr('cx', d => d.x) .attr('cy', d => d.y) .attr('fill', d => this.clickHighlight.length > 0 && checkClicked(d, this.clickHighlight, this.interactionKeys) && this.clickStyle.color ? visaColors[this.clickStyle.color] || this.clickStyle.color : checkHovered(d, this.hoverHighlight, this.interactionKeys) && this.hoverStyle.color ? visaColors[this.hoverStyle.color] || this.hoverStyle.color : this.clusterAccessor ? this.colorArr(d[this.clusterAccessor]) : this.colorArr(d[this.nodeSizeAccessor]) ) .attr('stroke', d => this.clickHighlight.length > 0 && checkClicked(d, this.clickHighlight, this.interactionKeys) && this.clickStyle.color ? checkClicked(d, this.clickHighlight, this.interactionKeys) ? visaColors[this.clickStyle.stroke] || this.clickStyle.stroke || outlineColor(visaColors[this.clickStyle.color] || this.clickStyle.color) : checkHovered(d, this.hoverHighlight, this.interactionKeys) ? visaColors[this.hoverStyle.stroke] || this.hoverStyle.stroke || outlineColor(visaColors[this.hoverStyle.color] || this.hoverStyle.color) : '' : this.clusterAccessor ? outlineColor(this.colorArr(d[this.clusterAccessor])) : outlineColor(this.colorArr(d[this.nodeSizeAccessor])) ) .attr('stroke-width', d => this.clickHighlight.length > 0 && checkClicked(d, this.clickHighlight, this.interactionKeys) && this.clickStyle.color ? checkClicked(d, this.clickHighlight, this.interactionKeys) ? this.clickStyle.strokeWidth || 2 : checkHovered(d, this.hoverHighlight, this.interactionKeys) ? this.hoverStyle.strokeWidth || 2 : 1 : 1 ) .attr('stroke-dasharray', d => (checkClicked(d, this.clickHighlight, this.interactionKeys) ? '4 3' : '')) .attr('opacity', d => checkInteraction(d, 1, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.interactionKeys) ) .on('click', d => this.onClickHandler(d)) .on('mouseover', d => this.onHoverHandler(d)) .on('mouseout', () => this.onMouseOutHandler()); // enable circle drag if (this.drag) { this.circle.call( drag() .on('start', _dragstarted) .on('drag', _dragged) .on('end', _dragended) ); } // reduce jitter by delaying force // this.circle // .transition() // .duration(750) // .delay(d => d.index * 5) // .attrTween('r', d => { // const i = interpolate(0, d.radius); // return t => (d.radius = i(t)); // }); }); } drawCircle(circle) { circle .attr('class', d => (checkClicked(d, this.clickHighlight, this.interactionKeys) ? 'circle highlight' : 'circle')) .attr('fill', d => this.clickHighlight.length > 0 && checkClicked(d, this.clickHighlight, this.interactionKeys) && this.clickStyle.color ? visaColors[this.clickStyle.color] || this.clickStyle.color : checkHovered(d, this.hoverHighlight, this.interactionKeys) && this.hoverStyle.color ? visaColors[this.hoverStyle.color] || this.hoverStyle.color : this.clusterAccessor ? this.colorArr(d[this.clusterAccessor]) : this.colorArr(d[this.nodeSizeAccessor]) ) .attr('stroke', d => this.clickHighlight.length > 0 && checkClicked(d, this.clickHighlight, this.interactionKeys) && this.clickStyle.color ? checkClicked(d, this.clickHighlight, this.interactionKeys) ? visaColors[this.clickStyle.stroke] || this.clickStyle.stroke || outlineColor(visaColors[this.clickStyle.color] || this.clickStyle.color) : checkHovered(d, this.hoverHighlight, this.interactionKeys) ? visaColors[this.hoverStyle.stroke] || this.hoverStyle.stroke || outlineColor(visaColors[this.hoverStyle.color] || this.hoverStyle.color) : '' : this.clusterAccessor ? outlineColor(this.colorArr(d[this.clusterAccessor])) : outlineColor(this.colorArr(d[this.nodeSizeAccessor])) ) .attr('stroke-width', d => this.clickHighlight.length > 0 && checkClicked(d, this.clickHighlight, this.interactionKeys) && this.clickStyle.color ? checkClicked(d, this.clickHighlight, this.interactionKeys) ? this.clickStyle.strokeWidth || 2 : checkHovered(d, this.hoverHighlight, this.interactionKeys) ? this.hoverStyle.strokeWidth || 2 : 1 : 1 ) .attr('stroke-dasharray', d => (checkClicked(d, this.clickHighlight, this.interactionKeys) ? '4 3' : '')) .attr('opacity', d => checkInteraction(d, 1, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.interactionKeys) ); } onClickHandler(d) { this.clickFunc.emit(d); } onHoverHandler(d) { this.hoverFunc.emit(d); if (this.showTooltip) { this.eventsTooltip({ data: d, evt: event, isToShow: true }); } } onMouseOutHandler() { this.mouseOutFunc.emit(); if (this.showTooltip) { this.eventsTooltip({ isToShow: false }); } } // based on whether value accessor and format was provided return the right thing formatDataLabel(d) { if (this.dataLabel.content === 'nodeAccessor') { return d[this.nodeAccessor]; } else { if (this.dataLabel.format) { return formatStats(d[this.nodeSizeAccessor], this.dataLabel.format); } else { return d[this.nodeSizeAccessor]; } } } // set initial style (instead of copying css class across the lib) setTooltipInitialStyle() { initTooltipStyle(this.tooltipG); } // tooltip eventsTooltip({ data, evt, isToShow }: { data?: any; evt?: any; isToShow: boolean }) { drawTooltip({ root: this.tooltipG, data, event: evt, isToShow, tooltipLabel: this.tooltipLabel, dataLabel: this.dataLabel, ordinalAccessor: this.nodeAccessor, valueAccessor: this.nodeSizeAccessor, groupAccessor: this.clusterAccessor, chartType: 'clustered-force-layout' }); } render() { return ( <div class="o-layout"> <div class="o-layout--chart"> <h2>{this.mainTitle}</h2> <p class="visa-ui-text--instructions">{this.subTitle}</p> <div class="clustered-force-layout-tooltip vcl-tooltip" style={{ display: this.showTooltip ? 'block' : 'none' }} /> <div id="visa-viz-d3-force-cluster-container" /> </div> </div> ); } } // incorporate OSS licenses into build window['VisaChartsLibOSSLicenses'] = getLicenses(); // tslint:disable-line no-string-literal
the_stack
import unknownTest, { TestInterface } from 'ava'; import { createClient } from './lib/SettingsClient'; import { Gateway, KlasaClient, Provider, Schema, Settings, SettingsExistenceStatus, SchemaEntry, KeyedObject, SettingsUpdateContext } from '../src'; const ava = unknownTest as TestInterface<{ client: KlasaClient, gateway: Gateway, schema: Schema, settings: Settings, provider: Provider }>; ava.beforeEach(async (test): Promise<void> => { const client = createClient(); const schema = new Schema() .add('count', 'number') .add('messages', 'string', { array: true }); const gateway = new Gateway(client, 'settings-test', { provider: 'json', schema }); const provider = gateway.provider as Provider; client.gateways.register(gateway); await gateway.init(); const id = '1'; const settings = new Settings(gateway, { id }, id); test.context = { client, gateway, schema, settings, provider }; }); ava('Settings Properties', (test): void => { test.plan(5); const id = '1'; const target = { id }; const settings = new Settings(test.context.gateway, target, id); test.is(settings.id, id); test.is(settings.gateway, test.context.gateway); test.is(settings.target, target); test.is(settings.existenceStatus, SettingsExistenceStatus.Unsynchronized); test.deepEqual(settings.toJSON(), { count: null, messages: [] }); }); ava('Settings#clone', (test): void => { test.plan(4); const { settings } = test.context; const clone = settings.clone(); test.true(clone instanceof Settings); test.is(settings.id, clone.id); test.is(settings.target, clone.target); test.deepEqual(clone.toJSON(), settings.toJSON()); }); ava('Settings#sync (Not Exists)', async (test): Promise<void> => { test.plan(2); const { settings } = test.context; test.is(await settings.sync(), settings); test.is(settings.existenceStatus, SettingsExistenceStatus.NotExists); }); ava('Settings#sync (Exists)', async (test): Promise<void> => { test.plan(7); const { settings } = test.context; await test.context.provider.create(test.context.gateway.name, settings.id, { count: 60 }); settings.client.once('settingsSync', (...args) => { test.is(args.length, 1); const emittedSettings = args[0] as unknown as Settings; test.is(emittedSettings, settings); test.is(emittedSettings.existenceStatus, SettingsExistenceStatus.Exists); test.is(emittedSettings.get('count'), 60); }); test.is(await settings.sync(), settings); test.is(settings.existenceStatus, SettingsExistenceStatus.Exists); test.is(settings.get('count'), 60); }); ava('Settings#destroy (Not Exists)', async (test): Promise<void> => { test.plan(2); const { settings } = test.context; test.is(await settings.destroy(), settings); test.is(settings.existenceStatus, SettingsExistenceStatus.NotExists); }); ava('Settings#destroy (Exists)', async (test): Promise<void> => { test.plan(9); const { settings } = test.context; await test.context.provider.create(test.context.gateway.name, settings.id, { count: 120 }); settings.client.once('settingsDelete', (...args) => { test.is(args.length, 1); // The emitted settings are the settings before getting reset synchronously. // To keep the state a little longer, synchronous code is required. Otherwise // the user must clone it. const emittedSettings = args[0] as unknown as Settings; test.is(emittedSettings, settings); test.is(emittedSettings.get('count'), 120); test.is(emittedSettings.existenceStatus, SettingsExistenceStatus.Exists); }); test.is(await settings.sync(), settings); test.is(settings.get('count'), 120); test.is(await settings.destroy(), settings); test.is(settings.existenceStatus, SettingsExistenceStatus.NotExists); test.is(settings.get('count'), null); }); ava('Settings#pluck', async (test): Promise<void> => { test.plan(5); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { count: 65 }); await settings.sync(); test.deepEqual(settings.pluck('count'), [65]); test.deepEqual(settings.pluck('messages'), [[]]); test.deepEqual(settings.pluck('invalid.path'), [undefined]); test.deepEqual(settings.pluck('count', 'messages'), [65, []]); test.deepEqual(settings.pluck('count', 'messages', 'invalid.path'), [65, [], undefined]); }); ava('Settings#resolve', async (test): Promise<void> => { test.plan(4); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { count: 65 }); await settings.sync(); // Check if single value from root's folder is resolved correctly test.deepEqual(await settings.resolve('count'), [65]); // Check if multiple values are resolved correctly test.deepEqual(await settings.resolve('count', 'messages'), [65, []]); // Update and give it an actual value await provider.update(gateway.name, settings.id, { messages: ['Hello'] }); await settings.sync(true); test.deepEqual(await settings.resolve('messages'), [['Hello']]); // Invalid path test.deepEqual(await settings.resolve('invalid.path'), [undefined]); }); ava('Settings#reset (Single | Not Exists)', async (test): Promise<void> => { test.plan(3); const { settings, gateway, provider } = test.context; await settings.sync(); test.is(await provider.get(gateway.name, settings.id), null); test.deepEqual(await settings.reset('count'), []); test.is(await provider.get(gateway.name, settings.id), null); }); ava('Settings#reset (Single | Exists)', async (test): Promise<void> => { test.plan(7); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { count: 64 }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, count: 64 }); const results = await settings.reset('count'); test.is(results.length, 1); test.is(results[0].previous, 64); test.is(results[0].next, null); test.is(results[0].entry, gateway.schema.get('count')); test.is(settings.get('count'), null); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, count: null }); }); ava('Settings#reset (Multiple[Array] | Not Exists)', async (test): Promise<void> => { test.plan(3); const { settings, gateway, provider } = test.context; await settings.sync(); test.is(await provider.get(gateway.name, settings.id), null); test.deepEqual(await settings.reset(['count', 'messages']), []); test.is(await provider.get(gateway.name, settings.id), null); }); ava('Settings#reset (Multiple[Array] | Exists)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['world'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['world'] }); const results = await settings.reset(['count', 'messages']); test.is(results.length, 1); test.deepEqual(results[0].previous, ['world']); test.deepEqual(results[0].next, []); test.is(results[0].entry, gateway.schema.get('messages')); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#reset (Multiple[Object] | Not Exists)', async (test): Promise<void> => { test.plan(3); const { settings, gateway, provider } = test.context; await settings.sync(); test.is(await provider.get(gateway.name, settings.id), null); test.deepEqual(await settings.reset({ count: true, messages: true }), []); test.is(await provider.get(gateway.name, settings.id), null); }); ava('Settings#reset (Multiple[Object] | Exists)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['world'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['world'] }); const results = await settings.reset({ count: true, messages: true }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['world']); test.deepEqual(results[0].next, []); test.is(results[0].entry, gateway.schema.get('messages')); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#reset (Multiple[Object-Deep] | Not Exists)', async (test): Promise<void> => { test.plan(3); const { settings, gateway, provider } = test.context; await settings.sync(); test.is(await provider.get(gateway.name, settings.id), null); test.deepEqual(await settings.reset({ count: true, messages: true }), []); test.is(await provider.get(gateway.name, settings.id), null); }); ava('Settings#reset (Multiple[Object-Deep] | Exists)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['world'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['world'] }); const results = await settings.reset({ count: true, messages: true }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['world']); test.deepEqual(results[0].next, []); test.is(results[0].entry, gateway.schema.get('messages')); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#reset (Root | Not Exists)', async (test): Promise<void> => { test.plan(3); const { settings, gateway, provider } = test.context; await settings.sync(); test.is(await provider.get(gateway.name, settings.id), null); test.deepEqual(await settings.reset(), []); test.is(await provider.get(gateway.name, settings.id), null); }); ava('Settings#reset (Root | Exists)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['world'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['world'] }); const results = await settings.reset(); test.is(results.length, 1); test.deepEqual(results[0].previous, ['world']); test.deepEqual(results[0].next, []); test.is(results[0].entry, gateway.schema.get('messages')); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#reset (Array | Empty)', async (test): Promise<void> => { test.plan(3); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, {}); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id }); const results = await settings.reset('messages'); test.is(results.length, 0); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id }); }); ava('Settings#reset (Array | Filled)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); const results = await settings.reset('messages'); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.is(results[0].next, (schema.get('messages') as SchemaEntry).default); test.is(results[0].entry, schema.get('messages') as SchemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#reset (Events | Not Exists)', async (test): Promise<void> => { test.plan(1); const { client, settings } = test.context; await settings.sync(); client.once('settingsCreate', () => test.fail()); client.once('settingsUpdate', () => test.fail()); test.deepEqual(await settings.reset('count'), []); }); ava('Settings#reset (Events | Exists)', async (test): Promise<void> => { test.plan(9); const { client, settings, gateway, provider, schema } = test.context; await provider.create(gateway.name, settings.id, { count: 64 }); await settings.sync(); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', () => test.fail()); client.once('settingsUpdate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: null }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, 64); test.is(context.changes[0].next, schemaEntry.default); test.is(context.extraContext, undefined); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); await settings.reset('count'); }); ava('Settings#reset (Events + Extra | Exists)', async (test): Promise<void> => { test.plan(9); const { client, settings, gateway, provider, schema } = test.context; await provider.create(gateway.name, settings.id, { count: 64 }); await settings.sync(); const extraContext = Symbol('Hello!'); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', () => test.fail()); client.once('settingsUpdate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: null }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, 64); test.is(context.changes[0].next, schemaEntry.default); test.is(context.extraContext, extraContext); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); await settings.reset('count', { extraContext }); }); ava('Settings#reset (Unsynchronized)', async (test): Promise<void> => { test.plan(1); const { settings } = test.context; await test.throwsAsync(() => settings.reset(), { message: 'Cannot reset keys from an unsynchronized settings instance. Perhaps you want to call `sync()` first.' }); }); ava('Settings#reset (Invalid Key)', async (test): Promise<void> => { test.plan(1); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['world'] }); await settings.sync(); await test.throwsAsync(() => settings.reset('invalid.path'), { message: '[SETTING_GATEWAY_KEY_NOEXT]: invalid.path' }); }); ava('Settings#update (Single)', async (test): Promise<void> => { test.plan(8); const { settings, gateway, schema, provider } = test.context; await settings.sync(); test.is(settings.existenceStatus, SettingsExistenceStatus.NotExists); const results = await settings.update('count', 2); test.is(results.length, 1); test.is(results[0].previous, null); test.is(results[0].next, 2); test.is(results[0].entry, schema.get('count') as SchemaEntry); test.is(settings.get('count'), 2); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, count: 2 }); test.is(settings.existenceStatus, SettingsExistenceStatus.Exists); }); ava('Settings#update (Multiple)', async (test): Promise<void> => { test.plan(8); const { settings, gateway, schema, provider } = test.context; await settings.sync(); const results = await settings.update([['count', 6], ['messages', [4]]]); test.is(results.length, 2); // count test.is(results[0].previous, null); test.is(results[0].next, 6); test.is(results[0].entry, schema.get('count') as SchemaEntry); // messages test.deepEqual(results[1].previous, []); test.deepEqual(results[1].next, ['4']); test.is(results[1].entry, schema.get('messages') as SchemaEntry); // persistence test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, count: 6, messages: ['4'] }); }); ava('Settings#update (Multiple | Object)', async (test): Promise<void> => { test.plan(8); const { settings, gateway, schema, provider } = test.context; await settings.sync(); const results = await settings.update({ count: 6, messages: [4] }); test.is(results.length, 2); // count test.is(results[0].previous, null); test.is(results[0].next, 6); test.is(results[0].entry, schema.get('count') as SchemaEntry); // messages test.deepEqual(results[1].previous, []); test.deepEqual(results[1].next, ['4']); test.is(results[1].entry, schema.get('messages') as SchemaEntry); // persistence test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, count: 6, messages: ['4'] }); }); ava('Settings#update (Not Exists | Default Value)', async (test): Promise<void> => { test.plan(2); const { settings, gateway, provider } = test.context; await settings.sync(); test.is(await provider.get(gateway.name, settings.id), null); await settings.update('messages', null); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#update (ArrayAction | Empty | Default)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, provider } = test.context; await settings.sync(); const schemaEntry = gateway.schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2']); test.is(results.length, 1); test.is(results[0].previous, schemaEntry.default); test.deepEqual(results[0].next, ['1', '2']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2'] }); }); ava('Settings#update (ArrayAction | Filled | Default)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); const results = await settings.update('messages', ['1', '2', '4']); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, []); test.is(results[0].entry, schema.get('messages') as SchemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#update (ArrayAction | Empty | Auto)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, provider } = test.context; await settings.sync(); const schemaEntry = gateway.schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2'], { arrayAction: 'auto' }); test.is(results.length, 1); test.is(results[0].previous, schemaEntry.default); test.deepEqual(results[0].next, ['1', '2']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2'] }); }); ava('Settings#update (ArrayAction | Filled | Auto)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); const results = await settings.update('messages', ['1', '2', '4'], { arrayAction: 'auto' }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, []); test.is(results[0].entry, schema.get('messages') as SchemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#update (ArrayAction | Empty | Add)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, provider } = test.context; await settings.sync(); const schemaEntry = gateway.schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2'], { arrayAction: 'add' }); test.is(results.length, 1); test.is(results[0].previous, schemaEntry.default); test.deepEqual(results[0].next, ['1', '2']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2'] }); }); ava('Settings#update (ArrayAction | Filled | Add)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); const results = await settings.update('messages', ['3', '5', '6'], { arrayAction: 'add' }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, ['1', '2', '4', '3', '5', '6']); test.is(results[0].entry, schema.get('messages') as SchemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4', '3', '5', '6'] }); }); ava('Settings#update (ArrayAction | Empty | Remove)', async (test): Promise<void> => { test.plan(2); const { settings, provider, gateway } = test.context; await settings.sync(); await test.throwsAsync(() => settings.update('messages', ['1', '2'], { arrayAction: 'remove' }), { message: '[SETTING_GATEWAY_MISSING_VALUE]: messages 1' }); test.is(await provider.get(gateway.name, settings.id), null); }); ava('Settings#update (ArrayAction | Filled | Remove)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); const schemaEntry = gateway.schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2'], { arrayAction: 'remove' }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, ['4']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['4'] }); }); ava('Settings#update (ArrayAction | Filled | Remove With Nulls)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '3', '4'] }); await settings.sync(); const schemaEntry = gateway.schema.get('messages') as SchemaEntry; const results = await settings.update('messages', [null, null], { arrayAction: 'remove', arrayIndex: 1 }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '3', '4']); test.deepEqual(results[0].next, ['1', '4']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '4'] }); }); ava('Settings#update (ArrayAction | Empty | Overwrite)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, provider } = test.context; await settings.sync(); const schemaEntry = gateway.schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2', '4'], { arrayAction: 'overwrite' }); test.is(results.length, 1); test.is(results[0].previous, schemaEntry.default); test.deepEqual(results[0].next, ['1', '2', '4']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); }); ava('Settings#update (ArrayAction | Filled | Overwrite)', async (test): Promise<void> => { test.plan(6); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); const results = await settings.update('messages', ['3', '5', '6'], { arrayAction: 'overwrite' }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, ['3', '5', '6']); test.is(results[0].entry, schema.get('messages') as SchemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['3', '5', '6'] }); }); ava('Settings#update (ArrayIndex | Empty | Auto)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, schema, provider } = test.context; await settings.sync(); const schemaEntry = schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2', '3'], { arrayIndex: 0 }); test.is(results.length, 1); test.is(results[0].previous, schemaEntry.default); test.deepEqual(results[0].next, ['1', '2', '3']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '3'] }); }); ava('Settings#update (ArrayIndex | Filled | Auto)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); const schemaEntry = schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['5', '6'], { arrayIndex: 0 }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, ['5', '6', '4']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['5', '6', '4'] }); }); ava('Settings#update (ArrayIndex | Empty | Add)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, schema, provider } = test.context; await settings.sync(); const schemaEntry = schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2', '3'], { arrayIndex: 0, arrayAction: 'add' }); test.is(results.length, 1); test.is(results[0].previous, schemaEntry.default); test.deepEqual(results[0].next, ['1', '2', '3']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '3'] }); }); ava('Settings#update (ArrayIndex | Filled | Add)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); const schemaEntry = schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['5', '6'], { arrayIndex: 0, arrayAction: 'add' }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, ['5', '6', '1', '2', '4']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['5', '6', '1', '2', '4'] }); }); ava('Settings#update (ArrayIndex | Filled | Add | Error)', async (test): Promise<void> => { test.plan(2); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); await test.throwsAsync(() => settings.update('messages', '4', { arrayAction: 'add' }), { message: '[SETTING_GATEWAY_DUPLICATE_VALUE]: messages 4' }); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); }); ava('Settings#update (ArrayIndex | Empty | Remove)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, schema, provider } = test.context; await settings.sync(); const schemaEntry = schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2'], { arrayIndex: 0, arrayAction: 'remove' }); test.is(results.length, 1); test.is(results[0].previous, schemaEntry.default); test.deepEqual(results[0].next, []); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: [] }); }); ava('Settings#update (ArrayIndex | Filled | Remove)', async (test): Promise<void> => { test.plan(5); const { settings, gateway, schema, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); const schemaEntry = schema.get('messages') as SchemaEntry; const results = await settings.update('messages', ['1', '2'], { arrayIndex: 1, arrayAction: 'remove' }); test.is(results.length, 1); test.deepEqual(results[0].previous, ['1', '2', '4']); test.deepEqual(results[0].next, ['1']); test.is(results[0].entry, schemaEntry); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1'] }); }); ava('Settings#update (ArrayIndex | Filled | Remove | Error)', async (test): Promise<void> => { test.plan(2); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['1', '2', '4'] }); await settings.sync(); await test.throwsAsync(() => settings.update('messages', 3, { arrayAction: 'remove' }), { message: '[SETTING_GATEWAY_MISSING_VALUE]: messages 3' }); test.deepEqual(await provider.get(gateway.name, settings.id), { id: settings.id, messages: ['1', '2', '4'] }); }); ava('Settings#update (Events | Not Exists)', async (test): Promise<void> => { test.plan(9); const { client, schema, settings } = test.context; await settings.sync(); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: 64 }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, schemaEntry.default); test.is(context.changes[0].next, 64); test.is(context.extraContext, undefined); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); client.once('settingsUpdate', () => test.fail()); await settings.update('count', 64); }); ava('Settings#update (Events | Exists | Simple)', async (test): Promise<void> => { test.plan(9); const { client, settings, gateway, provider, schema } = test.context; await provider.create(gateway.name, settings.id, { count: 64 }); await settings.sync(); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', () => test.fail()); client.once('settingsUpdate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: 420 }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, 64); test.is(context.changes[0].next, 420); test.is(context.extraContext, undefined); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); await settings.update('count', 420); }); ava('Settings#update (Events | Exists | Array Overload | Options)', async (test): Promise<void> => { test.plan(9); const { client, settings, gateway, provider, schema } = test.context; await provider.create(gateway.name, settings.id, { count: 64 }); await settings.sync(); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', () => test.fail()); client.once('settingsUpdate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: 420 }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, 64); test.is(context.changes[0].next, 420); test.is(context.extraContext, 'Hello!'); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); await settings.update([['count', 420]], { extraContext: 'Hello!' }); }); ava('Settings#update (Events | Exists | Object Overload | Options)', async (test): Promise<void> => { test.plan(9); const { client, settings, gateway, provider, schema } = test.context; await provider.create(gateway.name, settings.id, { count: 64 }); await settings.sync(); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', () => test.fail()); client.once('settingsUpdate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: 420 }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, 64); test.is(context.changes[0].next, 420); test.is(context.extraContext, 'Hello!'); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); await settings.update({ count: 420 }, { extraContext: 'Hello!' }); }); ava('Settings#update (Events + Extra | Not Exists)', async (test): Promise<void> => { test.plan(9); const { client, settings, schema } = test.context; await settings.sync(); const extraContext = Symbol('Hello!'); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: 420 }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, schemaEntry.default); test.is(context.changes[0].next, 420); test.is(context.extraContext, extraContext); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); client.once('settingsUpdate', () => test.fail()); await settings.update('count', 420, { extraContext }); }); ava('Settings#update (Events + Extra | Exists)', async (test): Promise<void> => { test.plan(9); const { client, settings, gateway, provider, schema } = test.context; await provider.create(gateway.name, settings.id, { count: 64 }); await settings.sync(); const extraContext = Symbol('Hello!'); const schemaEntry = schema.get('count') as SchemaEntry; client.once('settingsCreate', () => test.fail()); client.once('settingsUpdate', (emittedSettings: Settings, changes: KeyedObject, context: SettingsUpdateContext) => { test.is(emittedSettings, settings); test.deepEqual(changes, { count: 420 }); test.is(context.changes.length, 1); test.is(context.changes[0].entry, schemaEntry); test.is(context.changes[0].previous, 64); test.is(context.changes[0].next, 420); test.is(context.extraContext, extraContext); test.is(context.guild, null); test.is(context.language, client.languages.get('en-US')); }); await settings.update('count', 420, { extraContext }); }); ava('Settings#update (Uninitialized)', async (test): Promise<void> => { test.plan(1); const { settings } = test.context; await test.throwsAsync(() => settings.update('count', 6), { message: 'Cannot update values from an unsynchronized settings instance. Perhaps you want to call `sync()` first.' }); }); ava('Settings#update (Unsynchronized)', async (test): Promise<void> => { test.plan(1); const { settings } = test.context; await test.throwsAsync(() => settings.update('count', 6), { message: 'Cannot update values from an unsynchronized settings instance. Perhaps you want to call `sync()` first.' }); }); ava('Settings#update (Invalid Key)', async (test): Promise<void> => { test.plan(1); const { settings, gateway, provider } = test.context; await provider.create(gateway.name, settings.id, { messages: ['world'] }); await settings.sync(); await test.throwsAsync(() => settings.update('invalid.path', 420), { message: '[SETTING_GATEWAY_KEY_NOEXT]: invalid.path' }); }); ava('Settings#toJSON', async (test): Promise<void> => { test.plan(2); const { settings, gateway, provider } = test.context; // Non-synced entry should have schema defaults test.deepEqual(settings.toJSON(), { messages: [], count: null }); await provider.create(gateway.name, settings.id, { count: 123, messages: [] }); await settings.sync(); // Synced entry should use synced values or schema defaults test.deepEqual(settings.toJSON(), { messages: [], count: 123 }); });
the_stack
import { Page, ReferencePointer, CryptoInterface } from '../parser'; import { Util } from '../util'; import { ErrorList, InvalidOpacityError, InvalidRectError, InvalidDateError, InvalidReferencePointerError, ColorOutOfRangeError, InvalidColorError, InvalidIDError } from './annotation_errors'; import { WriterUtil } from '../writer-util'; export enum LineEndingStyle { Square, Circle, Diamond, OpenArrow, ClosedArrow, Butt, ROpenArrow, RClosedArrow, Slash, None } export interface Color { r: number g: number b: number } export enum BorderStyles { Solid, Dashed, Beveled, Inset, Underline } export interface Border { horizontal_corner_radius?: number vertical_corner_radius?: number border_width?: number dash_pattern?: number[] border_style?: BorderStyles cloudy?: boolean cloud_intensity?: number } export interface AnnotationFlags { invisible?: boolean hidden?: boolean print?: boolean noZoom?: boolean noRotate?: boolean noView?: boolean readOnly?: boolean locked?: boolean toggleNoView?: boolean lockedContents?: boolean } export interface AppearanceStream { } export interface OptionalContent { } export interface BaseAnnotation { page: number pageReference: Page | undefined // The reference to the page object to which the annotation is added object_id: ReferencePointer | undefined // an unused object id type?: string rect: number[] contents?: string | undefined id: string // /NM updateDate: string | Date// /M annotationFlags?: AnnotationFlags | undefined // /F appearanceStream?: AppearanceStream | undefined // /AP appearanceStreamSelector?: string | undefined // /AS border?: Border | undefined color?: Color | undefined // /C structParent?: number | undefined // /StructParent optionalContent?: OptionalContent | undefined // /OC is_deleted?: boolean // internal flag to determine whether the annotation was deleted } export class BaseAnnotationObj implements BaseAnnotation { object_id: ReferencePointer | undefined = undefined// an unused object id is_deleted: boolean = false// internal flag to determine whether the annotation was deleted raw_parameters: number[][] | undefined page: number = -1 pageReference: Page | undefined = undefined// The reference to the page object to which the annotation is added type: string = "" type_encoded: number[] = [] rect: number[] = [] contents: string = "" id: string = ""// /NM updateDate: string | Date = ""// /M annotationFlags: AnnotationFlags | undefined // /F border: Border | undefined color: Color | undefined // /C optionalContent: OptionalContent | undefined // /OC structParent: number | undefined // /StructParent appearanceStream: AppearanceStream | undefined // /AP appearanceStreamSelector: string | undefined // /AS constructor() { } public writeAnnotationPreamble() : number[] { let ret: number[] = WriterUtil.writeReferencePointer(this.object_id!) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.OBJ) ret.push(WriterUtil.CR) ret.push(WriterUtil.LF) ret = ret.concat(WriterUtil.DICT_START) ret = ret.concat(WriterUtil.TYPE_ANNOT) ret.push(WriterUtil.SPACE) return ret } public writeAnnotationObject(cryptoInterface : CryptoInterface) : number[] { let ret : number[] = [] ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.PAGE_REFERENCE) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.writeReferencePointer(this.pageReference!.object_id!, true)) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.SUBTYPE) ret.push(WriterUtil.SPACE) ret = ret.concat(this.type_encoded) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.RECT) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.writeNumberArray(this.rect)) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.CONTENTS) ret.push(WriterUtil.SPACE) ret.push(WriterUtil.BRACKET_START) ret = ret.concat(Array.from(Util.escapeString(cryptoInterface.encrypt(new Uint8Array(Util.convertStringToAscii(this.contents)), this.object_id)))) ret.push(WriterUtil.BRACKET_END) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.ID) ret.push(WriterUtil.SPACE) ret.push(WriterUtil.BRACKET_START) ret = ret.concat(Array.from(Util.escapeString(cryptoInterface.encrypt(new Uint8Array(Util.convertStringToAscii(this.id)), this.object_id)))) ret.push(WriterUtil.BRACKET_END) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.UPDATE_DATE) ret.push(WriterUtil.SPACE) ret.push(WriterUtil.BRACKET_START) ret = ret.concat(Array.from(Util.escapeString(cryptoInterface.encrypt(new Uint8Array(Util.convertStringToAscii(this.updateDate as string)), this.object_id)))) ret.push(WriterUtil.BRACKET_END) ret.push(WriterUtil.SPACE) if (this.annotationFlags) { let flags_value : number = this.encodeAnnotationFlags() ret = ret.concat(WriterUtil.FLAG) ret.push(WriterUtil.SPACE) ret = ret.concat(Util.convertNumberToCharArray(flags_value)) ret.push(WriterUtil.SPACE) } if (this.border) { ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.BORDER) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.writeNumberArray([this.border.horizontal_corner_radius || 0, this.border.vertical_corner_radius || 0, this.border.border_width || 1])) ret.push(WriterUtil.SPACE) } if (this.color) { if (this.color.r > 1) this.color.r /= 255 if (this.color.g > 1) this.color.g /= 255 if (this.color.b > 1) this.color.b /= 255 ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.COLOR) ret.push(WriterUtil.SPACE) ret = ret.concat(WriterUtil.writeNumberArray([this.color.r, this.color.g, this.color.b])) ret.push(WriterUtil.SPACE) } if (this.raw_parameters && this.raw_parameters.length > 0) { for(let i of this.raw_parameters) { ret.push(WriterUtil.SPACE) ret = ret.concat(i) ret.push(WriterUtil.SPACE) } } return ret } protected convertLineEndingStyle(lne : LineEndingStyle) : number[] { switch(lne) { case LineEndingStyle.Square: return Util.convertStringToAscii("/Square") case LineEndingStyle.Circle: return Util.convertStringToAscii("/Circle") case LineEndingStyle.Diamond: return Util.convertStringToAscii("/Diamond") case LineEndingStyle.OpenArrow: return Util.convertStringToAscii("/OpenArrow") case LineEndingStyle.ClosedArrow: return Util.convertStringToAscii("/ClosedArrow") case LineEndingStyle.Butt: return Util.convertStringToAscii("/Butt") case LineEndingStyle.ROpenArrow: return Util.convertStringToAscii("/ROpenArrow") case LineEndingStyle.RClosedArrow: return Util.convertStringToAscii("/RClosedArrow") case LineEndingStyle.Slash: return Util.convertStringToAscii("/Slash") default: return Util.convertStringToAscii("/None") } } public writeAnnotationPostamble() : number[] { let ret : number[] = WriterUtil.DICT_END ret.push(WriterUtil.CR) ret.push(WriterUtil.LF) ret = ret.concat(WriterUtil.ENDOBJ) ret.push(WriterUtil.CR) ret.push(WriterUtil.LF) return ret } public encodeAnnotationFlags() : number { if (!this.annotationFlags) { return 0 } let val = 0 if (this.annotationFlags.invisible) { val |= 1 } if (this.annotationFlags.hidden) { val |= 2 } if (this.annotationFlags.print) { val |= 4 } if (this.annotationFlags.noZoom) { val |= 8 } if (this.annotationFlags.noRotate) { val |= 16 } if (this.annotationFlags.noView) { val |= 32 } if (this.annotationFlags.readOnly) { val |= 64 } if (this.annotationFlags.locked) { val |= 128 } if (this.annotationFlags.toggleNoView) { val |= 256 } if (this.annotationFlags.lockedContents) { val |= 512 } return val } /** * If enact is true, the error will be thrown directly, otherwise the errors are collected * and returned as error list. * */ public validate(enact : boolean = true) : ErrorList { let errorList : ErrorList = this.checkRect(4, this.rect) errorList = errorList.concat(this.checkReferencePointer(this.object_id)) if(!this.pageReference || typeof this.pageReference !== 'object') { errorList.push(new InvalidReferencePointerError("Inalid page reference")) } let res = this.checkDate(this.updateDate) if (res[1]) { this.updateDate = res[1] } errorList = errorList.concat(res[0]) errorList = errorList.concat(this.checkColor(this.color)) if (!this.id || this.id === "") { errorList.push(new InvalidIDError("Invalid ID provided")) } if (enact) { for(let error of errorList) { throw error } } return errorList } protected checkColor(color : Color | undefined) : ErrorList { let errorList : ErrorList = [] if (!color) { return errorList } if (!(color && "r" in color && "g" in color && "b" in color)) { errorList.push(new InvalidColorError("Not {r: <r>, g: <g>, b: <b>}")) } if (color!.r > 255 || color!.r < 0) { errorList.push(new ColorOutOfRangeError("Red value out of range")) } if (color!.g > 255 || color!.g < 0) { errorList.push(new ColorOutOfRangeError("Green value out of range")) } if(color!.b > 255 && color!.b < 0) { errorList.push(new ColorOutOfRangeError("Blue value out of range")) } return errorList } protected checkReferencePointer(ptr : ReferencePointer | undefined) : ErrorList { let errorList : ErrorList = [] if(!(ptr && "obj" in ptr && ptr.obj >= 0 && "generation" in ptr && ptr.generation >= 0)) { errorList.push(new InvalidReferencePointerError("Invalid reference pointer")) } return errorList } protected checkDate(date : string | Date) : [ErrorList, string | undefined] { if (typeof date === 'string') { return [[], date] } let errorList : ErrorList = [] let ret_val : string | undefined = undefined try { ret_val = Util.convertDateToPDFDate(date as Date) } catch (e) { errorList.push(new InvalidDateError("Invalid update date provided")) } return [errorList, ret_val] } protected checkRect(nr: number, rect: number[]) : ErrorList { let errorList : ErrorList = [] if (!Array.isArray(rect)) { errorList.push(new InvalidRectError("invalid rect parameter")) } if (rect.length !== nr) { errorList.push(new InvalidRectError("Rect has invalid number of entries: " + rect + " has " + rect.length + " entries, but should have " + nr + " entries")) } rect.forEach((a) => { if ('number' !== typeof a) { errorList.push(new InvalidRectError("Rect " + rect + " has invalid entry: " + a)) } }) return errorList } } export enum ReplyTypes { Reply, Group } export interface InReplyTo {} export interface MarkupAnnotation extends BaseAnnotation { author?: string // /T opacity?: number // /CA richtextString?: string // /RC creationDate?: string | Date // /CreationDate inReplyTo?: InReplyTo // /IRT subject?: string // /Subj replyType?: ReplyTypes // /RT } export class MarkupAnnotationObj extends BaseAnnotationObj implements MarkupAnnotation { author: string = "" opacity?: number = 1// /CA creationDate?: string | Date // /CreationDate subject : string = "" richtextString?: string constructor() { super() } public writeAnnotationObject(cryptoInterface : CryptoInterface) : number[] { let ret : number[] = super.writeAnnotationObject(cryptoInterface) ret = ret.concat(WriterUtil.AUTHOR) ret.push(WriterUtil.SPACE) ret.push(WriterUtil.BRACKET_START) ret = ret.concat(Array.from(Util.escapeString(cryptoInterface.encrypt(new Uint8Array(Util.convertStringToAscii(this.author)), this.object_id)))) ret.push(WriterUtil.BRACKET_END) ret.push(WriterUtil.SPACE) if (this.opacity) { ret = ret.concat(WriterUtil.OPACITY) ret.push(WriterUtil.SPACE) ret = ret.concat(Util.convertNumberToCharArray(this.opacity)) ret.push(WriterUtil.SPACE) } if (this.creationDate) { ret = ret.concat(WriterUtil.CREATION_DATE) ret.push(WriterUtil.SPACE) ret.push(WriterUtil.BRACKET_START) ret = ret.concat(Array.from(Util.escapeString(cryptoInterface.encrypt(new Uint8Array(Util.convertStringToAscii(this.creationDate as string)), this.object_id)))) ret.push(WriterUtil.BRACKET_END) ret.push(WriterUtil.SPACE) } if (this.subject !== "") { ret = ret.concat(WriterUtil.SUBJ) ret.push(WriterUtil.SPACE) ret.push(WriterUtil.BRACKET_START) ret = ret.concat(Array.from(Util.escapeString(cryptoInterface.encrypt(new Uint8Array(Util.convertStringToAscii(this.subject)), this.object_id)))) ret.push(WriterUtil.BRACKET_END) ret.push(WriterUtil.SPACE) } if (this.richtextString) { ret = ret.concat(WriterUtil.RC) ret.push(WriterUtil.SPACE) ret.push(WriterUtil.BRACKET_START) ret = ret.concat(Array.from(Util.escapeString(cryptoInterface.encrypt(new Uint8Array(Util.convertStringToAscii(this.richtextString!)), this.object_id)))) ret.push(WriterUtil.BRACKET_END) ret.push(WriterUtil.SPACE) } return ret } public validate(enact : boolean = true) : ErrorList { let errorList : ErrorList = super.validate(false) if (this.opacity) { try { this.opacity = +this.opacity } catch (e) { errorList.push(new InvalidOpacityError("Opacity no numerical value")) } if (this.opacity < 0 || this.opacity > 255) { errorList.push(new InvalidOpacityError("Opacity out of range")) } } if (this.creationDate) { let res = this.checkDate(this.creationDate) this.creationDate = res[1] errorList = errorList.concat(res[0]) } if (enact) { for(let error of errorList) { throw error } } return errorList } }
the_stack
import { BinaryHeap } from './BinaryHeap'; import { GridNode } from './GridNode'; export type PathFindingHeuristicFunction = (pos0: GridNode, pos1: GridNode) => number; export type PathFindingSearchOptions = { heuristic?: PathFindingHeuristicFunction; closest?: boolean; }; export type PathFindingOptions = { diagonal?: boolean; closest?: boolean; }; // Based on http://github.com/bgrins/javascript-astar v0.4.0 /** * Includes all path finding logic. * * @class PathFinding */ export class PathFinding { /** * @property {Array(Array(GridNode))} grid * @private */ private grid: GridNode[][]; /** * @property {boolean} diagonal * @private */ private diagonal: boolean; /** * Active heuristic method to use * @property * @private */ private heuristic: PathFindingHeuristicFunction; private closest: boolean; private nodes: GridNode[]; private dirtyNodes: GridNode[]; /** * See list of heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html * * @property * @private * @static */ private static readonly HEURISTICS: { [key in 'manhattan' | 'diagonal']: PathFindingHeuristicFunction; } = { manhattan: (pos0: GridNode, pos1: GridNode) => { const d1 = Math.abs(pos1.x - pos0.x); const d2 = Math.abs(pos1.y - pos0.y); return d1 + d2; }, diagonal: (pos0: GridNode, pos1: GridNode) => { const D = 1; const D2 = Math.sqrt(2); const d1 = Math.abs(pos1.x - pos0.x); const d2 = Math.abs(pos1.y - pos0.y); return D * (d1 + d2) + (D2 - 2 * D) * Math.min(d1, d2); }, }; /** * Constructor function for the PathFinding class. * * @constructor * * @param mapSizeC {number} number of columns * @param mapSizeR {number} number of rows * @param options {PathFindingOptions} settings for the search algorithm, default `{}` */ constructor(mapSizeC: number, mapSizeR: number, options: PathFindingOptions = {}) { //define map this.nodes = []; this.diagonal = !!options.diagonal; this.heuristic = this.diagonal ? PathFinding.HEURISTICS.diagonal : PathFinding.HEURISTICS.manhattan; this.closest = !!options.closest; this.grid = []; let c = 0, r = 0, node: GridNode; for (c = 0; c < mapSizeC; c++) { this.grid[c] = []; for (r = 0; r < mapSizeR; r++) { node = new GridNode(c, r, 1); this.grid[c][r] = node; this.nodes.push(node); } } this.init(); } /** * Cleans/resets all nodes. * * @method init * @private */ private init(): void { this.dirtyNodes = []; for (let i = 0; i < this.nodes.length; i++) { this.cleanNode(this.nodes[i]); } } // /** // * Cleans only dirty nodes. // * // * @method cleanDirty // * @private // */ // private cleanDirty(): void { // for (let i = 0; i < this.dirtyNodes.length; i++) { // this.cleanNode(this.dirtyNodes[i]); // } // this.dirtyNodes = []; // } /** * Marks a node as dirty. * * @method markDirty * @private * @param node {TRAVISO.PathFinding.GridNode} node to be marked */ private markDirty(node: GridNode): void { this.dirtyNodes.push(node); } /** * Finds adjacent/neighboring cells of a single node. * * @method neighbors * @param node {TRAVISO.PathFinding.GridNode} source node * @return {Array(TRAVISO.PathFinding.GridNode)} an array of available cells */ private neighbors(node: GridNode): GridNode[] { const ret = [], x = node.x, y = node.y, grid = this.grid; // West if (grid[x - 1] && grid[x - 1][y]) { ret.push(grid[x - 1][y]); } // East if (grid[x + 1] && grid[x + 1][y]) { ret.push(grid[x + 1][y]); } // South if (grid[x] && grid[x][y - 1]) { ret.push(grid[x][y - 1]); } // North if (grid[x] && grid[x][y + 1]) { ret.push(grid[x][y + 1]); } if (this.diagonal) { // Southwest if (grid[x - 1] && grid[x - 1][y - 1]) { ret.push(grid[x - 1][y - 1]); } // Southeast if (grid[x + 1] && grid[x + 1][y - 1]) { ret.push(grid[x + 1][y - 1]); } // Northwest if (grid[x - 1] && grid[x - 1][y + 1]) { ret.push(grid[x - 1][y + 1]); } // Northeast if (grid[x + 1] && grid[x + 1][y + 1]) { ret.push(grid[x + 1][y + 1]); } } return ret; } public toString(): string { const graphString: string[] = [], nodes = this.grid; // when using grid let rowDebug: number[], row: GridNode[], x: number, len: number, y: number, l: number; for (x = 0, len = nodes.length; x < len; x++) { rowDebug = []; row = nodes[x]; for (y = 0, l = row.length; y < l; y++) { rowDebug.push(row[y].weight); } graphString.push(rowDebug.join(' ')); } return graphString.join('\n'); } /** * Solves path finding for the given source and destination locations. * * @method solve * @private * @param originC {number} column index of the source location * @param originR {number} row index of the source location * @param destC {number} column index of the destination location * @param destR {number} row index of the destination location * @return {Array(Object)} solution path */ public solve(originC: number, originR: number, destC: number, destR: number): GridNode[] { const start = this.grid[originC][originR]; const end = this.grid[destC][destR]; const result = this.search(start, end, { heuristic: this.heuristic, closest: this.closest, }); return result && result.length > 0 ? result : null; } /** * Finds available adjacent cells of an area defined by location and size. * * @method getAdjacentOpenCells * @param cellC {number} column index of the location * @param cellR {number} row index of the location * @param sizeC {number} column size of the area * @param sizeR {number} row size of the area * @return {Array(Object)} an array of available cells */ public getAdjacentOpenCells(cellC: number, cellR: number, sizeC: number, sizeR: number): GridNode[] { let r: number, c: number, cellArray: GridNode[] = []; for (r = cellR; r > cellR - sizeR; r--) { for (c = cellC; c < cellC + sizeC; c++) { // NOTE: concat is browser dependent. It is fastest for Chrome. Might be a good idea to use for loop or "a.push.apply(a, b);" for other browsers cellArray = cellArray.concat(this.neighbors(this.grid[c][r])); } } return cellArray; } private pathTo(node: GridNode): GridNode[] { let curr = node; const path: GridNode[] = []; while (curr.parent) { path.push(curr); curr = curr.parent; } // return path.reverse(); return path; } private getHeap(): BinaryHeap { return new BinaryHeap((node: unknown) => (node as GridNode).f); } /** * Perform an A* Search on a graph given a start and end node. * * @method * @function * @private * * @param start {GridNode} beginning node of search * @param end {GridNode} end node of the search * @param options {Object} Search options * @return {Array(GridNode)} resulting list of nodes */ private search(start: GridNode, end: GridNode, options: PathFindingSearchOptions = {}): GridNode[] { this.init(); const heuristic = options.heuristic || PathFinding.HEURISTICS.manhattan; const closest = options.closest || false; const openHeap = this.getHeap(); let closestNode = start; // set the start node to be the closest if required start.h = heuristic(start, end); openHeap.push(start); while (openHeap.size() > 0) { // Grab the lowest f(x) to process next. Heap keeps this sorted for us. const currentNode: GridNode = openHeap.pop() as GridNode; // End case -- result has been found, return the traced path. if (currentNode === end) { return this.pathTo(currentNode); } // Normal case -- move currentNode from open to closed, process each of its neighbors. currentNode.closed = true; // Find all neighbors for the current node. const neighbors = this.neighbors(currentNode); for (let i = 0, il = neighbors.length; i < il; ++i) { const neighbor = neighbors[i]; if (neighbor.closed || neighbor.isWall()) { // Not a valid node to process, skip to next neighbor. continue; } // The g score is the shortest distance from start to current node. // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet. const gScore = currentNode.g + neighbor.getCost(currentNode), beenVisited = neighbor.visited; if (!beenVisited || gScore < neighbor.g) { // Found an optimal (so far) path to this node. Take score for node to see how good it is. neighbor.visited = true; neighbor.parent = currentNode; neighbor.h = neighbor.h || heuristic(neighbor, end); neighbor.g = gScore; neighbor.f = neighbor.g + neighbor.h; this.markDirty(neighbor); if (closest) { // If the neighbor is closer than the current closestNode or if it's equally close but has // a cheaper path than the current closest node then it becomes the closest node if ( neighbor.h < closestNode.h || (neighbor.h === closestNode.h && neighbor.g < closestNode.g) ) { closestNode = neighbor; } } if (!beenVisited) { // Pushing to heap will put it in proper place based on the 'f' value. openHeap.push(neighbor); } else { // Already seen the node, but since it has been re-scored we need to reorder it in the heap openHeap.rescoreElement(neighbor); } } } } if (closest) { return this.pathTo(closestNode); } // No result was found - empty array signifies failure to find path. return []; } private cleanNode(node: GridNode): void { node.f = 0; node.g = 0; node.h = 0; node.visited = false; node.closed = false; node.parent = null; } /** * Checks if the location is occupied/available or not. * * @method isCellFilled * @param c {number} column index of the location * @param r {number} row index of the location * @return {Array(Object)} if the location is not available */ public isCellFilled(c: number, r: number): boolean { if (this.grid[c][r].weight === 0) { return true; } return false; } /** * Sets individual cell state for ground layer. * * @method setCell * @param c {number} column index of the location * @param r {number} row index of the location * @param movable {boolean} free to move or not */ public setCell(c: number, r: number, movable: number): void { this.grid[c][r].staticWeight = this.grid[c][r].weight = movable; } /** * Sets individual cell state for objects layer. * * @method setDynamicCell * @param c {number} column index of the location * @param r {number} row index of the location * @param movable {boolean} free to move or not */ public setDynamicCell(c: number, r: number, movable: number): void { // if it is movable by static tile property if (this.grid[c][r].staticWeight !== 0) { this.grid[c][r].weight = movable; } } /** * Clears all references. * * @method * @function * @public */ public destroy(): void { this.grid = null; this.nodes = null; this.dirtyNodes = null; this.heuristic = null; } }
the_stack
import { DiskStorage } from 'react-native' const AsyncStorage = new DiskStorage({ namespace: 'stats' }) import { getMyGameAPI, getGameAPI } from '../dao' const getGameURL = (psnid, page) => `https://psnine.com/psnid/${psnid}/psngame?page=${page}` const getGameList = async (psnid, callback) => { const list: any = [] let page = 1 callback && callback({ title: `正在获取第${page}页游戏` }) let result = await getMyGameAPI(getGameURL(psnid, page)) while (result.list.length !== 0) { list.push(...result.list) page++ callback && callback({ title: `正在获取第${page}页游戏` }) result = await getMyGameAPI(getGameURL(psnid, page)) } return list } declare var global export const removeAll = () => AsyncStorage.removeAll().then(() => global.toast('清理完毕')).catch(err => global.toast('清理失败: ' + err.toString())) export const removeItem = (psnid) => AsyncStorage.removeItem(`Statistics::TrophyList::${psnid.toLowerCase()}`).then(( ) => global.toast('清理完毕')).catch(err => global.toast('清理失败: ' + err.toString())) export const getTrophyList = async (psnid, callback, forceNew = false) => { const prefix = `Statistics::TrophyList::${psnid.toLowerCase()}` console.log('===> it really starts') if (forceNew === false) { let cacheStr = await AsyncStorage.getItem(prefix) if (cacheStr) { const cache = JSON.parse(cacheStr) // await AsyncStorage.removeItem(prefix) if (cache && cache.trophyList) { console.log('removing !!') // alert('remove cahce') await AsyncStorage.removeItem(prefix) } else { console.log('hehe global cache hit', Object.keys(cache)) const { gameList, statsInfo, trophyChunks } = cache console.log({ trophyChunks }) let trophyList: any = [] if (trophyChunks < 20) { trophyList = ([] as any).concat(...(await Promise.all( '0'.repeat(trophyChunks).split('').map((_, index) => { return AsyncStorage.getItem(`${prefix}::trophyChunk::${index}`) }) )).map(str => JSON.parse(str))) } else { for (let i = 0; i < trophyChunks; i++) { const str: string = await AsyncStorage.getItem(`${prefix}::trophyChunk::${i}`) trophyList.push(...JSON.parse(str)) callback && callback({ title: `正在读取中 (${i + 1}/${trophyChunks})` }) } } // console.log(trophyList[0], trophyList[1], trophyList[2]) const unearnedTrophyList = trophyList.filter(item => !item.timestamp) // console.log(unearnedTrophyList[0]) // console.log(trophyList.length, unearnedTrophyList.length, 'combined') return { gameList, statsInfo, trophyList, unearnedTrophyList } } } } const statsInfo: any = {} const gameList = (await getGameList(psnid, callback))//.slice(0, 2) const trophyList: any = [] let index = 0 // gameList[0].percent = '0%' for (const game of gameList) { const cacheKey = `${prefix}::${game.href}` // ::${game.trophyArr}::${game.percent} const cacheGame = await AsyncStorage.getItem(cacheKey) const cacheResult = await AsyncStorage.getItem(`${cacheKey}::trophy`) let outterResult console.log(!!cacheGame, !!cacheResult) if (cacheGame && cacheResult) { const parsedGame = JSON.parse(cacheGame) console.log('===>', parsedGame.percent, game.percent) if (parsedGame.trophyArr === game.trophyArr && parsedGame.percent === game.percent) { console.log('cache hit for game ' + game.title) outterResult = JSON.parse(cacheResult) } else { console.log('=================> cache not hit') } } const result = outterResult || (await getGameAPI(game.href)) if (!outterResult) { console.log('cache game for ' + game.title) await AsyncStorage.setItem(cacheKey, JSON.stringify(game)) await AsyncStorage.setItem(`${cacheKey}::trophy`, JSON.stringify(result)) } result.trophyArr.forEach(temp => { temp.list.forEach(trophy => { trophy.gameInfo = result.gameInfo trophy.playerInfo = result.playerInfo trophy.banner = temp.banner trophyList.push(trophy) }) }) // console.log('=========================================================>', index + 1, i) callback && callback({ gameInfo: result.gameInfo, trophyLength: trophyList.length, gameIndex: index + 1 }) index++ } // console.log(gameList.length, trophyList.length) const earnedTrophyList = trophyList.filter(item => item.timestamp).sort((a: any, b: any) => b.timestamp - a.timestamp) const unearnedTrophyList = trophyList.filter(item => !item.timestamp) statsd(statsInfo, gameList, { earnedTrophyList, unearnedTrophyList }) const allTrophyArr = sliceArrayByNumber(trophyList, 500) await AsyncStorage.setItem(prefix, JSON.stringify({ gameList, statsInfo, trophyChunks: allTrophyArr.length })) console.log({ trophyChunks: allTrophyArr.length, trophyList: trophyList.length }) if (allTrophyArr.length < 20) { await Promise.all( allTrophyArr.map((item, index) => { // console.log('=========================================>',item.length, item[0]) return AsyncStorage.setItem(`${prefix}::trophyChunk::${index}`, JSON.stringify(item)) }) ) } else { for (let index = 0; index < allTrophyArr.length; index++) { await AsyncStorage.setItem(`${prefix}::trophyChunk::${index}`, JSON.stringify(allTrophyArr[index])) callback && callback({ title: `正在存储中 (${index + 1}/${allTrophyArr.length})` }) } } return { gameList, trophyList: earnedTrophyList, statsInfo, unearnedTrophyList } } function mapObj(obj) { return Object.keys(obj).map(name => { return { label: name, value: obj[name] } }) } function statsd(statsInfo, gameList, { unearnedTrophyList, earnedTrophyList }) { // 平台 statsInfo.platform = mapObj(gameList.reduce((prev, curr) => { const { platform } = curr if (platform.length > 1) { // fuck ts if (prev.多平台) { prev.多平台++ } else { prev.多平台 = 1 } return prev } const target = platform[0] if (prev[target]) { prev[target]++ } else { prev[target] = 1 } return prev }, {})) // 奖杯种类 statsInfo.trophyNumber = mapObj(earnedTrophyList.reduce((prev, curr) => { const { type } = curr if (prev[type]) { prev[type]++ } else { prev[type] = 1 } return prev }, { '白金': 0, '金': 0, '银': 0, '铜': 0 })) // 点数 statsInfo.trophyPoints = mapObj(earnedTrophyList.reduce((prev, curr) => { const { point, type } = curr if (!type) { return prev } if (prev[type]) { prev[type] += point } else { prev[type] = point } return prev }, { '白金': 0, '金': 0, '银': 0, '铜': 0 })) // 奖杯稀有率 statsInfo.trophyRarePercent = (earnedTrophyList.reduce((prev, curr) => { return prev + parseFloat(curr.rare) }, 0) / earnedTrophyList.length).toFixed(2) + '%' statsInfo.trophyRare = mapObj(earnedTrophyList.reduce((prev, curr) => { const { rare } = curr const num = parseFloat(rare) let type = '简单' switch (true) { case num === 0.1: type = '地狱' break case num <= 1: type = '噩梦' break case num <= 5: type = '困难' break case num <= 25: type = '普通' break case num <= 50: type = '一般' break } prev[type] += 1 return prev }, { '地狱': 0, '噩梦': 0, '困难': 0, '普通': 0, '一般': 0, '简单': 0 })).filter(item => item.value !== 0) // 游戏完成率 statsInfo.gameRarePercent = (earnedTrophyList.length / unearnedTrophyList.length).toFixed(2) + '%' statsInfo.gamePercent = mapObj(gameList.reduce((prev, curr) => { const num = new Function(`return ${curr.percent.replace('%', '/100')}`)() let type = '80%' switch (true) { case num <= 0.2: type = '0%' break case num <= 0.4: type = '20%' break case num <= 0.6: type = '40%' break case num <= 0.8: type = '60%' break } if (prev[type]) { prev[type] += 1 } else { prev[type] = 1 } return prev }, { '80%': 0, '60%': 0, '40%': 0, '20%': 0, '0%': 0 })).filter(item => item.value !== 0) // 游戏难度 const tempDiff = gameList.reduce((prev, curr) => { const type = curr.alert if (prev[type]) { prev[type] += 1 } else { prev[type] = 1 } return prev }, { '地狱': 0, '噩梦': 0, '困难': 0, '麻烦': 0, '普通': 0, '容易': 0, '极易': 0 }) statsInfo.gameDifficulty = mapObj({ '地狱': tempDiff.地狱, '噩梦': tempDiff.噩梦, '困难': tempDiff.困难, '麻烦': tempDiff.麻烦, '普通': tempDiff.普通, '容易': tempDiff.容易, '极易': tempDiff.极易 }) // 月活 statsInfo.monthTrophy = mapObjToLine(earnedTrophyList.reduce((prev, curr) => { if (!curr.timestamp) return prev const date = new Date(curr.timestamp) const month = (date.getUTCMonth() + 1) const str = date.getUTCFullYear() + '-' + (month < 10 ? '0' + month : month) if (prev[str]) { prev[str] += 1 } else { prev[str] = 1 } return prev }, {})).sort((a: any, b: any) => a.time - b.time) // 日活 const tempAllMinute = {} const tempDayTrophy = mapObjToMultiLine(earnedTrophyList.reverse().reduce((prev, curr) => { if (!curr.timestamp) return prev const date = new Date(curr.timestamp) const month = (date.getUTCMonth() + 1) const day = date.getUTCDate() const str = date.getUTCFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) const hour = date.getHours() const minute = date.getMinutes() const tempAllMinuteStr = str + `:${hour}-${minute}` if (tempAllMinute[tempAllMinuteStr]) { tempAllMinute[tempAllMinuteStr]++ } else { tempAllMinute[tempAllMinuteStr] = 1 } const type = curr.type if (prev[str]) { prev[str][type]++ } else { prev[str] = { '白金': 0, '金': 0, '银': 0, '铜': 0 } prev[str][type]++ } return prev }, {})) const dayTrophyObj: any = { '白金': [], '金': [], '银': [], '铜': [] } statsInfo.minuteArr = Object.keys(tempAllMinute) statsInfo.dayArr = [] tempDayTrophy.forEach(item => { statsInfo.dayArr.push(item.label) dayTrophyObj.白金.push(item.value.白金) dayTrophyObj.金.push(item.value.金) dayTrophyObj.银.push(item.value.银) dayTrophyObj.铜.push(item.value.铜) }) statsInfo.dayTrophy = mapObjToLine(dayTrophyObj) const tempHour = earnedTrophyList.reduce((prev, curr) => { const date = new Date(curr.timestamp) const str = date.getUTCHours() // if (str === 6) console.log(curr.timestamp) if (prev[str]) { prev[str]++ } else { prev[str] = 1 } return prev }, {}) const hours = '0'.repeat(24).split('').map((_, i) => i.toString()) Object.keys(tempHour).forEach(item => { const index = hours.indexOf(item) if (index !== -1) hours.splice(index, 1) }) hours.forEach(str => { tempHour[str] = 0 }) statsInfo.hourTrophy = mapObj(tempHour).sort((a: any, b: any) => { return parseInt(a.label, 10) - parseInt(b.label, 10) }) let points = 0 statsInfo.levelTrophy = [] const tempWeek = earnedTrophyList.reverse().sort((a, b) => a.timestamp - b.timestamp).reduce((prev, curr) => { if (!curr.timestamp) return prev const date = new Date(curr.timestamp) const num = date.getDay() const str = weekdays[num] const { point } = curr let nextPoints = points + point const targetPoints = historyLevel[statsInfo.levelTrophy.length] const isBigger = targetPoints ? nextPoints >= targetPoints : nextPoints > 0 // console.log(nextPoints, points, targetPoints, isBigger, points <= targetPoints, isBigger && points <= targetPoints) if (isBigger && points <= targetPoints) { // console.log('hit level') statsInfo.levelTrophy.push(Object.assign({}, curr, { level: statsInfo.levelTrophy.length + 1 })) } points = nextPoints if (prev[str]) { prev[str]++ } else { prev[str] = 1 } return prev }, {}) statsInfo.levelTrophy = statsInfo.levelTrophy.reverse() const weekdaysTemp = weekdays.slice() Object.keys(tempWeek).forEach(item => { const index = weekdaysTemp.indexOf(item) // console.log(item, index, '===>') if (index !== -1) weekdaysTemp.splice(index, 1) }) // console.log(weekdaysTemp, '===> deleted') weekdaysTemp.forEach(str => { tempWeek[str] = 0 }) // console.log(tempWeek) statsInfo.weekTrophy = mapObj(tempWeek).sort((a: any, b: any) => { return weekdays.indexOf(a.label) - weekdays.indexOf(b.label) }) // 星期活跃度分布 const weekLoc = earnedTrophyList.reduce((prev, curr) => { if (!curr.timestamp) return prev const date = new Date(curr.timestamp) const num = date.getDay() // const day = weekdays[num] const hour = date.getUTCHours() const key = `${num}-${hour}` if (prev[key]) { prev[key]++ } else { prev[key] = 1 } return prev }, {}) const tempWeekLoc = Object.keys(weekLoc).map(item => { return { x: parseInt(item.split('-')[0] as string, 10), y: parseInt(item.split('-').pop() as string, 10), size: weekLoc[item], data: { y: parseInt(item.split('-').pop() as string, 10), size: weekLoc[item] } } }) const max = tempWeekLoc.reduce((prev, curr) => { // console.log(curr.size) if (curr.size > prev) return curr.size return prev }, 0) const div = (max / 100) > 1 ? (max / 100) : 1 statsInfo.weekLoc = tempWeekLoc.map(item => { return { ...item, size: ~~(item.size / div), data: { ...item.data, size: ~~(item.size / div), } } }) // console.log(statsInfo.weekLoc, div, max) // console.log(div, max) statsInfo.daysMapper = weekdays } const weekdays: any = [] weekdays[0] = '周天' weekdays[1] = '周一' weekdays[2] = '周二' weekdays[3] = '周三' weekdays[4] = '周四' weekdays[5] = '周五' weekdays[6] = '周六' function mapObjToLine(obj) { return Object.keys(obj).map(name => { const arr = name.split('-') return { label: name, y: obj[name], time: new Date(parseInt(arr[0], 10), parseInt(arr[1], 10)).valueOf() } }) } function mapObjToMultiLine(obj) { return Object.keys(obj).map(name => { const arr = name.split('-') return { label: name, value: obj[name], time: new Date( parseInt(arr[0], 10), parseInt(arr[1], 10), parseInt(arr[2], 10) ).valueOf() } }) } const historyLevel: any = [ 0, 200, 600, 1200, 2400, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 24000, 32000, 40000, 48000, 56000, 64000, 72000, 80000, 88000, 96000, 104000, 112000, 120000, 128000 ] for (let i = historyLevel.length; i < 100; i++) { const finalOne = historyLevel[historyLevel.length - 1] historyLevel.push(finalOne + 10000) } function sliceArrayByNumber(arr, num) { const result: any = [] for (let i = 0, len = arr.length; i < len; i += num) { result.push(arr.slice(i, i + num)) } return result }
the_stack
import { CancellationToken, CodeLens, CompletionContext, CompletionItem, CompletionList, DocumentSymbol, Hover, Location, LocationLink, Position, ProviderResult, ReferenceContext, SignatureHelp, SignatureHelpContext, SymbolInformation, TextDocument, WorkspaceEdit, } from 'vscode'; import * as vscodeLanguageClient from 'vscode-languageclient/node'; import { ILanguageServer, ILanguageServerConnection, ILanguageServerProxy } from '../activation/types'; import { ILanguageServerCapabilities } from './types'; /* * The Language Server Capabilities class implements the ILanguageServer interface to provide support for the existing Jupyter integration. */ export class LanguageServerCapabilities implements ILanguageServerCapabilities { serverProxy: ILanguageServerProxy | undefined; public dispose(): void { // Nothing to do here. } get(): Promise<ILanguageServer> { return Promise.resolve(this); } public get connection(): ILanguageServerConnection | undefined { const languageClient = this.getLanguageClient(); if (languageClient) { // Return an object that looks like a connection return { sendNotification: languageClient.sendNotification.bind(languageClient), sendRequest: languageClient.sendRequest.bind(languageClient), sendProgress: languageClient.sendProgress.bind(languageClient), onRequest: languageClient.onRequest.bind(languageClient), onNotification: languageClient.onNotification.bind(languageClient), onProgress: languageClient.onProgress.bind(languageClient), }; } return undefined; } public get capabilities(): vscodeLanguageClient.ServerCapabilities | undefined { const languageClient = this.getLanguageClient(); if (languageClient) { return languageClient.initializeResult?.capabilities; } return undefined; } public provideRenameEdits( document: TextDocument, position: Position, newName: string, token: CancellationToken, ): ProviderResult<WorkspaceEdit> { return this.handleProvideRenameEdits(document, position, newName, token); } public provideDefinition( document: TextDocument, position: Position, token: CancellationToken, ): ProviderResult<Location | Location[] | LocationLink[]> { return this.handleProvideDefinition(document, position, token); } public provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Hover> { return this.handleProvideHover(document, position, token); } public provideReferences( document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken, ): ProviderResult<Location[]> { return this.handleProvideReferences(document, position, context, token); } public provideCompletionItems( document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext, ): ProviderResult<CompletionItem[] | CompletionList> { return this.handleProvideCompletionItems(document, position, token, context); } public provideCodeLenses(document: TextDocument, token: CancellationToken): ProviderResult<CodeLens[]> { return this.handleProvideCodeLenses(document, token); } public provideDocumentSymbols( document: TextDocument, token: CancellationToken, ): ProviderResult<SymbolInformation[] | DocumentSymbol[]> { return this.handleProvideDocumentSymbols(document, token); } public provideSignatureHelp( document: TextDocument, position: Position, token: CancellationToken, context: SignatureHelpContext, ): ProviderResult<SignatureHelp> { return this.handleProvideSignatureHelp(document, position, token, context); } protected getLanguageClient(): vscodeLanguageClient.LanguageClient | undefined { return this.serverProxy?.languageClient; } private async handleProvideRenameEdits( document: TextDocument, position: Position, newName: string, token: CancellationToken, ): Promise<WorkspaceEdit | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args: vscodeLanguageClient.RenameParams = { textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document), position: languageClient.code2ProtocolConverter.asPosition(position), newName, }; const result = await languageClient.sendRequest(vscodeLanguageClient.RenameRequest.type, args, token); if (result) { return languageClient.protocol2CodeConverter.asWorkspaceEdit(result); } } return undefined; } private async handleProvideDefinition( document: TextDocument, position: Position, token: CancellationToken, ): Promise<Location | Location[] | LocationLink[] | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args: vscodeLanguageClient.TextDocumentPositionParams = { textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document), position: languageClient.code2ProtocolConverter.asPosition(position), }; const result = await languageClient.sendRequest(vscodeLanguageClient.DefinitionRequest.type, args, token); if (result) { return languageClient.protocol2CodeConverter.asDefinitionResult(result); } } return undefined; } private async handleProvideHover( document: TextDocument, position: Position, token: CancellationToken, ): Promise<Hover | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args: vscodeLanguageClient.TextDocumentPositionParams = { textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document), position: languageClient.code2ProtocolConverter.asPosition(position), }; const result = await languageClient.sendRequest(vscodeLanguageClient.HoverRequest.type, args, token); if (result) { return languageClient.protocol2CodeConverter.asHover(result); } } return undefined; } private async handleProvideReferences( document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken, ): Promise<Location[] | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args: vscodeLanguageClient.ReferenceParams = { textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document), position: languageClient.code2ProtocolConverter.asPosition(position), context, }; const result = await languageClient.sendRequest(vscodeLanguageClient.ReferencesRequest.type, args, token); if (result) { // Remove undefined part. return result.map((l) => { const r = languageClient!.protocol2CodeConverter.asLocation(l); return r!; }); } } return undefined; } private async handleProvideCodeLenses( document: TextDocument, token: CancellationToken, ): Promise<CodeLens[] | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args: vscodeLanguageClient.CodeLensParams = { textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document), }; const result = await languageClient.sendRequest(vscodeLanguageClient.CodeLensRequest.type, args, token); if (result) { return languageClient.protocol2CodeConverter.asCodeLenses(result); } } return undefined; } private async handleProvideCompletionItems( document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext, ): Promise<CompletionItem[] | CompletionList | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args = languageClient.code2ProtocolConverter.asCompletionParams(document, position, context); const result = await languageClient.sendRequest(vscodeLanguageClient.CompletionRequest.type, args, token); if (result) { return languageClient.protocol2CodeConverter.asCompletionResult(result); } } return undefined; } private async handleProvideDocumentSymbols( document: TextDocument, token: CancellationToken, ): Promise<SymbolInformation[] | DocumentSymbol[] | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args: vscodeLanguageClient.DocumentSymbolParams = { textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document), }; const result = await languageClient.sendRequest( vscodeLanguageClient.DocumentSymbolRequest.type, args, token, ); if (result && result.length) { if ((result[0] as DocumentSymbol).range) { // Document symbols const docSymbols = result as vscodeLanguageClient.DocumentSymbol[]; return languageClient.protocol2CodeConverter.asDocumentSymbols(docSymbols); } // Document symbols const symbols = result as vscodeLanguageClient.SymbolInformation[]; return languageClient.protocol2CodeConverter.asSymbolInformations(symbols); } } return undefined; } private async handleProvideSignatureHelp( document: TextDocument, position: Position, token: CancellationToken, _context: SignatureHelpContext, ): Promise<SignatureHelp | undefined> { const languageClient = this.getLanguageClient(); if (languageClient) { const args: vscodeLanguageClient.TextDocumentPositionParams = { textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document), position: languageClient.code2ProtocolConverter.asPosition(position), }; const result = await languageClient.sendRequest( vscodeLanguageClient.SignatureHelpRequest.type, args, token, ); if (result) { return languageClient.protocol2CodeConverter.asSignatureHelp(result); } } return undefined; } }
the_stack
import { analyzeMovesBase, getMoveObjects, getDepots, safeCheck, safeAdd, safeSubtract } from '../library'; import { reducerWithInitialState } from "typescript-fsa-reducers"; import { BasedState, AnalyzedBaseData } from '../types'; import { addMinutes, setViewport, setDefaultViewport, setTimeStamp, setTime, increaseTime, decreaseTime, setLeading, setTrailing, setFrameTimestamp, setMovesBase, setDepotsBase, setAnimatePause, setAnimateReverse, setSecPerHour, setMultiplySpeed, setClicked, setRoutePaths, setDefaultPitch, setMovesOptionFunc, setDepotsOptionFunc, setExtractedDataFunc, setLinemapData, setLoading, setInputFilename, updateMovesBase, setNoLoop, setInitialViewChange, setIconGradationChange, setTimeBegin, setTimeLength, addMovesBaseData} from '../actions'; interface InnerState extends Partial<BasedState>{}; const initialState: BasedState = { viewport: { longitude: 136.906428, latitude: 35.181453, zoom: 11.1, maxZoom: 18, minZoom: 5, pitch: 30, bearing: 0, maxPitch: undefined, minPitch: undefined, width: window.innerWidth, // 共通 height: window.innerHeight, // 共通 transitionDuration: 0, transitionInterpolator: undefined, transitionInterruption: undefined, }, settime: 0, starttimestamp: 0, timeLength: 0, timeBegin: 0, loopTime: 0, leading: 100, trailing: 180, beforeFrameTimestamp: 0, movesbase: [], depotsBase: [], bounds: { westlongitiude: 0, eastlongitiude: 0, southlatitude: 0, northlatitude: 0 }, animatePause: false, loopEndPause: false, animateReverse: false, secperhour: 180, multiplySpeed:20, //(3600 / secperhour)値であること clickedObject: null, routePaths: [], defaultZoom: 11.1, defaultPitch: 30, getMovesOptionFunc: null, getDepotsOptionFunc: null, movedData: [], ExtractedData: undefined, getExtractedDataFunc: null, depotsData: [], linemapData: [], loading: false, inputFileName: {}, noLoop: false, initialViewChange: true, iconGradation: false }; const parameter = { coefficient: 0 }; const calcLoopTime = // LoopTime とは1ループにかける時間(ミリ秒) (timeLength : number, secperhour: number) : number => (timeLength / 3.6) * secperhour; const reducer = reducerWithInitialState<BasedState>(initialState); const assign = Object.assign; reducer.case(addMinutes, (state, min) => { const assignData:InnerState = {}; assignData.loopEndPause = false; assignData.settime = safeAdd(state.settime, (min * 60)); if (assignData.settime < safeSubtract(state.timeBegin, state.leading)) { assignData.settime = safeSubtract(state.timeBegin, state.leading); } if (assignData.settime > (state.timeBegin + state.timeLength)) { assignData.settime = (state.timeBegin + state.timeLength); } assignData.starttimestamp = Date.now() - (((assignData.settime - state.timeBegin) / state.timeLength) * state.loopTime); return assign({}, state, assignData); }); reducer.case(setViewport, (state, view) => { const viewport = assign({}, state.viewport, view); return assign({}, state, { viewport }); }); reducer.case(setDefaultViewport, (state, defViewport:{defaultZoom?:number,defaultPitch?:number}={}) => { const {defaultZoom,defaultPitch} = defViewport; const zoom = defaultZoom === undefined ? state.defaultZoom : defaultZoom; const pitch = defaultPitch === undefined ? state.defaultPitch : defaultPitch; const viewport = assign({}, state.viewport, { bearing:0, zoom, pitch }); return assign({}, state, { viewport, defaultZoom:zoom, defaultPitch:pitch }); }); reducer.case(setTimeStamp, (state, props) => { const starttimestamp = (Date.now() + calcLoopTime(state.leading, state.secperhour)); return assign({}, state, { starttimestamp, loopEndPause:false }); }); reducer.case(setTime, (state, settime) => { const starttimestamp = Date.now() - ((safeSubtract(settime, state.timeBegin) / state.timeLength) * state.loopTime); return assign({}, state, { settime, starttimestamp, loopEndPause:false }); }); reducer.case(increaseTime, (state, props) => { const assignData:InnerState = {}; const now = Date.now(); const difference = now - state.starttimestamp; if(state.noLoop){ const margins = calcLoopTime(state.leading + state.trailing, state.secperhour); if(difference >= (state.loopTime - margins)){ return assign({}, state, {loopEndPause:true}); } } if (difference >= state.loopTime) { console.log('settime overlap.'); assignData.settime = safeSubtract(state.timeBegin, state.leading); assignData.starttimestamp = now - ((safeSubtract(assignData.settime, state.timeBegin) / state.timeLength) * state.loopTime); const setProps = { ...props, ...assignData }; const {movedData,ExtractedData} = getMoveObjects(setProps); if(movedData){ assignData.movedData = movedData; if(assignData.movedData.length === 0){ assignData.clickedObject = null; assignData.routePaths = []; } } assignData.ExtractedData = ExtractedData; if(state.depotsBase.length <= 0 || state.depotsData.length <= 0 || state.getDepotsOptionFunc){ const depotsData = getDepots(setProps) if(depotsData){ assignData.depotsData = depotsData; } } return assign({}, state, assignData); }else{ // assignData.settime = ((difference / state.loopTime) * state.timeLength) + state.timeBegin; assignData.settime = safeAdd((difference * parameter.coefficient), state.timeBegin); } if (state.settime > assignData.settime) { console.log(`${state.settime} ${assignData.settime}`); } assignData.beforeFrameTimestamp = now; const setProps = { ...props, ...assignData }; const {movedData,ExtractedData} = getMoveObjects(setProps); if(movedData){ assignData.movedData = movedData; if(assignData.movedData.length === 0){ assignData.clickedObject = null; assignData.routePaths = []; } } assignData.ExtractedData = ExtractedData; if(state.depotsBase.length <= 0 || state.depotsData.length <= 0 || state.getDepotsOptionFunc){ const depotsData = getDepots(setProps) if(depotsData){ assignData.depotsData = depotsData; } } return assign({}, state, assignData); }); reducer.case(decreaseTime, (state, props) => { const now = Date.now(); const beforeFrameElapsed = now - state.beforeFrameTimestamp; const assignData:InnerState = {}; assignData.starttimestamp = state.starttimestamp + (beforeFrameElapsed << 1); assignData.settime = safeAdd(((now - state.starttimestamp) % state.loopTime) * parameter.coefficient, state.timeBegin); if (assignData.settime <= safeSubtract(state.timeBegin, state.leading)) { if(state.noLoop){ return assign({}, state, {loopEndPause:true}); } assignData.settime = safeAdd(state.timeBegin, state.timeLength); assignData.starttimestamp = now - ((safeSubtract(assignData.settime, state.timeBegin) / state.timeLength) * state.loopTime); } assignData.beforeFrameTimestamp = now; const setProps = { ...props, ...assignData }; const {movedData,ExtractedData} = getMoveObjects(setProps); if(movedData){ assignData.movedData = movedData; if(assignData.movedData.length === 0){ assignData.clickedObject = null; assignData.routePaths = []; } } assignData.ExtractedData = ExtractedData; if(state.depotsBase.length <= 0 || state.depotsData.length <= 0 || state.getDepotsOptionFunc){ const depotsData = getDepots(setProps) if(depotsData){ assignData.depotsData = depotsData; } } return assign({}, state, assignData); }); reducer.case(setLeading, (state, leading) => { safeCheck(leading); return assign({}, state, { leading }); }); reducer.case(setTrailing, (state, trailing) => { safeCheck(trailing); return assign({}, state, { trailing }); }); reducer.case(setFrameTimestamp, (state, props) => { const assignData:InnerState = {}; const now = Date.now(); assignData.beforeFrameTimestamp = now; assignData.starttimestamp = now - ((safeSubtract(state.settime, state.timeBegin) / state.timeLength) * state.loopTime); const setProps = { ...props, ...assignData }; const {movedData,ExtractedData} = getMoveObjects(setProps); if(movedData){ assignData.movedData = movedData; if(assignData.movedData.length === 0){ assignData.clickedObject = null; assignData.routePaths = []; } } assignData.ExtractedData = ExtractedData; if(state.depotsBase.length <= 0 || state.depotsData.length <= 0 || state.getDepotsOptionFunc){ const depotsData = getDepots(setProps) if(depotsData){ assignData.depotsData = depotsData; } } return assign({}, state, assignData); }); const setMovesBaseFunc = (state:BasedState, analyzeData:AnalyzedBaseData):BasedState => { const assignData:InnerState = {}; assignData.loopEndPause = false; assignData.timeBegin = analyzeData.timeBegin; assignData.bounds = analyzeData.bounds; if(analyzeData.viewport && state.initialViewChange && analyzeData.movesbase.length > 0){ assignData.viewport = assign({}, state.viewport, {bearing:0, zoom:state.defaultZoom, pitch:state.defaultPitch}, analyzeData.viewport); } assignData.settime = safeSubtract(analyzeData.timeBegin, (analyzeData.movesbase.length === 0 ? 0 : state.leading)); if (analyzeData.timeLength > 0) { assignData.timeLength = safeAdd(analyzeData.timeLength, state.trailing); }else{ assignData.timeLength = analyzeData.timeLength; } assignData.loopTime = calcLoopTime(assignData.timeLength, state.secperhour); parameter.coefficient = assignData.timeLength / assignData.loopTime; // starttimestampはDate.now()の値でいいが、スタート時はleading分の余白時間を付加する assignData.starttimestamp = Date.now() + calcLoopTime(state.leading, state.secperhour); if(state.depotsBase.length <= 0 || state.depotsData.length <= 0 || state.getDepotsOptionFunc){ const depotsData = getDepots({ ...state, ...assignData }) if(depotsData){ assignData.depotsData = depotsData; } } assignData.movesbase = analyzeData.movesbase; assignData.movedData = []; console.log('setMovesBaseFunc'); return assign({}, state, assignData); }; reducer.case(setMovesBase, (state, base) => { const analyzeData:Readonly<AnalyzedBaseData> = analyzeMovesBase(state, base, false); return setMovesBaseFunc(state, analyzeData); }); reducer.case(setDepotsBase, (state, depotsBase) => { const assignData:InnerState = {}; assignData.depotsBase = depotsBase; if(state.depotsBase.length <= 0 || state.depotsData.length <= 0 || state.getDepotsOptionFunc){ const depotsData = getDepots({ ...state, depotsBase }) if(depotsData){ assignData.depotsData = depotsData; } } return assign({}, state, assignData); }); reducer.case(setAnimatePause, (state, animatePause) => { const assignData:InnerState = {}; assignData.animatePause = animatePause; assignData.loopEndPause = false; assignData.starttimestamp = (Date.now() - ((safeSubtract(state.settime, state.timeBegin) / state.timeLength) * state.loopTime)); return assign({}, state, assignData); }); reducer.case(setAnimateReverse, (state, animateReverse) => { return assign({}, state, { animateReverse, loopEndPause:false }); }); reducer.case(setSecPerHour, (state, secperhour) => { if(secperhour === 0){ console.log('secperhour set zero!'); return state; } const assignData:InnerState = {}; assignData.loopEndPause = false; assignData.secperhour = secperhour; assignData.multiplySpeed = 3600 / secperhour; assignData.loopTime = calcLoopTime(state.timeLength, secperhour); parameter.coefficient = state.timeLength / assignData.loopTime; if (!state.animatePause) { assignData.starttimestamp = (Date.now() - ((safeSubtract(state.settime, state.timeBegin) / state.timeLength) * assignData.loopTime)); } return assign({}, state, assignData); }); reducer.case(setMultiplySpeed, (state, multiplySpeed) => { if(multiplySpeed === 0){ console.log('secperhour set zero!'); return state; } const assignData:InnerState = {}; assignData.loopEndPause = false; assignData.multiplySpeed = multiplySpeed; assignData.secperhour = 3600 / multiplySpeed; assignData.loopTime = calcLoopTime(state.timeLength, assignData.secperhour); parameter.coefficient = state.timeLength / assignData.loopTime; if (!state.animatePause) { assignData.starttimestamp = (Date.now() - ((safeSubtract(state.settime, state.timeBegin) / state.timeLength) * assignData.loopTime)); } return assign({}, state, assignData); }); reducer.case(setClicked, (state, clickedObject) => { return assign({}, state, { clickedObject }); }); reducer.case(setRoutePaths, (state, routePaths) => { return assign({}, state, { routePaths }); }); reducer.case(setDefaultPitch, (state, defaultPitch) => { return assign({}, state, { defaultPitch }); }); reducer.case(setMovesOptionFunc, (state, getMovesOptionFunc) => { return assign({}, state, { getMovesOptionFunc }); }); reducer.case(setDepotsOptionFunc, (state, getDepotsOptionFunc) => { return assign({}, state, { getDepotsOptionFunc }); }); reducer.case(setExtractedDataFunc, (state, getExtractedDataFunc) => { return assign({}, state, { getExtractedDataFunc }); }); reducer.case(setLinemapData, (state, linemapData) => { return assign({}, state, { linemapData }); }); reducer.case(setLoading, (state, loading) => { return assign({}, state, { loading }); }); reducer.case(setInputFilename, (state, fileName) => { const inputFileName = assign({}, state.inputFileName, fileName); return assign({}, state, { inputFileName }); }); reducer.case(updateMovesBase, (state, base) => { const analyzeData:Readonly<AnalyzedBaseData> = analyzeMovesBase(state, base, true); if(state.movesbase.length === 0){ //初回? return setMovesBaseFunc(state, analyzeData); } const assignData:InnerState = {}; assignData.loopEndPause = false; assignData.movesbase = analyzeData.movesbase; const startState:InnerState = {}; startState.timeLength = analyzeData.timeLength; if (startState.timeLength > 0) { startState.timeLength = safeAdd(startState.timeLength, state.trailing); } if(analyzeData.timeBegin !== state.timeBegin || startState.timeLength !== state.timeLength){ startState.timeBegin = analyzeData.timeBegin; startState.loopTime = calcLoopTime(startState.timeLength, state.secperhour); parameter.coefficient = startState.timeLength / startState.loopTime; startState.starttimestamp = (Date.now() - ((safeSubtract(state.settime, startState.timeBegin) / startState.timeLength) * startState.loopTime)); return assign({}, state, startState, assignData); } return assign({}, state, assignData); }); reducer.case(setNoLoop, (state, noLoop) => { return assign({}, state, { noLoop, loopEndPause:false }); }); reducer.case(setInitialViewChange, (state, initialViewChange) => { return assign({}, state, { initialViewChange }); }); reducer.case(setIconGradationChange, (state, iconGradation) => { return assign({}, state, { iconGradation }); }); reducer.case(setTimeBegin, (state, timeBegin) => { safeCheck(timeBegin); const assignData:InnerState = {}; const movesbaselength = state.movesbase.length; if(movesbaselength > 0){ const firstDeparturetime = state.movesbase.reduce((acc,cur)=>Math.min(acc,cur.departuretime),Number.MAX_SAFE_INTEGER); if(firstDeparturetime >= timeBegin){ assignData.timeBegin = timeBegin; assignData.timeLength = safeAdd(state.timeLength, safeSubtract(state.timeBegin, assignData.timeBegin)); if(assignData.timeLength === 0){ assignData.settime = assignData.timeBegin; }else{ assignData.settime = state.settime; } assignData.loopTime = calcLoopTime(assignData.timeLength, state.secperhour); parameter.coefficient = assignData.timeLength / assignData.loopTime; assignData.starttimestamp = (Date.now() - ((safeSubtract(assignData.settime, assignData.timeBegin) / assignData.timeLength) * assignData.loopTime)); } }else{ if(state.timeLength === 0){ assignData.timeBegin = timeBegin; assignData.settime = assignData.timeBegin; assignData.starttimestamp = (Date.now() - ((safeSubtract(assignData.settime, assignData.timeBegin) / state.timeLength) * state.loopTime)); }else if((state.timeBegin + state.timeLength) >= timeBegin){ assignData.timeBegin = timeBegin; assignData.timeLength = safeAdd(state.timeLength, safeSubtract(state.timeBegin, assignData.timeBegin)); if(assignData.timeLength === 0){ assignData.settime = assignData.timeBegin; }else{ assignData.settime = state.settime; } assignData.loopTime = calcLoopTime(assignData.timeLength, state.secperhour); parameter.coefficient = assignData.timeLength / assignData.loopTime; assignData.starttimestamp = (Date.now() - ((safeSubtract(assignData.settime, assignData.timeBegin) / assignData.timeLength) * assignData.loopTime)); } } return assign({}, state, assignData); }); reducer.case(setTimeLength, (state, timeLength) => { safeCheck(timeLength); const assignData:InnerState = {}; const movesbaselength = state.movesbase.length; if(timeLength >= 0){ if(movesbaselength > 0){ if(timeLength >= state.trailing){ const lastArrivaltime = state.movesbase.reduce((acc,cur)=>Math.max(acc,cur.arrivaltime),state.timeBegin); if(safeSubtract(safeAdd(state.timeBegin, timeLength), state.trailing) >= lastArrivaltime){ assignData.timeLength = timeLength; if(assignData.timeLength === 0){ assignData.settime = state.timeBegin; }else{ assignData.settime = state.settime; } assignData.loopTime = calcLoopTime(assignData.timeLength, state.secperhour); parameter.coefficient = assignData.timeLength / assignData.loopTime; assignData.starttimestamp = (Date.now() - ((safeSubtract(assignData.settime, state.timeBegin) / assignData.timeLength) * assignData.loopTime)); } } }else{ assignData.timeLength = timeLength; if(assignData.timeLength === 0){ assignData.settime = state.timeBegin; }else{ assignData.settime = state.settime; } assignData.loopTime = calcLoopTime(assignData.timeLength, state.secperhour); parameter.coefficient = assignData.timeLength / assignData.loopTime; assignData.starttimestamp = (Date.now() - ((safeSubtract(assignData.settime, state.timeBegin) / assignData.timeLength) * assignData.loopTime)); } } return assign({}, state, assignData); }); reducer.case(addMovesBaseData, (state, movesbase) => { const movesbaseidxArray = movesbase.map(x=>x.movesbaseidx); const analyzeData:Readonly<AnalyzedBaseData> = analyzeMovesBase(state, movesbase, true); if(state.movesbase.length === 0){ //初回? return setMovesBaseFunc(state, analyzeData); } const assignData:InnerState = {}; assignData.loopEndPause = false; assignData.movesbase = [...state.movesbase]; for (let i = 0, lengthi = movesbaseidxArray.length; i < lengthi; i=(i+1)|0) { const movesbaseidx = movesbaseidxArray[i]; if(movesbaseidx !== undefined && movesbaseidx < state.movesbase.length){ assignData.movesbase[movesbaseidx] = analyzeData.movesbase[i]; assignData.movesbase[movesbaseidx].movesbaseidx = movesbaseidx; }else{ const addidx = assignData.movesbase.length; assignData.movesbase.push(analyzeData.movesbase[i]); assignData.movesbase[addidx].movesbaseidx = addidx; } } const startState:InnerState = {}; if(analyzeData.timeBegin < state.timeBegin){ startState.timeBegin = analyzeData.timeBegin; }else{ startState.timeBegin = state.timeBegin; } const analyzeEndTime = safeAdd(analyzeData.timeBegin, analyzeData.timeLength); const stateEndTime = safeAdd(state.timeBegin, state.timeLength); if(analyzeEndTime > stateEndTime){ startState.timeLength = safeSubtract(analyzeEndTime, startState.timeBegin); }else{ startState.timeLength = safeSubtract(stateEndTime, startState.timeBegin); } if(startState.timeBegin !== state.timeBegin || startState.timeLength !== state.timeLength){ startState.loopTime = calcLoopTime(startState.timeLength, state.secperhour); parameter.coefficient = startState.timeLength / startState.loopTime; startState.starttimestamp = (Date.now() - ((safeSubtract(state.settime, startState.timeBegin) / startState.timeLength) * startState.loopTime)); return assign({}, state, startState, assignData); } return assign({}, state, assignData); }); reducer.default((state) => state); export default reducer.build();
the_stack
import React, { Component } from 'react' import { StyleSheet, Text, View, Image, TouchableNativeFeedback, InteractionManager, ActivityIndicator, Animated, FlatList, Linking, TextInput, Button } from 'react-native' import Ionicons from 'react-native-vector-icons/Ionicons' import { standardColor, idColor } from '../../constant/colorConfig' import ComplexComment from '../../component/ComplexComment' import { getTrophyAPI } from '../../dao' import { translate } from '../../dao/post' let toolbarActions = [ { title: '回复', iconName: 'md-create', show: 'always', iconSize: 22 }, { title: '刷新', iconName: 'md-refresh', show: 'always' } ] declare var global class CommunityTopic extends Component<any, any> { constructor(props) { super(props) this.state = { data: false, isLoading: true, mainContent: false, title: '', content: '', rotation: new Animated.Value(1), scale: new Animated.Value(1), opacity: new Animated.Value(1), openVal: new Animated.Value(0), modalVisible: false, modalOpenVal: new Animated.Value(0), topicMarginTop: new Animated.Value(0) } } _onActionSelected = (index) => { const { params } = this.props.navigation.state switch (index) { case 0: if (this.isReplyShowing === true) return this.props.navigation.navigate('Reply', { type: params.type, id: params.rowData.id, callback: this.preFetch, isOldPage: this.state.data.isOldPage, shouldSeeBackground: true }) return case 1: this.preFetch() return } } componentWillMount() { this.preFetch() } preFetch = () => { this.setState({ isLoading: true }) const { params } = this.props.navigation.state InteractionManager.runAfterInteractions(() => { const data = getTrophyAPI(params.URL).then(data => { this.hasComment = data.commentList.length !== 0 this.setState({ data, commentList: data.commentList, isLoading: false }) }) }) } handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', { images: [ { url } ] }) shouldComponentUpdate = (nextProp, nextState) => { return true } renderHeader = (rowData) => { const { modeInfo } = this.props.screenProps return ( <TouchableNativeFeedback onPress={() => { if (rowData.url) { this.props.navigation.navigate('GamePage', { // URL: 'https://psnine.com/psngame/5424?psnid=Smallpath', URL: rowData.url, title: rowData.title, rowData, type: 'game' }) } }} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View style={{ flex: -1, flexDirection: 'row', padding: 12, backgroundColor: modeInfo.backgroundColor, elevation: 2, height: 74 }}> <Image source={{ uri: rowData.avatar }} style={[styles.avatar, { width: 54, height: 54 }]} /> <View style={{ marginLeft: 10, flex: 1, flexDirection: 'column' }}> <Text style={{ flex: 1, color: modeInfo.titleTextColor }}> {rowData.title} </Text> <Text selectable={false} numberOfLines={1} style={{ flex: -1, color: modeInfo.standardTextColor}}>{rowData.text}</Text> </View> <View style={{justifyContent: 'center', alignItems: 'center'}}> <Text onPress={() => { this.setState({ modalVisible: true }) }} style={{ backgroundColor: '#f2c230', color: modeInfo.reverseModeInfo.titleTextColor, padding: 5, paddingHorizontal: 8}}>翻译</Text> </View> </View> </TouchableNativeFeedback> ) } renderGame = (rowData) => { const { modeInfo } = this.props.screenProps return ( <View style={{ backgroundColor: modeInfo.backgroundColor, elevation: 1, margin: 5, marginTop: 0 }}> <TouchableNativeFeedback onPress={() => { }} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12 }}> <Image source={{ uri: rowData.avatar }} style={[styles.avatar, { width: 91 }]} /> <View style={{ marginLeft: 10, flex: 1, flexDirection: 'column' }}> <Text ellipsizeMode={'tail'} numberOfLines={3} style={{ flex: 2.5, color: modeInfo.titleTextColor }}> {rowData.title} </Text> <View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}> <Text selectable={false} style={{ flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' }}>{rowData.platform.join(' ')}</Text> </View> </View> </View> </TouchableNativeFeedback> </View> ) } hasComment = false isReplyShowing = false renderComment = (rowData, index) => { const { modeInfo } = this.props.screenProps const { navigation } = this.props const { preFetch } = this return (<ComplexComment key={rowData.id || index} {...{ navigation, modeInfo, onLongPress: () => {}, preFetch, rowData }}/>) } focusNextField = (nextField) => { this[nextField] && this[nextField].focus() } submit = () => { const { params } = this.props.navigation.state const tid = (params.URL || '').split('/').pop() translate({ title: this.state.title, detail: this.state.content, tid, cn: '' }).then(res => res.text()).then(html => { if (html.includes('玩脱了')) { const arr = html.match(/\<title\>(.*?)\<\/title\>/) if (arr && arr[1]) { const msg = `翻译失败: ${arr[1]}` global.toast(msg) return } } global.toast('翻译成功') this.setState({ modalVisible: false }) this.preFetch() }).catch(err => global.toast('翻译失败: ' + err.toString())) } viewTopIndex = 0 viewBottomIndex = 0 render() { const { params } = this.props.navigation.state const { modeInfo } = this.props.screenProps const { data: source } = this.state const data: any[] = [] const renderFuncArr: any[] = [] const shouldPushData = !this.state.isLoading // if (shouldPushData) { // data.push(source.trophyInfo) // renderFuncArr.push(this.renderHeader) // data.push(source.gameInfo) // renderFuncArr.push(this.renderGame) // } if (shouldPushData && this.hasComment) { renderFuncArr.push(this.renderComment) } this.viewBottomIndex = Math.max(data.length - 1, 0) return ( <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }} onStartShouldSetResponder={() => false} onMoveShouldSetResponder={() => false} > <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={`${params.title}`} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} style={[styles.toolbar, { backgroundColor: modeInfo.standardColor }]} actions={toolbarActions} onIconClicked={() => { this.props.navigation.goBack() }} onActionSelected={this._onActionSelected} /> {this.state.isLoading && ( <ActivityIndicator animating={this.state.isLoading} style={{ flex: 999, justifyContent: 'center', alignItems: 'center' }} color={modeInfo.accentColor} size={50} /> )} {!this.state.isLoading && this.renderHeader(source.trophyInfo)} {!this.state.isLoading && <FlatList style={{ flex: -1, backgroundColor: modeInfo.standardColor }} ref={flatlist => this.flatlist = flatlist} data={this.state.commentList} keyExtractor={(item, index) => item.id || index} renderItem={({ item, index }) => { return this.renderComment(item, index) }} extraData={this.state} windowSize={999} disableVirtualization={true} viewabilityConfig={{ minimumViewTime: 3000, viewAreaCoveragePercentThreshold: 100, waitForInteraction: true }} > </FlatList> } { this.state.modalVisible && ( <global.MyDialog modeInfo={this.props.modeInfo} modalVisible={this.state.modalVisible} onDismiss={() => this.setState({modalVisible: false})} onRequestClose={() => this.setState({modalVisible: false})} renderContent={() => ( <View style={{ justifyContent: 'center', alignItems: 'center', backgroundColor: modeInfo.backgroundColor, paddingVertical: 20, paddingHorizontal: 20, position: 'absolute', left: 30, right: 30, elevation: 4, opacity: 1, borderRadius: 2 }} > <Text style={{color: modeInfo.standardTextColor}}>为了更好的帮助他人,奖杯翻译请严格遵循 <Text style={{color: modeInfo.accentColor}} onPress={() => this.setState({ modalVisible: false}, () => Linking.openURL('p9://psnine.com/topic/1317'))}>「翻译」使用全指南</Text></Text> <View style={{ flexDirection: 'row'}}> <TextInput placeholder='奖杯标题(对奖杯标题文字的翻译)' autoCorrect={false} multiline={false} keyboardType='default' returnKeyType='go' returnKeyLabel='go' blurOnSubmit={true} numberOfLines={1} ref={ref => this.title = ref} onSubmitEditing={() => this.focusNextField('content')} onChange={({ nativeEvent }) => { this.setState({ title: nativeEvent.text }) }} value={this.state.title} style={[{ color: modeInfo.titleTextColor, textAlign: 'left', textAlignVertical: 'center', flex: 1, backgroundColor: modeInfo.brighterLevelOne, marginBottom: 2 }]} placeholderTextColor={modeInfo.standardTextColor} // underlineColorAndroid={accentColor} underlineColorAndroid='rgba(0,0,0,0)' /> </View> <View style={{flexDirection: 'row'}}> <TextInput placeholder='奖杯说明(不是奖杯攻略,是对奖杯说明文字的翻译)' autoCorrect={false} multiline={true} keyboardType='default' blurOnSubmit={true} numberOfLines={4} ref={ref => this.content = ref} onChange={({ nativeEvent }) => { this.setState({ content: nativeEvent.text }) }} value={this.state.content} style={[{ color: modeInfo.titleTextColor, flex: 2, marginBottom: 2, backgroundColor: modeInfo.brighterLevelOne }]} placeholderTextColor={modeInfo.standardTextColor} // underlineColorAndroid={accentColor} underlineColorAndroid='rgba(0,0,0,0)' /> </View> <Button title='提交' onPress={() => this.submit()} color={modeInfo.standardColor}/> </View> )} /> )} </View> ) } isValueChanged = false content: any = false refreshControl: any = false flatlist: any = false ref: any = false title: any = false } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#F5FCFF' }, toolbar: { backgroundColor: standardColor, height: 56, elevation: 4 }, selectedTitle: { // backgroundColor: '#00ffff' // fontSize: 20 }, avatar: { width: 50, height: 50 }, a: { fontWeight: '300', color: idColor // make links coloured pink } }) export default CommunityTopic
the_stack
import {createRange, Log, Source, SourceRange} from "../../utils/log"; import {assert} from "../../utils/assert"; /** * Author: Nidin Vinayakan */ export enum TokenKind { END_OF_FILE, // Literals CHARACTER, IDENTIFIER, INT32, INT64, FLOAT32, FLOAT64, STRING, ARRAY, // Punctuation ASSIGN, BITWISE_AND, BITWISE_OR, BITWISE_XOR, COLON, COMMA, COMPLEMENT, DIVIDE, DOT, EQUAL, EXPONENT, GREATER_THAN, GREATER_THAN_EQUAL, LEFT_BRACE, LEFT_BRACKET, LEFT_PARENTHESIS, LESS_THAN, LESS_THAN_EQUAL, LOGICAL_AND, LOGICAL_OR, MINUS, MINUS_MINUS, MULTIPLY, NOT, NOT_EQUAL, PLUS, PLUS_PLUS, QUESTION_MARK, REMAINDER, RIGHT_BRACE, RIGHT_BRACKET, RIGHT_PARENTHESIS, SEMICOLON, FROM, SHIFT_LEFT, SHIFT_RIGHT, // Keywords ALIGNOF, AS, BREAK, MODULE, CLASS, CONST, CONTINUE, DECLARE, ELSE, ENUM, EXPORT, EXTENDS, FALSE, FUNCTION, ANYFUNC, IF, IMPLEMENTS, IMPORT, LET, NEW, DELETE, NULL, UNDEFINED, OPERATOR, PRIVATE, PROTECTED, PUBLIC, RETURN, SIZEOF, STATIC, THIS, TRUE, UNSAFE, JAVASCRIPT, START, VIRTUAL, VAR, WHILE, FOR, // Preprocessor PREPROCESSOR_DEFINE, PREPROCESSOR_ELIF, PREPROCESSOR_ELSE, PREPROCESSOR_ENDIF, PREPROCESSOR_ERROR, PREPROCESSOR_IF, PREPROCESSOR_NEEDED, PREPROCESSOR_NEWLINE, PREPROCESSOR_UNDEF, PREPROCESSOR_WARNING, } export function isKeyword(kind: TokenKind): boolean { return kind >= TokenKind.ALIGNOF && kind <= TokenKind.WHILE; } export class Token { kind: TokenKind; range: SourceRange; next: Token; } export function splitToken(first: Token, firstKind: TokenKind, secondKind: TokenKind): void { var range = first.range; assert(range.end - range.start >= 2); var second = new Token(); second.kind = secondKind; second.range = createRange(range.source, range.start + 1, range.end); second.next = first.next; first.kind = firstKind; first.next = second; range.end = range.start + 1; } export function tokenToString(token: TokenKind): string { if (token == TokenKind.END_OF_FILE) return "end of file"; // Literals if (token == TokenKind.CHARACTER) return "character literal"; if (token == TokenKind.IDENTIFIER) return "identifier"; if (token == TokenKind.INT32) return "integer32 literal"; if (token == TokenKind.INT64) return "integer64 literal"; if (token == TokenKind.FLOAT32) return "float32 literal"; if (token == TokenKind.FLOAT64) return "float64 literal"; if (token == TokenKind.STRING) return "string literal"; if (token == TokenKind.ARRAY) return "array literal"; // Punctuation if (token == TokenKind.ASSIGN) return "'='"; if (token == TokenKind.BITWISE_AND) return "'&'"; if (token == TokenKind.BITWISE_OR) return "'|'"; if (token == TokenKind.BITWISE_XOR) return "'^'"; if (token == TokenKind.COLON) return "':'"; if (token == TokenKind.COMMA) return "','"; if (token == TokenKind.COMPLEMENT) return "'~'"; if (token == TokenKind.DIVIDE) return "'/'"; if (token == TokenKind.DOT) return "'.'"; if (token == TokenKind.EQUAL) return "'=='"; if (token == TokenKind.EXPONENT) return "'**'"; if (token == TokenKind.GREATER_THAN) return "'>'"; if (token == TokenKind.GREATER_THAN_EQUAL) return "'>='"; if (token == TokenKind.LEFT_BRACE) return "'{'"; if (token == TokenKind.LEFT_BRACKET) return "'['"; if (token == TokenKind.LEFT_PARENTHESIS) return "'('"; if (token == TokenKind.LESS_THAN) return "'<'"; if (token == TokenKind.LESS_THAN_EQUAL) return "'<='"; if (token == TokenKind.LOGICAL_AND) return "'&&'"; if (token == TokenKind.LOGICAL_OR) return "'||'"; if (token == TokenKind.MINUS) return "'-'"; if (token == TokenKind.MINUS_MINUS) return "'--'"; if (token == TokenKind.MULTIPLY) return "'*'"; if (token == TokenKind.NOT) return "'!'"; if (token == TokenKind.NOT_EQUAL) return "'!='"; if (token == TokenKind.PLUS) return "'+'"; if (token == TokenKind.PLUS_PLUS) return "'++'"; if (token == TokenKind.QUESTION_MARK) return "'?'"; if (token == TokenKind.REMAINDER) return "'%'"; if (token == TokenKind.RIGHT_BRACE) return "'}'"; if (token == TokenKind.RIGHT_BRACKET) return "']'"; if (token == TokenKind.RIGHT_PARENTHESIS) return "')'"; if (token == TokenKind.SEMICOLON) return "';'"; if (token == TokenKind.SHIFT_LEFT) return "'<<'"; if (token == TokenKind.SHIFT_RIGHT) return "'>>'"; // Keywords if (token == TokenKind.FROM) return "'from'"; if (token == TokenKind.ALIGNOF) return "'alignof'"; if (token == TokenKind.AS) return "'as'"; if (token == TokenKind.BREAK) return "'break'"; if (token == TokenKind.MODULE) return "'namespace'"; if (token == TokenKind.CLASS) return "'class'"; if (token == TokenKind.CONST) return "'const'"; if (token == TokenKind.CONTINUE) return "'continue'"; if (token == TokenKind.DECLARE) return "'declare'"; if (token == TokenKind.ELSE) return "'else'"; if (token == TokenKind.ENUM) return "'enum'"; if (token == TokenKind.EXPORT) return "'export'"; if (token == TokenKind.EXTENDS) return "'extends'"; if (token == TokenKind.FALSE) return "'false'"; if (token == TokenKind.FUNCTION) return "'function'"; if (token == TokenKind.ANYFUNC) return "'anyfunc'"; if (token == TokenKind.IF) return "'if'"; if (token == TokenKind.IMPLEMENTS) return "'implements'"; if (token == TokenKind.IMPORT) return "'import'"; if (token == TokenKind.LET) return "'let'"; if (token == TokenKind.NEW) return "'new'"; if (token == TokenKind.DELETE) return "'delete'"; if (token == TokenKind.NULL) return "'null'"; if (token == TokenKind.UNDEFINED) return "'undefined'"; if (token == TokenKind.OPERATOR) return "'operator'"; if (token == TokenKind.PRIVATE) return "'private'"; if (token == TokenKind.PROTECTED) return "'protected'"; if (token == TokenKind.PUBLIC) return "'public'"; if (token == TokenKind.RETURN) return "'return'"; if (token == TokenKind.SIZEOF) return "'sizeof'"; if (token == TokenKind.STATIC) return "'static'"; if (token == TokenKind.THIS) return "'this'"; if (token == TokenKind.TRUE) return "'true'"; if (token == TokenKind.UNSAFE) return "'unsafe'"; if (token == TokenKind.JAVASCRIPT) return "'@JS'"; if (token == TokenKind.START) return "'@start'"; if (token == TokenKind.VIRTUAL) return "'@virtual'"; if (token == TokenKind.VAR) return "'var'"; if (token == TokenKind.WHILE) return "'while'"; if (token == TokenKind.FOR) return "'for'"; // Preprocessor if (token == TokenKind.PREPROCESSOR_DEFINE) return "'#define'"; if (token == TokenKind.PREPROCESSOR_ELIF) return "'#elif'"; if (token == TokenKind.PREPROCESSOR_ELSE) return "'#else'"; if (token == TokenKind.PREPROCESSOR_ENDIF) return "'#endif'"; if (token == TokenKind.PREPROCESSOR_ERROR) return "'#error'"; if (token == TokenKind.PREPROCESSOR_IF) return "'#if'"; if (token == TokenKind.PREPROCESSOR_NEWLINE) return "newline"; if (token == TokenKind.PREPROCESSOR_UNDEF) return "'#undef'"; if (token == TokenKind.PREPROCESSOR_WARNING) return "'#warning'"; assert(false); return null; } export function isAlpha(c: string): boolean { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_'; } export function isASCII(c: uint16): boolean { return c >= 0x20 && c <= 0x7E; } export function isNumber(c: string): boolean { return c >= '0' && c <= '9'; } export function isDigit(c: any, base: uint8): boolean { if (c.trim() == "") return false; if (base == 16) { return isNumber(c) || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f'; } //return c >= '0' && c < '0' + base; return !isNaN(c); } export function tokenize(source: Source, log: Log): Token { var first: Token = null; var last: Token = null; var contents = source.contents; var limit = contents.length; var needsPreprocessor = false; var wantNewline = false; var i = 0; while (i < limit) { var start = i; var c = contents[i]; i = i + 1; if (c == ' ' || c == '\t' || c == '\r') { continue; } var kind = TokenKind.END_OF_FILE; // Newline if (c == '\n') { if (!wantNewline) { continue; } // Preprocessor commands all end in a newline kind = TokenKind.PREPROCESSOR_NEWLINE; wantNewline = false; } // Identifier else if (isAlpha(c) || c == "@") { kind = TokenKind.IDENTIFIER; while (i < limit && (isAlpha(contents[i]) || isNumber(contents[i]))) { i = i + 1; } // Keywords var length = i - start; if (length >= 2 && length <= 10) { var text = contents.slice(start, i); if (length == 2) { if (text == "as") kind = TokenKind.AS; else if (text == "if") kind = TokenKind.IF; } else if (length == 3) { if (text == "let") kind = TokenKind.LET; else if (text == "new") kind = TokenKind.NEW; else if (text == "var") kind = TokenKind.VAR; else if (text == "for") kind = TokenKind.FOR; else if (text == "@JS") kind = TokenKind.JAVASCRIPT; } else if (length == 4) { if (text == "else") kind = TokenKind.ELSE; else if (text == "enum") kind = TokenKind.ENUM; else if (text == "null") kind = TokenKind.NULL; else if (text == "this") kind = TokenKind.THIS; else if (text == "true") kind = TokenKind.TRUE; else if (text == "from") kind = TokenKind.FROM; } else if (length == 5) { if (text == "break") kind = TokenKind.BREAK; else if (text == "class") kind = TokenKind.CLASS; else if (text == "const") kind = TokenKind.CONST; else if (text == "false") kind = TokenKind.FALSE; else if (text == "while") kind = TokenKind.WHILE; } else if (length == 6) { if (text == "export") kind = TokenKind.EXPORT; else if (text == "module") kind = TokenKind.MODULE; else if (text == "import") kind = TokenKind.IMPORT; else if (text == "public") kind = TokenKind.PUBLIC; else if (text == "return") kind = TokenKind.RETURN; else if (text == "sizeof") kind = TokenKind.SIZEOF; else if (text == "static") kind = TokenKind.STATIC; else if (text == "unsafe") kind = TokenKind.UNSAFE; else if (text == "@start") kind = TokenKind.START; else if (text == "delete") kind = TokenKind.DELETE; } else if (length == 7) { if (text == "alignof") kind = TokenKind.ALIGNOF; else if (text == "declare") kind = TokenKind.DECLARE; else if (text == "extends") kind = TokenKind.EXTENDS; else if (text == "private") kind = TokenKind.PRIVATE; else if (text == "anyfunc") kind = TokenKind.ANYFUNC; } else { if (text == "continue") kind = TokenKind.CONTINUE; else if (text == "@virtual") kind = TokenKind.VIRTUAL; else if (text == "function") kind = TokenKind.FUNCTION; else if (text == "implements") kind = TokenKind.IMPLEMENTS; else if (text == "protected") kind = TokenKind.PROTECTED; } } } // Integer or Float else if (isNumber(c)) { let isFloat: boolean = false; let isDouble: boolean = false; //kind = TokenKind.INT32; if (i < limit) { var next = contents[i]; var base: uint8 = 10; // Handle binary, octal, and hexadecimal prefixes if (c == '0' && i + 1 < limit) { if (next == 'b' || next == 'B') base = 2; else if (next == 'o' || next == 'O') base = 8; else if (next == 'x' || next == 'X') base = 16; if (base != 10) { if (isDigit(contents[i + 1], base)) i = i + 2; else base = 10; } } let floatFound: boolean = false; let exponentFound: boolean = false; // Scan the payload while (i < limit && (isDigit(contents[i], base) || (exponentFound = contents[i] === "e") || (floatFound = contents[i] === "."))) { i = i + 1; if (exponentFound) { isFloat = true; if (contents[i] === "+" || contents[i] === "-") { i = i + 1; } } if (floatFound) { isFloat = true; } } if (contents[i] === "f") { kind = TokenKind.FLOAT32; i = i + 1; } else { kind = isFloat ? TokenKind.FLOAT64 : TokenKind.INT32; } // Extra letters after the end is an error if (i < limit && (isAlpha(contents[i]) || isNumber(contents[i]))) { i = i + 1; while (i < limit && (isAlpha(contents[i]) || isNumber(contents[i]))) { i = i + 1; } log.error(createRange(source, start, i), `Invalid ${isFloat ? "float" : "integer"} literal: '${contents.slice(start, i)}'`); return null; } } } // Character or string else if (c == '"' || c == '\'' || c == '`') { while (i < limit) { var next = contents[i]; // Escape any character including newlines if (i + 1 < limit && next == '\\') { i = i + 2; } // Only allow newlines in template literals else if (next == '\n' && c != '`') { break; } // Handle a normal character else { i = i + 1; // End the string with a matching quote character if (next == c) { kind = c == '\'' ? TokenKind.CHARACTER : TokenKind.STRING; break; } } } // It's an error if we didn't find a matching quote character if (kind == TokenKind.END_OF_FILE) { log.error(createRange(source, start, i), c == '\'' ? "Unterminated character literal" : c == '`' ? "Unterminated template literal" : "Unterminated string literal"); return null; } } // Operators else if (c == '%') kind = TokenKind.REMAINDER; else if (c == '(') kind = TokenKind.LEFT_PARENTHESIS; else if (c == ')') kind = TokenKind.RIGHT_PARENTHESIS; else if (c == ',') kind = TokenKind.COMMA; else if (c == '.') kind = TokenKind.DOT; else if (c == ':') kind = TokenKind.COLON; else if (c == ';') kind = TokenKind.SEMICOLON; else if (c == '?') kind = TokenKind.QUESTION_MARK; else if (c == '[') kind = TokenKind.LEFT_BRACKET; else if (c == ']') kind = TokenKind.RIGHT_BRACKET; else if (c == '^') kind = TokenKind.BITWISE_XOR; else if (c == '{') kind = TokenKind.LEFT_BRACE; else if (c == '}') kind = TokenKind.RIGHT_BRACE; else if (c == '~') kind = TokenKind.COMPLEMENT; // * or ** else if (c == '*') { kind = TokenKind.MULTIPLY; if (i < limit && contents[i] == '*') { kind = TokenKind.EXPONENT; i = i + 1; } } // / or // or /* else if (c == '/') { kind = TokenKind.DIVIDE; // Single-line comments if (i < limit && contents[i] == '/') { i = i + 1; while (i < limit && contents[i] != '\n') { i = i + 1; } continue; } // Multi-line comments if (i < limit && contents[i] == '*') { i = i + 1; var foundEnd = false; while (i < limit) { var next = contents[i]; if (next == '*' && i + 1 < limit && contents[i + 1] == '/') { foundEnd = true; i = i + 2; break; } i = i + 1; } if (!foundEnd) { log.error(createRange(source, start, start + 2), "Unterminated multi-line comment"); return null; } continue; } } // ! or != else if (c == '!') { kind = TokenKind.NOT; if (i < limit && contents[i] == '=') { kind = TokenKind.NOT_EQUAL; i = i + 1; // Recover from !== if (i < limit && contents[i] == '=') { i = i + 1; log.error(createRange(source, start, i), "Use '!=' instead of '!=='"); } } } // = or == else if (c == '=') { kind = TokenKind.ASSIGN; if (i < limit && contents[i] == '=') { kind = TokenKind.EQUAL; i = i + 1; // Recover from === if (i < limit && contents[i] == '=') { i = i + 1; log.error(createRange(source, start, i), "Use '==' instead of '==='"); } } } // + or ++ else if (c == '+') { kind = TokenKind.PLUS; if (i < limit && contents[i] == '+') { kind = TokenKind.PLUS_PLUS; i = i + 1; } } // - or -- else if (c == '-') { kind = TokenKind.MINUS; if (i < limit && contents[i] == '-') { kind = TokenKind.MINUS_MINUS; i = i + 1; } } // & or && else if (c == '&') { kind = TokenKind.BITWISE_AND; if (i < limit && contents[i] == '&') { kind = TokenKind.LOGICAL_AND; i = i + 1; } } // | or || else if (c == '|') { kind = TokenKind.BITWISE_OR; if (i < limit && contents[i] == '|') { kind = TokenKind.LOGICAL_OR; i = i + 1; } } // < or << or <= else if (c == '<') { kind = TokenKind.LESS_THAN; if (i < limit) { c = contents[i]; if (c == '<') { kind = TokenKind.SHIFT_LEFT; i = i + 1; } else if (c == '=') { kind = TokenKind.LESS_THAN_EQUAL; i = i + 1; } } } // > or >> or >= else if (c == '>') { kind = TokenKind.GREATER_THAN; if (i < limit) { c = contents[i]; if (c == '>') { kind = TokenKind.SHIFT_RIGHT; i = i + 1; } else if (c == '=') { kind = TokenKind.GREATER_THAN_EQUAL; i = i + 1; } } } else if (c == '#') { while (i < limit && (isAlpha(contents[i]) || isNumber(contents[i]))) { i = i + 1; } var text = contents.slice(start, i); if (text == "#define") kind = TokenKind.PREPROCESSOR_DEFINE; else if (text == "#elif") kind = TokenKind.PREPROCESSOR_ELIF; else if (text == "#else") kind = TokenKind.PREPROCESSOR_ELSE; else if (text == "#endif") kind = TokenKind.PREPROCESSOR_ENDIF; else if (text == "#error") kind = TokenKind.PREPROCESSOR_ERROR; else if (text == "#if") kind = TokenKind.PREPROCESSOR_IF; else if (text == "#undef") kind = TokenKind.PREPROCESSOR_UNDEF; else if (text == "#warning") kind = TokenKind.PREPROCESSOR_WARNING; // Allow a shebang at the start of the file else if (start == 0 && text == "#" && i < limit && contents[i] == '!') { while (i < limit && contents[i] != '\n') { i = i + 1; } continue; } else { let errorMessage = `Invalid preprocessor token '${text}'`; // Check for #if typos if (text == "#ifdef") { errorMessage += ", did you mean '#if'?"; kind = TokenKind.PREPROCESSOR_IF; } // Check for #elif typos else if (text == "#elsif" || text == "#elseif") { errorMessage += ", did you mean '#elif'?"; kind = TokenKind.PREPROCESSOR_ELIF; } // Check for #endif typos else if (text == "#end") { errorMessage += ", did you mean '#endif'?"; kind = TokenKind.PREPROCESSOR_ENDIF; } log.error(createRange(source, start, i), errorMessage); } // All preprocessor directives must be on a line by themselves if (last != null && last.kind != TokenKind.PREPROCESSOR_NEWLINE) { let end = last.range.end; let j = i - 1; while (j >= end) { if (contents[j] == '\n') { break; } j = j - 1; } if (j < end) { log.error(createRange(source, start, i), `Expected newline before ${tokenToString(kind)}`); } } needsPreprocessor = true; wantNewline = true; } let range = createRange(source, start, i); if (kind == TokenKind.END_OF_FILE) { log.error(range, `Syntax error: '${contents.slice(start, start + 1)}'`); return null; } let token = new Token(); token.kind = kind; token.range = range; if (first == null) first = token; else last.next = token; last = token; } let eof = new Token(); eof.kind = TokenKind.END_OF_FILE; eof.range = createRange(source, limit, limit); if (first == null) first = eof; else last.next = eof; last = eof; // Pass a "flag" for whether the preprocessor is needed back to the caller if (needsPreprocessor) { let token = new Token(); token.kind = TokenKind.PREPROCESSOR_NEEDED; token.next = first; return token; } return first; }
the_stack
import { ServiceCenter } from '../lib' // Compiled from https://www.samband.is/sveitarfelogin/ list and // https://is.wikipedia.org/wiki/Íslensk_sveitarfélög_eftir_sveitarfélagsnúmerum export const serviceCenters: ServiceCenter[] = [ { name: 'Þjónustumiðstöð Vesturbæjar, Miðborgar og Hlíða', number: 0, phone: '411-1600', address: 'Laugavegi 77', addressPostalCode: '101 Reykjavík', postalCodes: [101, 102, 105, 107], link: 'https://reykjavik.is/stadir/thjonustumidstod-vesturbaejar-midborgar-og-hlida', }, { name: 'Þjónustumiðstöð Laugardals og Háaleitis', number: 0, phone: '411-1500', address: 'Efstaleiti 1', addressPostalCode: '103 Reykjavík', postalCodes: [103, 104, 105, 108], link: 'https://reykjavik.is/stadir/thjonustumidstod-laugardals-og-haaleitis', }, { name: 'Þjónustumiðstöð Árbæjar og Grafarholts', number: 0, phone: '411-1200', address: 'Hraunbær 115', addressPostalCode: '110 Reykjavík', postalCodes: [110, 113], link: 'https://reykjavik.is/stadir/thjonustumidstod-arbaejar-og-grafarholts', }, { name: 'Þjónustumiðstöð Breiðholts', number: 0, phone: '411-1300', address: 'Álfabakki 12', addressPostalCode: '109 Reykjavík', postalCodes: [109, 111], link: 'https://reykjavik.is/stadir/thjonustumidstod-breidholts', }, { name: 'Þjónustumiðstöð Grafarvogs og Kjalarness - Miðgarður', number: 0, phone: '411-1400', address: 'Gylfaflöt 5', addressPostalCode: '112 Reykjavík', postalCodes: [110, 112, 116, 162], link: 'https://reykjavik.is/stadir/thjonustumidstod-grafarvogs-og-kjalarness-midgardur', }, { name: 'Kópavogur', number: 1000, phone: '441-0000', address: 'Digranesvegi 1', addressPostalCode: '200 Kópavogi', postalCodes: [200, 201, 202, 203], }, { name: 'Seltjarnarnes', number: 1100, phone: '595-9100', address: 'Austurströnd 2', addressPostalCode: '170 Seltjarnarnes', postalCodes: [170], }, { name: 'Garðabær', number: 1300, phone: '525-8500', address: 'Garðatorgi 7', addressPostalCode: '210 Garðabæ', postalCodes: [210, 212, 225], }, { name: 'Hafnarfjörður', number: 1400, phone: '585-5500', address: 'Strandgötu 6', addressPostalCode: '220 Hafnarfirði', postalCodes: [220, 221, 222], active: true, }, { name: 'Reykjanesbær', number: 2000, phone: '421-6700', address: 'Tjarnargötu 12', addressPostalCode: '230 Reykjanesbæ', postalCodes: [230, 232, 233, 235, 260], }, { name: 'Grindavíkurbær', number: 2300, phone: '420-1100', address: 'Víkurbraut 62', addressPostalCode: '240 Grindavík', postalCodes: [240], }, { name: 'Akranes', number: 3000, phone: '433-1000', address: 'Stillholti 16-18', addressPostalCode: '300 Akranesi', postalCodes: [300], }, { name: 'Snæfellsbær', number: 3714, phone: '433-6900', address: 'Klettsbúð 4', addressPostalCode: '360 Hellissandi', postalCodes: [360], }, { name: 'Bolungarvík', number: 4100, phone: '450-7000', address: 'Aðalstræti 12', addressPostalCode: '415 Bolungarvík', postalCodes: [415], }, { name: 'Ísafjarðarbær', number: 4200, phone: '450-8000', address: 'Hafnarstræti 1', addressPostalCode: '400 Ísafjörður', postalCodes: [400, 401, 410, 425, 430, 470, 471], }, { name: 'Sveitarfélagið Skagafjörður', number: 5200, phone: '455-6000', address: 'Skagfirðingabraut 21', addressPostalCode: '550 Sauðárkrókur', postalCodes: [550, 551, 560, 565, 566, 570], }, { name: 'Akureyri', number: 6000, phone: '460-1000', address: 'Geislagötu 9', addressPostalCode: '600 Akureyri', postalCodes: [600, 603, 611, 630], }, { name: 'Norðurþing', number: 6100, phone: '464-6100', address: 'Ketilsbraut 7-9', addressPostalCode: '640 Húsavík', postalCodes: [640, 670, 671, 675], }, { name: 'Fjallabyggð', number: 6250, phone: '464-9100', address: 'Gránugötu 24', addressPostalCode: '580 Siglufirði', postalCodes: [580, 625], }, { name: 'Dalvíkurbyggð', number: 6400, phone: '460-4900', address: 'Ráðhúsi', addressPostalCode: '620 Dalvík', postalCodes: [620, 621], }, { name: 'Seyðisfjörður', number: 7000, phone: '470-2300', address: 'Hafnargötu 44', addressPostalCode: '710 Seyðisfirði', postalCodes: [710], }, { name: 'Fjarðabyggð', number: 7300, phone: '470-9000', address: 'Hafnargötu 2', addressPostalCode: '730 Reyðarfirði', postalCodes: [715, 730, 735, 740, 750, 755], }, { name: 'Vestmannaeyjar', number: 8000, phone: '488-2000', address: 'Bárustíg 15', addressPostalCode: '900 Vestmannaeyjum', postalCodes: [900, 902], }, { name: 'Sveitarfélagið Árborg', number: 8200, phone: '480-1900', address: 'Austurvegi 2', addressPostalCode: '800 Selfossi', postalCodes: [800, 801, 802, 820, 825], }, { name: 'Mosfellsbær', number: 1604, phone: '525-6700', address: 'Þverholti 2', addressPostalCode: '270 Mosfellsbæ', postalCodes: [270], }, { name: 'Kjósarhreppur', number: 1606, phone: '566-7100', address: 'Ásgarði', addressPostalCode: '276 Mosfellsbæ', postalCodes: [270], }, { name: 'Sandgerði', number: 2503, phone: '420-7500', address: 'Miðnestorgi 3', addressPostalCode: '245 Sandgerði', postalCodes: [245], }, { name: 'Sveitarfélagið Garður', number: 2504, phone: '422-0200', address: 'Sunnubraut 4', addressPostalCode: '250 Garði', postalCodes: [250], }, { name: 'Sveitarfélagið Vogar', number: 2506, phone: '440-6200', address: 'Iðndal 2', addressPostalCode: '190 Vogum', postalCodes: [190], }, { name: 'Skorradalshreppur', number: 3506, phone: '431-1020', address: 'Hvanneyrargötu 3', addressPostalCode: '311 Borgarnes', postalCodes: [311], }, { name: 'Hvalfjarðarsveit', number: 3511, phone: '433-8500', address: 'Innrimel 3', addressPostalCode: '301 Akranes', postalCodes: [301], }, { name: 'Borgarbyggð', number: 3609, phone: '433-7100', address: 'Borgarbraut 14', addressPostalCode: '310 Borgarnesi', postalCodes: [310, 311, 320], }, { name: 'Grundarfjarðarbær', number: 3709, phone: '430-8500', address: 'Borgarbraut 16', addressPostalCode: '350 Grundarfirði', postalCodes: [350], }, { name: 'Helgafellssveit', number: 3710, phone: '438-1536', address: 'Gríshóll', addressPostalCode: '340 Helgafellssveit', postalCodes: [340], }, { name: 'Stykkishólmur', number: 3711, phone: '433-8100', address: 'Hafnargötu 3', addressPostalCode: '340 Stykkishólmi', postalCodes: [340], }, { name: 'Eyja- og Miklaholtshreppur', number: 3713, phone: '435-6870', address: 'Hofsstöðum', addressPostalCode: '311 Borgarnesi', postalCodes: [311], }, { name: 'Dalabyggð', number: 3811, phone: '430-4700', address: 'Miðbraut 11', addressPostalCode: '370 Búðardal', postalCodes: [370, 371], }, { name: 'Reykhólahreppur', number: 4502, phone: '430-3200', address: 'Maríutröð 5a', addressPostalCode: '380 Reykhólshreppi', postalCodes: [380], }, { name: 'Tálknafjarðarhreppur', number: 4604, phone: '450-2500', address: 'Strandgötu 38', addressPostalCode: '460 Tálknafirði', postalCodes: [460], }, { name: 'Vesturbyggð', number: 4607, phone: '450-2300', address: 'Aðalstræti 75', addressPostalCode: '450 Patreksfirði', postalCodes: [450, 451, 465], }, { name: 'Súðavíkurhreppur', number: 4803, phone: '450-5900', address: 'Grundarstræti 3', addressPostalCode: '420 Súðavík', postalCodes: [420], }, { name: 'Árneshreppur', number: 4901, phone: '451-4001', address: 'Norðurfirði', addressPostalCode: '524 Árneshreppur', postalCodes: [524], }, { name: 'Kaldrananeshreppur', number: 4902, phone: '451-3277', address: 'Holtagötu', addressPostalCode: '520 Drangsnesi', postalCodes: [510, 520], }, { name: 'Strandabyggð', number: 4911, phone: '451-3510', address: 'Höfðagötu 3', addressPostalCode: '510 Hólmavík', postalCodes: [510], }, { name: 'Húnaþing vestra', number: 5508, phone: '455-2400', address: 'Hvammstangabraut 5', addressPostalCode: '530 Hvammstanga', postalCodes: [500, 530, 531], }, { name: 'Blönduós', number: 5604, phone: '455-4700', address: 'Hnjúkabyggð 33', addressPostalCode: '540 Blönduósi', postalCodes: [540], }, { name: 'Sveitarfélagið Skagaströnd', number: 5609, phone: '455-2700', address: 'Túnbraut 1-30', addressPostalCode: '545 Skagaströnd', postalCodes: [545], }, { name: 'Skagabyggð', number: 5611, phone: '452-2732', address: 'Ytri-Hóll', addressPostalCode: '541 Blönduósi', postalCodes: [545], }, { name: 'Húnavatnshreppur', number: 5612, phone: '455-0010', address: 'Húnavöllum', addressPostalCode: '541 Blönduósi', postalCodes: [541], }, { name: 'Akrahreppur', number: 5706, phone: '626-1016', address: 'Miklabæ', addressPostalCode: '561 Varmahlíð', postalCodes: [560], }, { name: 'Eyjafjarðarsveit', number: 6513, phone: '463-0600', address: 'Skólatröð 9', addressPostalCode: '601 Akureyri', postalCodes: [601], }, { name: 'Hörgársveit', number: 6515, phone: '460-1750', address: 'Þelamerkurskóla', addressPostalCode: '601 Akureyri', postalCodes: [601], }, { name: 'Svalbarðarsstrandarhreppur', number: 6601, phone: '464-5500', address: 'Svalbarðseyri', addressPostalCode: '601 Akureyri', postalCodes: [601], }, { name: 'Grýtubakkahreppur', number: 6602, phone: '414-5400', address: 'Túngötu 3', addressPostalCode: '610 Grenivík', postalCodes: [601, 610], }, { name: 'Skútustaðahreppur', number: 6607, phone: '464-4163', address: 'Hlíðavegi 6', addressPostalCode: '660 Mývatni', postalCodes: [660], }, { name: 'Tjörneshreppur', number: 6611, phone: '863-6629', address: 'Ketilsstaðir', addressPostalCode: '641 Húsavík', postalCodes: [641], }, { name: 'Þingeyjarsveit', number: 6612, phone: '464-3322', address: 'Kjarna', addressPostalCode: '650 Laugum', postalCodes: [601, 641, 645, 650], }, { name: 'Svalbarðshreppur', number: 6706, phone: '895-0833', address: 'Holti', addressPostalCode: '681 Þórshöfn', postalCodes: [681], }, { name: 'Langanesbyggð', number: 6709, phone: '468-1220', address: 'Fjarðarvegi 3', addressPostalCode: '680 Þórshöfn', postalCodes: [680, 681, 685], }, { name: 'Vopnafjarðarhreppur', number: 7502, phone: '473-1300', address: 'Hamrahlíð 15', addressPostalCode: '690 Vopnafirði', postalCodes: [690], }, { name: 'Fljótsdalshreppur', number: 7505, phone: '471-1810', address: 'Végarði', addressPostalCode: '701 Egilsstöðum', postalCodes: [701], }, { name: 'Borgarfjarðarhreppur', number: 7509, phone: '472-9999', address: 'Hreppsstofu', addressPostalCode: '720 Borgarfirði', postalCodes: [701], }, { name: 'Djúpavogshreppur', number: 7617, phone: '470-8700', address: 'Bakka 1', addressPostalCode: '765 Djúpavogi', postalCodes: [765, 766], }, { name: 'Fljótsdalshérað', number: 7620, phone: '470-0700', address: 'Lyngási 12', addressPostalCode: '700 Egilsstöðum', postalCodes: [700, 701], }, { name: 'Sveitarfélagið Hornafjörður', number: 7708, phone: '470-8000', address: 'Hafnarbraut 27', addressPostalCode: '780 Höfn í Hornafirði', postalCodes: [780, 781, 785], }, { name: 'Mýrdalshreppur', number: 8508, phone: '487-1210', address: 'Austurvegi 17', addressPostalCode: '870 Vík', postalCodes: [870, 871], }, { name: 'Skaftárhreppur', number: 8509, phone: '487-4840', address: 'Klausturvegi 10', addressPostalCode: '880 Kirkjubæjarklaustri', postalCodes: [880], }, { name: 'Áshreppur', number: 8610, phone: '487-6501', address: 'Hreppsstofu', addressPostalCode: '720 Borgarfirði', postalCodes: [851], }, { name: 'Rangárþing eystra', number: 8613, phone: '488-4200', address: 'Austurvegi 4', addressPostalCode: '860 Hvolsvelli', postalCodes: [860, 861], }, { name: 'Rangárþing ytra', number: 8614, phone: '488-7000', address: 'Suðurlandsvegi 1-3', addressPostalCode: '850 Hellu', postalCodes: [850, 851], }, { name: 'Hrunamannahreppur', number: 8710, phone: '480-6600', address: 'Akurgerði 6', addressPostalCode: '845 Flúðum', postalCodes: [845], }, { name: 'Hveragerði', number: 8716, phone: '483-4000', address: 'Breiðumörk 20', addressPostalCode: '810 Hveragerði', postalCodes: [810], }, { name: 'Sveitarfélagið Ölfus', number: 8717, phone: '480-3800', address: 'Hafnarbergi 1', addressPostalCode: '815 Þorlákshöfn', postalCodes: [815], }, { name: 'Grímsnes- og Grafningshreppur', number: 8719, phone: '480-5500', address: 'Borg', addressPostalCode: '801 Selfossi', postalCodes: [801], }, { name: 'Skeiða- og Gnúpverjahreppur', number: 8720, phone: '486-6100', address: 'Árnesi', addressPostalCode: '801 Selfossi', postalCodes: [801], }, { name: 'Bláskógabyggð', number: 8721, phone: '480-3000', address: 'Reykholti', addressPostalCode: '801 Selfossi', postalCodes: [801], }, { name: 'Flóahreppur', number: 8722, phone: '480-4370', address: 'Þingborg', addressPostalCode: '801 Selfossi', postalCodes: [801], }, ] export default serviceCenters
the_stack
import { ILayoutRestorer, JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { ICommandPalette, WidgetTracker, IWidgetTracker } from '@jupyterlab/apputils'; import { IMainMenu, JupyterLabMenu } from '@jupyterlab/mainmenu'; import { IFileBrowserFactory } from '@jupyterlab/filebrowser'; import { ILauncher } from '@jupyterlab/launcher'; import { undoIcon, redoIcon } from '@jupyterlab/ui-components'; import { CommandRegistry } from '@lumino/commands'; import { Token } from '@lumino/coreutils'; import { zoominIcon, zoomoutIcon, toFrontIcon, toBackIcon, fillColorIcon, strokeColorIcon, shadowIcon } from './icons'; import { DrawIODocumentWidget } from './editor'; import { DrawIOFactory } from './factory'; /** * The name of the factory that creates editor widgets. */ const FACTORY = 'Drawio'; type IDrawioTracker = IWidgetTracker<DrawIODocumentWidget>; export const IDrawioTracker = new Token<IDrawioTracker>('drawio/tracki'); /** * The editor tracker extension. */ const extension: JupyterFrontEndPlugin<IDrawioTracker> = { id: '@jupyterlab/drawio-extension:plugin', autoStart: true, requires: [IFileBrowserFactory, ILayoutRestorer, IMainMenu, ICommandPalette], optional: [ILauncher], provides: IDrawioTracker, activate }; export default extension; function activate( app: JupyterFrontEnd, browserFactory: IFileBrowserFactory, restorer: ILayoutRestorer, menu: IMainMenu, palette: ICommandPalette, launcher: ILauncher | null ): IDrawioTracker { const { commands } = app; const namespace = 'drawio'; const tracker = new WidgetTracker<DrawIODocumentWidget>({ namespace }); // Handle state restoration. restorer.restore(tracker, { command: 'docmanager:open', args: widget => ({ path: widget.context.path, factory: FACTORY }), name: widget => widget.context.path }); const factory = new DrawIOFactory({ name: FACTORY, fileTypes: ['dio', 'drawio'], defaultFor: ['dio', 'drawio'], commands: app.commands }); factory.widgetCreated.connect((sender, widget) => { widget.title.icon = 'jp-MaterialIcon jp-ImageIcon'; // TODO change // Notify the instance tracker if restore data needs to update. widget.context.pathChanged.connect(() => { tracker.save(widget); }); tracker.add(widget); }); app.docRegistry.addWidgetFactory(factory); // register the filetype app.docRegistry.addFileType({ name: 'drawio', displayName: 'Diagram', mimeTypes: ['application/dio', 'application/drawio'], extensions: ['.dio', '.drawio'], iconClass: 'jp-MaterialIcon jp-ImageIcon', fileFormat: 'text', contentType: 'file' }); // Add a command for creating a new diagram file. commands.addCommand('drawio:create-new', { label: 'Diagram', iconClass: 'jp-MaterialIcon jp-ImageIcon', caption: 'Create a new diagram file', execute: () => { const cwd = browserFactory.defaultBrowser.model.path; commands .execute('docmanager:new-untitled', { path: cwd, type: 'file', ext: '.dio' }) .then(model => commands.execute('docmanager:open', { path: model.path, factory: FACTORY }) ); } }); commands.addCommand('drawio:export-svg', { label: 'Export diagram as SVG', caption: 'Export diagram as SVG', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { const cwd = browserFactory.defaultBrowser.model.path; commands .execute('docmanager:new-untitled', { path: cwd, type: 'file', ext: '.svg' }) .then(model => { const wdg = app.shell.currentWidget as any; model.content = wdg.getSVG(); model.format = 'text'; app.serviceManager.contents.save(model.path, model); }); } }); // Add a launcher item if the launcher is available. if (launcher) { launcher.add({ command: 'drawio:create-new', rank: 1, category: 'Other' }); } if (menu) { addMenus(commands, menu, tracker); } addCommands(app, tracker); if (palette) { const args = { format: 'SVG', label: 'SVG', isPalette: true }; palette.addItem({ command: 'drawio:export-svg', category: 'Notebook Operations', args: args }); } return tracker; } function addMenus( commands: CommandRegistry, menu: IMainMenu, tracker: IDrawioTracker ): void { const diagram = new JupyterLabMenu({ commands }); diagram.menu.title.label = 'Diagram'; // FILE MENU // Add new text file creation to the file menu. menu.fileMenu.newMenu.addGroup([{ command: 'drawio:create-new' }], 40); const fileMenu = new JupyterLabMenu({ commands }); fileMenu.menu.title.label = 'File'; fileMenu.addGroup([{ command: 'drawio:create-new' }], 0); fileMenu.addGroup( [ { command: 'drawio:export-svg' }, { command: 'drawio:command/pageSetup' }, { command: 'drawio:command/print' } ], 1 ); // Edit MENU menu.editMenu.undoers.add({ tracker, undo: (widget: any) => widget.execute('undo'), redo: (widget: any) => widget.execute('redo') } as any); const editMenu = new JupyterLabMenu({ commands }); editMenu.menu.title.label = 'Edit'; editMenu.addGroup( [{ command: 'drawio:command/undo' }, { command: 'drawio:command/redo' }], 0 ); editMenu.addGroup( [ { command: 'drawio:command/cut' }, { command: 'drawio:command/copy' }, { command: 'drawio:command/paste' }, { command: 'drawio:command/delete' } ], 1 ); editMenu.addGroup([{ command: 'drawio:command/duplicate' }], 2); editMenu.addGroup( [ { command: 'drawio:command/editData' }, { command: 'drawio:command/editTooltip' }, { command: 'drawio:command/editStyle' } ], 3 ); editMenu.addGroup([{ command: 'drawio:command/edit' }], 4); editMenu.addGroup( [ { command: 'drawio:command/editLink' }, { command: 'drawio:command/openLink' } ], 5 ); editMenu.addGroup( [ { command: 'drawio:command/selectVertices' }, { command: 'drawio:command/selectEdges' }, { command: 'drawio:command/selectAll' }, { command: 'drawio:command/selectNone' } ], 6 ); editMenu.addGroup([{ command: 'drawio:command/lockUnlock' }], 7); // View MENU const viewMenu = new JupyterLabMenu({ commands }); viewMenu.menu.title.label = 'View'; viewMenu.addGroup( [ { command: 'drawio:command/formatPanel' }, { command: 'drawio:command/outline' }, { command: 'drawio:command/layers' } ], 0 ); viewMenu.addGroup( [ { command: 'drawio:command/pageView' }, { command: 'drawio:command/pageScale' } ], 1 ); viewMenu.addGroup( [ { command: 'drawio:command/scrollbars' }, { command: 'drawio:command/tooltips' } ], 2 ); viewMenu.addGroup( [{ command: 'drawio:command/grid' }, { command: 'drawio:command/guides' }], 3 ); viewMenu.addGroup( [ { command: 'drawio:command/connectionArrows' }, { command: 'drawio:command/connectionPoints' } ], 4 ); viewMenu.addGroup( [ { command: 'drawio:command/resetView' }, { command: 'drawio:command/zoomIn' }, { command: 'drawio:command/zoomOut' } ], 5 ); // Arrange MENU const arrangeMenu = new JupyterLabMenu({ commands }); arrangeMenu.menu.title.label = 'Arrange'; arrangeMenu.addGroup( [ { command: 'drawio:command/toFront' }, { command: 'drawio:command/toBack' } ], 0 ); const direction = new JupyterLabMenu({ commands }); direction.menu.title.label = 'Direction'; direction.addGroup( [{ command: 'drawio:command/flipH' }, { command: 'drawio:command/flipV' }], 0 ); direction.addGroup([{ command: 'drawio:command/rotation' }], 1); arrangeMenu.addGroup( [ { type: 'submenu', submenu: direction.menu }, { command: 'drawio:command/turn' } ], 1 ); const align = new JupyterLabMenu({ commands }); align.menu.title.label = 'Diagram Align'; align.addGroup( [ { command: 'drawio:command/alignCellsLeft' }, { command: 'drawio:command/alignCellsCenter' }, { command: 'drawio:command/alignCellsRight' } ], 0 ); align.addGroup( [ { command: 'drawio:command/alignCellsTop' }, { command: 'drawio:command/alignCellsMiddle' }, { command: 'drawio:command/alignCellsBottom' } ], 1 ); const distribute = new JupyterLabMenu({ commands }); distribute.menu.title.label = 'Distribute'; distribute.addGroup( [ { command: 'drawio:command/horizontal' }, { command: 'drawio:command/vertical' } ], 0 ); arrangeMenu.addGroup( [ { type: 'submenu', submenu: align.menu }, { type: 'submenu', submenu: distribute.menu } ], 2 ); const navigation = new JupyterLabMenu({ commands }); navigation.menu.title.label = 'Navigation'; navigation.addGroup([{ command: 'drawio:command/home' }], 0); navigation.addGroup( [ { command: 'drawio:command/exitGroup' }, { command: 'drawio:command/enterGroup' } ], 1 ); navigation.addGroup( [ { command: 'drawio:command/expand' }, { command: 'drawio:command/collapse' } ], 2 ); navigation.addGroup([{ command: 'drawio:command/collapsible' }], 3); const insert = new JupyterLabMenu({ commands }); insert.menu.title.label = 'Insert'; insert.addGroup( [ { command: 'drawio:command/insertLink' }, { command: 'drawio:command/insertImage' } ], 0 ); const layout = new JupyterLabMenu({ commands }); layout.menu.title.label = 'Layout'; layout.addGroup( [ { command: 'drawio:command/horizontalFlow' }, { command: 'drawio:command/verticalFlow' } ], 0 ); layout.addGroup( [ { command: 'drawio:command/horizontalTree' }, { command: 'drawio:command/verticalTree' }, { command: 'drawio:command/radialTree' } ], 1 ); layout.addGroup( [ { command: 'drawio:command/organic' }, { command: 'drawio:command/circle' } ], 2 ); arrangeMenu.addGroup( [ { type: 'submenu', submenu: navigation.menu }, { type: 'submenu', submenu: insert.menu }, { type: 'submenu', submenu: layout.menu } ], 3 ); arrangeMenu.addGroup( [ { command: 'drawio:command/group' }, { command: 'drawio:command/ungroup' }, { command: 'drawio:command/removeFromGroup' } ], 4 ); arrangeMenu.addGroup( [ { command: 'drawio:command/clearWaypoints' }, { command: 'drawio:command/autosize' } ], 5 ); // Extras MENU const extrasMenu = new JupyterLabMenu({ commands }); extrasMenu.menu.title.label = 'Extras'; extrasMenu.addGroup( [ { command: 'drawio:command/copyConnect' }, { command: 'drawio:command/collapseExpand' } ], 0 ); extrasMenu.addGroup([{ command: 'drawio:command/editDiagram' }], 1); diagram.addGroup( [ { type: 'submenu', submenu: fileMenu.menu }, { type: 'submenu', submenu: editMenu.menu }, { type: 'submenu', submenu: viewMenu.menu }, { type: 'submenu', submenu: arrangeMenu.menu }, { type: 'submenu', submenu: extrasMenu.menu }, { command: 'drawio:command/about' } ], 0 ); menu.addMenu(diagram.menu, { rank: 60 }); } function addCommands(app: JupyterFrontEnd, tracker: IDrawioTracker): void { // FILE MENU //Not Working: new, open, save, save as, import, export //Working: pageSetup, print const fileCommands = [ { name: 'pageSetup', label: 'Page Setup...' }, { name: 'print', label: 'Print...' } //Ctrl+P ]; fileCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); // Edit MENU //Not Working: //Working: // undo, redo, // cut, copy, paste, delete // Duplicate // Edit data, edit tooltip, Edit style // Edit // Edit link, open link // Select vertices, select edges, select all, select none // lock/unlock const editCommands = [ //{ name: 'undo', label: 'Undo' }, //Ctrl+Z //{ name: 'redo', label: 'Redo' }, //Ctrl+Shift+Z { name: 'cut', label: 'Cut' }, //Ctrl+X { name: 'copy', label: 'Copy' }, //Ctrl+C { name: 'paste', label: 'Paste' }, //Ctrl+V { name: 'delete', label: 'Delete' }, { name: 'duplicate', label: 'Duplicate' }, //Ctrl+D { name: 'editData', label: 'Edit Data...' }, //Ctrl+M { name: 'editTooltip', label: 'Edit Tooltip...' }, { name: 'editStyle', label: 'Edit Style...' }, //Ctrl+E { name: 'edit', label: 'Edit' }, //F2/Enter { name: 'editLink', label: 'Edit Link...' }, { name: 'openLink', label: 'Open Link' }, { name: 'selectVertices', label: 'Select Vertices' }, //Ctrl+Shift+I { name: 'selectEdges', label: 'Select Edges' }, //Ctrl+Shift+E { name: 'selectAll', label: 'Select all' }, //Ctrl+A { name: 'selectNone', label: 'Select None' }, //Ctrl+Shift+A { name: 'lockUnlock', label: 'Lock/Unlock' } //Ctrl+L ]; editCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); app.commands.addCommand('drawio:command/undo', { label: 'Undo', caption: 'Undo (Ctrl+Z)', icon: undoIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('undo').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('undo').funct(); } } }); app.commands.addCommand('drawio:command/redo', { label: 'Redo', caption: 'Redo (Ctrl+Shift+Z)', icon: redoIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('redo').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('redo').funct(); } } }); // View MENU //Not Working: //Working: // formatPanel, outline, layers // pageView, pageScale // scrollbars, tooltips // grid, guides // connectionArrows, connectionPoints // resetView, zoomIn, zoomOut const viewCommands = [ { name: 'formatPanel', label: 'Format Panel' }, //Ctrl+Shift+P { name: 'outline', label: 'Outline' }, //Ctrl+Shift+O { name: 'layers', label: 'Layers' }, //Ctrl+Shift+L { name: 'pageView', label: 'Page View' }, { name: 'pageScale', label: 'Page Scale...' }, { name: 'scrollbars', label: 'Scrollbars' }, { name: 'tooltips', label: 'Tooltips' }, { name: 'grid', label: 'Grid' }, //Ctrl+Shift+G { name: 'guides', label: 'Guides' }, { name: 'connectionArrows', label: 'Connection Arrows' }, //Alt+Shift+A { name: 'connectionPoints', label: 'Connection Points' }, //Alt+Shift+P { name: 'resetView', label: 'Reset View' } //Ctrl+H //{ name: 'zoomIn', label: 'Zoom In' }, //Ctrl+(Numpad)/Alt+Mousewheel //{ name: 'zoomOut', label: 'Zoom Out' } //Ctrl-(Numpad)/Alt+Mousewheel ]; viewCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isToggleable: true, isToggled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; const act = wdg.getAction(action.name); return act.toggleAction ? act.isSelected() : false; } else { return false; } }, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); app.commands.addCommand('drawio:command/zoomIn', { label: 'Zoom In', caption: 'Zoom In (Ctrl+(Numpad)/Alt+Mousewheel)', icon: zoominIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('zoomIn').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('zoomIn').funct(); } } }); app.commands.addCommand('drawio:command/zoomOut', { label: 'Zoom Out', caption: 'Zoom Out (Ctrl-(Numpad)/Alt+Mousewheel)', icon: zoomoutIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('zoomOut').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('zoomOut').funct(); } } }); // Arrange MENU //Not Working: //Working: // toFront, toBack // Direction->(flipH, flipV, rotation), turn // Align->(alignCellsRight, alignCellsCenter, alignCellsRight // alignCellsTop, alignCellsMiddle, alignCellsBottom), // Distribute->(horizontal, vertical) // Navigation->(home, // exitGroup, enterGroup // expand, collapse // collapsible), // Insert->(insertLink, insertImage) // Layout->(horizontalFlow, verticalFlow // horizontalTree, verticalTree, radialTree // organic, circle) // group, ungroup, removeFromGroup // clearWaypoints, autosize const arrangeCommands = [ //{ name: 'toFront', label: 'To Front' }, //Ctrl+Shift+F //{ name: 'toBack', label: 'To Back' }, //Ctrl+Shift+B { name: 'rotation', label: 'Rotation' }, { name: 'turn', label: 'Rotate 90⁰/Reverse' }, //Ctrl+R { name: 'home', label: 'Home' }, { name: 'exitGroup', label: 'Exit Group' }, //Ctrl+Shift+Home { name: 'enterGroup', label: 'Enter Group' }, //Ctrl+Shift+End { name: 'expand', label: 'Expand' }, //Ctrl+End { name: 'collapse', label: 'Collapse' }, //Ctrl+Home { name: 'collapsible', label: 'Collapsible' }, { name: 'insertLink', label: 'Insert Link...' }, { name: 'insertImage', label: 'Insert Image...' }, { name: 'group', label: 'Group' }, //Ctrl+G { name: 'ungroup', label: 'Ungroup' }, //Ctrl+Shift+U { name: 'removeFromGroup', label: 'Remove from Group' }, { name: 'clearWaypoints', label: 'Clear Waypoints' }, //Alt+Shift+C { name: 'autosize', label: 'Autosize' } //Ctrl+Shift+Y ]; arrangeCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); app.commands.addCommand('drawio:command/toFront', { label: 'To Front', caption: 'To Front (Ctrl+Shift+F)', icon: toFrontIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('toFront').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('toFront').funct(); } } }); app.commands.addCommand('drawio:command/toBack', { label: 'To Back', caption: 'To Back (Ctrl+Shift+B)', icon: toBackIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('toBack').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('toBack').funct(); } } }); //Direction app.commands.addCommand('drawio:command/flipH', { label: 'Flip Horizintal', caption: 'Flip Horizintal', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.toggleCellStyles('flipH'); } } }); app.commands.addCommand('drawio:command/flipV', { label: 'Flip Vertical', caption: 'Flip Vertical', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.toggleCellStyles('flipV'); } } }); //Align app.commands.addCommand('drawio:command/alignCellsLeft', { label: 'Left Align', caption: 'Left Align', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.alignCells('alignCellsLeft'); } } }); app.commands.addCommand('drawio:command/alignCellsCenter', { label: 'Center', caption: 'Center', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.alignCells('alignCellsCenter'); } } }); app.commands.addCommand('drawio:command/alignCellsRight', { label: 'Right Align', caption: 'Right Align', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.alignCells('alignCellsRight'); } } }); app.commands.addCommand('drawio:command/alignCellsTop', { label: 'Top Align', caption: 'Top Align', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.alignCells('alignCellsTop'); } } }); app.commands.addCommand('drawio:command/alignCellsMiddle', { label: 'Middle', caption: 'Middle', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.alignCells('alignCellsMiddle'); } } }); app.commands.addCommand('drawio:command/alignCellsBottom', { label: 'Bottom Align', caption: 'Bottom Align', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.alignCells('alignCellsBottom'); } } }); //Distribute app.commands.addCommand('drawio:command/horizontal', { label: 'Horizontal', caption: 'Horizontal', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.distributeCells(true); } } }); app.commands.addCommand('drawio:command/vertical', { label: 'Vertical', caption: 'Vertical', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.distributeCells(false); } } }); //Layout app.commands.addCommand('drawio:command/horizontalFlow', { label: 'Horizontal Flow', caption: 'Horizontal Flow', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.layoutFlow('horizontalFlow'); } } }); app.commands.addCommand('drawio:command/verticalFlow', { label: 'Vertical Flow', caption: 'Vertical Flow', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.layoutFlow('verticalFlow'); } } }); app.commands.addCommand('drawio:command/horizontalTree', { label: 'Horizontal Tree', caption: 'Horizontal Tree', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.horizontalTree(); } } }); app.commands.addCommand('drawio:command/verticalTree', { label: 'Vertical Tree', caption: 'Vertical Tree', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.verticalTree(); } } }); app.commands.addCommand('drawio:command/radialTree', { label: 'Radial Tree', caption: 'Radial Tree', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.radialTree(); } } }); app.commands.addCommand('drawio:command/organic', { label: 'Organic', caption: 'Organic', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.organic(); } } }); app.commands.addCommand('drawio:command/circle', { label: 'Circle', caption: 'Circle', isEnabled: () => tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.circle(); } } }); // Extras MENU //Not Working: //Working: // copyConnect, collapseExpand // editDiagram const extrasCommands = [ { name: 'copyConnect', label: 'Copy on Connect' }, { name: 'collapseExpand', label: 'Collapse/Expand' }, { name: 'editDiagram', label: 'Edit Diagram...' } ]; extrasCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); // Help MENU //Not Working: help //Working: // about const helpCommands = [{ name: 'about', label: 'About GraphEditor' }]; helpCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); /************************************************************************************** * Toolbar * **************************************************************************************/ //Working: fitWindow, fitPageWidth, fitPage, fitTwoPages, customZoom const toolbarCommands = [ { name: 'fitWindow', label: 'Fit Window' }, //Ctrl+Shift+H { name: 'fitPageWidth', label: 'Page Width' }, { name: 'fitPage', label: 'One Page' }, //Ctrl+J { name: 'fitTwoPages', label: 'Two Pages' }, //Ctrl+Shift+J { name: 'customZoom', label: 'Custom...' } //Ctrl+O ]; toolbarCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); app.commands.addCommand('drawio:command/fillColor', { label: 'Fill Color', caption: 'Fill Color', icon: fillColorIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; console.debug('fill Color:', wdg.getAction('fillColor').enabled); return wdg.getAction('fillColor').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('fillColor').funct(); } } }); app.commands.addCommand('drawio:command/strokeColor', { label: 'Fill Stroke Color', caption: 'Fill Stroke Color', icon: strokeColorIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('strokeColor').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('strokeColor').funct(); } } }); app.commands.addCommand('drawio:command/shadow', { label: 'Shadow', caption: 'Shadow', icon: shadowIcon, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction('shadow').enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction('shadow').funct(); } } }); /************************************************************************************** * Other * **************************************************************************************/ const otherCommands = [ { name: 'addWaypoint', label: 'Add Waypoint' }, { name: 'autosave', label: 'Autosave' }, { name: 'backgroundColor', label: 'Background Color' }, { name: 'bold', label: 'Bold' }, { name: 'borderColor', label: 'Border Color' }, { name: 'clearDefaultStyle', label: 'Clear Default Style' }, { name: 'curved', label: 'Curved' }, { name: 'dashed', label: 'Dashed' }, { name: 'deleteAll', label: 'Delete All' }, { name: 'dotted', label: 'Dotted' }, { name: 'fontColor', label: 'Font Color' }, { name: 'formattedText', label: 'Formatted Text' }, { name: 'gradientColor', label: 'Gradient Color' }, { name: 'image', label: 'Image' }, { name: 'italic', label: 'Italic' }, { name: 'link', label: 'Link' }, { name: 'pasteHere', label: 'Paste Here' }, { name: 'preview', label: 'Preview' }, { name: 'removeWaypoint', label: 'Remove Waypoint' }, { name: 'rounded', label: 'Rounded' }, { name: 'setAsDefaultStyle', label: 'Set As Default Style' }, { name: 'sharp', label: 'Sharp' }, { name: 'solid', label: 'Solid' }, { name: 'subscript', label: 'Subscript' }, { name: 'superscript', label: 'Superscript' }, { name: 'toggleRounded', label: 'Toggle Rounded' }, { name: 'underline', label: 'Underline' }, { name: 'wordWrap', label: 'Word Wrap' } ]; otherCommands.forEach(action => { app.commands.addCommand('drawio:command/' + action.name, { label: action.label, caption: action.label, isEnabled: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; return wdg.getAction(action.name).enabled; } else { return false; } }, execute: () => { if ( tracker.currentWidget !== null && tracker.currentWidget === app.shell.currentWidget ) { const wdg = app.shell.currentWidget as DrawIODocumentWidget; wdg.getAction(action.name).funct(); } } }); }); }
the_stack
import { Frustum, ICamera, IDENTIFIER, IInteractorService, } from '@antv/g-webgpu-core'; import { mat3, mat4, quat, vec3, vec4 } from 'gl-matrix'; import { inject, injectable, postConstruct } from 'inversify'; import { createVec3, getAngle } from '../utils/math'; import Landmark from './Landmark'; export enum CAMERA_TYPE { ORBITING = 'ORBITING', EXPLORING = 'EXPLORING', TRACKING = 'TRACKING', } export enum CAMERA_TRACKING_MODE { DEFAULT = 'DEFAULT', ROTATIONAL = 'ROTATIONAL', TRANSLATIONAL = 'TRANSLATIONAL', CINEMATIC = 'CINEMATIC', } export enum CAMERA_PROJECTION_MODE { ORTHOGRAPHIC = 'ORTHOGRAPHIC', PERSPECTIVE = 'PERSPECTIVE', } const DEG_2_RAD = Math.PI / 180; const RAD_2_DEG = 180 / Math.PI; /** * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计 * 保存相机参数,定义相机动作: * 1. dolly 沿 n 轴移动 * 2. pan 沿 u v 轴移动 * 3. rotate 以方位角旋转 * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互 */ @injectable() export class Camera implements ICamera { public static ProjectionMode = { ORTHOGRAPHIC: 'ORTHOGRAPHIC', PERSPECTIVE: 'PERSPECTIVE', }; /** * 相机矩阵 */ public matrix = mat4.create(); /** * u 轴 * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition */ public right = vec3.fromValues(1, 0, 0); /** * v 轴 */ public up = vec3.fromValues(0, 1, 0); /** * n 轴 */ public forward = vec3.fromValues(0, 0, 1); /** * 相机位置 */ public position = vec3.fromValues(0, 0, 1); /** * 视点位置 */ public focalPoint = vec3.fromValues(0, 0, 0); /** * 相机位置到视点向量 * focalPoint - position */ public distanceVector = vec3.fromValues(0, 0, 0); /** * 相机位置到视点距离 * length(focalPoint - position) */ public distance = 1; /** * @see https://en.wikipedia.org/wiki/Azimuth */ public azimuth = 0; public elevation = 0; public roll = 0; public relAzimuth = 0; public relElevation = 0; public relRoll = 0; /** * 沿 n 轴移动时,保证移动速度从快到慢 */ public dollyingStep = 0; public maxDistance = Infinity; public minDistance = -Infinity; /** * invert the horizontal coordinate system HCS */ public rotateWorld = false; @inject(IDENTIFIER.InteractorService) public interactor: IInteractorService; /** * 投影矩阵参数 */ /** * field of view [0-360] * @see http://en.wikipedia.org/wiki/Angle_of_view */ private fov = 30; private near = 0.1; private far = 10000; private aspect = 1; private left: number; private rright: number; private top: number; private bottom: number; private zoom = 1; private perspective = mat4.create(); private view: | { enabled: boolean; fullWidth: number; fullHeight: number; offsetX: number; offsetY: number; width: number; height: number; } | undefined; private following = undefined; private type = CAMERA_TYPE.EXPLORING; private trackingMode = CAMERA_TRACKING_MODE.DEFAULT; private projectionMode = CAMERA_PROJECTION_MODE.PERSPECTIVE; /** * for culling use */ private frustum: Frustum = new Frustum(); /** * switch between multiple landmarks */ private landmarks: Landmark[] = []; private landmarkAnimationID: number | undefined; public clone(): Camera { const camera = new Camera(); camera.setType(this.type, undefined); camera.interactor = this.interactor; return camera; } public getProjectionMode() { return this.projectionMode; } public getPerspective() { return this.perspective; } public getFrustum() { return this.frustum; } public getPosition() { return this.position; } public setType( type: CAMERA_TYPE, trackingMode: CAMERA_TRACKING_MODE | undefined, ) { this.type = type; if (this.type === CAMERA_TYPE.EXPLORING) { this.setWorldRotation(true); } else { this.setWorldRotation(false); } this._getAngles(); if (this.type === CAMERA_TYPE.TRACKING && trackingMode !== undefined) { this.setTrackingMode(trackingMode); } return this; } public setProjectionMode(projectionMode: CAMERA_PROJECTION_MODE) { this.projectionMode = projectionMode; return this; } public setTrackingMode(trackingMode: CAMERA_TRACKING_MODE) { if (this.type !== CAMERA_TYPE.TRACKING) { throw new Error( 'Impossible to set a tracking mode if the camera is not of tracking type', ); } this.trackingMode = trackingMode; return this; } /** * If flag is true, it reverses the azimuth and elevation angles. * Subsequent calls to rotate, setAzimuth, setElevation, * changeAzimuth or changeElevation will cause the inverted effect. * setRoll or changeRoll is not affected by this method. * * This inversion is useful when one wants to simulate that the world * is moving, instead of the camera. * * By default the camera angles are not reversed. * @param {Boolean} flag the boolean flag to reverse the angles. */ public setWorldRotation(flag: boolean) { this.rotateWorld = flag; this._getAngles(); } /** * 计算 MV 矩阵,为相机矩阵的逆矩阵 */ public getViewTransform(): mat4 { return mat4.invert(mat4.create(), this.matrix)!; } public getWorldTransform(): mat4 { return this.matrix; } /** * 设置相机矩阵 */ public setMatrix(matrix: mat4) { this.matrix = matrix; this._update(); return this; } public setAspect(aspect: number) { this.setPerspective(this.near, this.far, this.fov, aspect); return this; } /** * Sets an offset in a larger frustum, used in PixelPicking */ public setViewOffset( fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number, ) { this.aspect = fullWidth / fullHeight; if (this.view === undefined) { this.view = { enabled: true, fullWidth: 1, fullHeight: 1, offsetX: 0, offsetY: 0, width: 1, height: 1, }; } this.view.enabled = true; this.view.fullWidth = fullWidth; this.view.fullHeight = fullHeight; this.view.offsetX = x; this.view.offsetY = y; this.view.width = width; this.view.height = height; if (this.projectionMode === CAMERA_PROJECTION_MODE.PERSPECTIVE) { this.setPerspective(this.near, this.far, this.fov, this.aspect); } else { this.setOrthographic( this.left, this.rright, this.top, this.bottom, this.near, this.far, ); } return this; } public clearViewOffset() { if (this.view !== undefined) { this.view.enabled = false; } if (this.projectionMode === CAMERA_PROJECTION_MODE.PERSPECTIVE) { this.setPerspective(this.near, this.far, this.fov, this.aspect); } else { this.setOrthographic( this.left, this.rright, this.top, this.bottom, this.near, this.far, ); } return this; } public setPerspective( near: number, far: number, fov: number, aspect: number, ) { this.projectionMode = CAMERA_PROJECTION_MODE.PERSPECTIVE; this.fov = fov; this.near = near; this.far = far; this.aspect = aspect; mat4.perspective( this.perspective, this.fov * DEG_2_RAD, this.aspect, this.near, this.far, ); return this; } public setOrthographic( l: number, r: number, t: number, b: number, near: number, far: number, ) { this.projectionMode = CAMERA_PROJECTION_MODE.ORTHOGRAPHIC; this.rright = r; this.left = l; this.top = t; this.bottom = b; this.near = near; this.far = far; const dx = (this.rright - this.left) / (2 * this.zoom); const dy = (this.top - this.bottom) / (2 * this.zoom); const cx = (this.rright + this.left) / 2; const cy = (this.top + this.bottom) / 2; let left = cx - dx; let right = cx + dx; let top = cy + dy; let bottom = cy - dy; if (this.view !== undefined && this.view.enabled) { const scaleW = (this.rright - this.left) / this.view.fullWidth / this.zoom; const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; left += scaleW * this.view.offsetX; right = left + scaleW * this.view.width; top -= scaleH * this.view.offsetY; bottom = top - scaleH * this.view.height; } mat4.ortho(this.perspective, left, right, top, bottom, near, far); return this; } /** * 设置相机位置 */ public setPosition(x: number | vec3, y?: number, z?: number) { this._setPosition(x, y, z); this.setFocalPoint(this.focalPoint); return this; } /** * 设置视点位置 */ public setFocalPoint(x: number | vec3, y?: number, z?: number) { let up = vec3.fromValues(0, 1, 0); this.focalPoint = createVec3(x, y, z); if (this.trackingMode === CAMERA_TRACKING_MODE.CINEMATIC) { const d = vec3.subtract(vec3.create(), this.focalPoint, this.position); x = d[0]; y = d[1] as number; z = d[2] as number; const r = vec3.length(d); const el = Math.asin(y / r) * RAD_2_DEG; const az = 90 + Math.atan2(z, x) * RAD_2_DEG; const m = mat4.create(); mat4.rotateY(m, m, az * DEG_2_RAD); mat4.rotateX(m, m, el * DEG_2_RAD); up = vec3.transformMat4(vec3.create(), [0, 1, 0], m); } mat4.invert( this.matrix, mat4.lookAt(mat4.create(), this.position, this.focalPoint, up), ); this._getAxes(); this._getDistance(); this._getAngles(); return this; } /** * 固定当前视点,按指定距离放置相机 */ public setDistance(d: number) { if (this.distance === d || d < 0) { return; } this.distance = d; if (this.distance < 0.0002) { this.distance = 0.0002; } this.dollyingStep = this.distance / 100; const pos = vec3.create(); d = this.distance; const n = this.forward; const f = this.focalPoint; pos[0] = d * n[0] + f[0]; pos[1] = d * n[1] + f[1]; pos[2] = d * n[2] + f[2]; this._setPosition(pos); return this; } public setMaxDistance(d: number) { this.maxDistance = d; return this; } public setMinDistance(d: number) { this.minDistance = d; return this; } /** * Changes the initial azimuth of the camera */ public changeAzimuth(az: number) { this.setAzimuth(this.azimuth + az); return this; } /** * Changes the initial elevation of the camera */ public changeElevation(el: number) { this.setElevation(this.elevation + el); return this; } /** * Changes the initial roll of the camera */ public changeRoll(rl: number) { this.setRoll(this.roll + rl); return this; } /** * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置 * @param {Number} el the azimuth in degrees */ public setAzimuth(az: number) { this.azimuth = getAngle(az); this.computeMatrix(); this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } return this; } public getAzimuth() { return this.azimuth; } /** * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置 * @param {Number} el the elevation in degrees */ public setElevation(el: number) { this.elevation = getAngle(el); this.computeMatrix(); this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } return this; } /** * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置 * @param {Number} angle the roll angle */ public setRoll(angle: number) { this.roll = getAngle(angle); this.computeMatrix(); this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } return this; } /** * Changes the azimuth and elevation with respect to the current camera axes * @param {Number} azimuth the relative azimuth * @param {Number} elevation the relative elevation * @param {Number} roll the relative roll */ public rotate(azimuth: number, elevation: number, roll: number) { if (this.type === CAMERA_TYPE.EXPLORING) { azimuth = getAngle(azimuth); elevation = getAngle(elevation); roll = getAngle(roll); const rotX = quat.setAxisAngle( quat.create(), [1, 0, 0], (this.rotateWorld ? 1 : -1) * elevation * DEG_2_RAD, ); const rotY = quat.setAxisAngle( quat.create(), [0, 1, 0], (this.rotateWorld ? 1 : -1) * azimuth * DEG_2_RAD, ); const rotZ = quat.setAxisAngle( quat.create(), [0, 0, 1], roll * DEG_2_RAD, ); let rotQ = quat.multiply(quat.create(), rotY, rotX); rotQ = quat.multiply(quat.create(), rotQ, rotZ); const rotMatrix = mat4.fromQuat(mat4.create(), rotQ); mat4.translate(this.matrix, this.matrix, [0, 0, -this.distance]); mat4.multiply(this.matrix, this.matrix, rotMatrix); mat4.translate(this.matrix, this.matrix, [0, 0, this.distance]); } else { if (Math.abs(this.elevation + elevation) > 90) { return; } this.relElevation = getAngle(elevation); this.relAzimuth = getAngle(azimuth); this.relRoll = getAngle(roll); this.elevation += this.relElevation; this.azimuth += this.relAzimuth; this.roll += this.relRoll; this.computeMatrix(); } this._getAxes(); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { this._getPosition(); } else if (this.type === CAMERA_TYPE.TRACKING) { this._getFocalPoint(); } this._update(); return this; } /** * 沿水平(right) & 垂直(up)平移相机 */ public pan(tx: number, ty: number) { const coords = createVec3(tx, ty, 0); const pos = vec3.clone(this.position); vec3.add(pos, pos, vec3.scale(vec3.create(), this.right, coords[0])); vec3.add(pos, pos, vec3.scale(vec3.create(), this.up, coords[1])); this._setPosition(pos); return this; } /** * 沿 n 轴移动,当距离视点远时移动速度较快,离视点越近速度越慢 */ public dolly(value: number) { const n = this.forward; const pos = vec3.clone(this.position); let step = value * this.dollyingStep; const updatedDistance = this.distance + value * this.dollyingStep; // 限制视点距离范围 step = Math.max(Math.min(updatedDistance, this.maxDistance), this.minDistance) - this.distance; pos[0] += step * n[0]; pos[1] += step * n[1]; pos[2] += step * n[2]; this._setPosition(pos); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { // 重新计算视点距离 this._getDistance(); } else if (this.type === CAMERA_TYPE.TRACKING) { // 保持视距,移动视点位置 vec3.add(this.focalPoint, pos, this.distanceVector); } return this; } public createLandmark( name: string, params: { position: vec3; focalPoint: vec3; roll?: number; }, ): Landmark { const camera = this.clone(); camera.setPosition(params.position); camera.setFocalPoint(params.focalPoint); if (params.roll !== undefined) { camera.setRoll(params.roll); } const landmark = new Landmark(name, camera); this.landmarks.push(landmark); return landmark; } public setLandmark(name: string) { const landmark = new Landmark(name, this); this.landmarks.push(landmark); return this; } public gotoLandmark(name: string, duration: number = 1000) { const landmark = this.landmarks.find((l) => l.name === name); if (landmark) { if (duration === 0) { landmark.retrieve(this); return; } if (this.landmarkAnimationID !== undefined) { window.cancelAnimationFrame(this.landmarkAnimationID); } // TODO: do not process events during animation this.interactor.disconnect(); const destPosition = landmark.getPosition(); const destFocalPoint = landmark.getFocalPoint(); const destRoll = landmark.getRoll(); let timeStart: number | undefined; const animate = (timestamp: number) => { if (timeStart === undefined) { timeStart = timestamp; } const elapsed = timestamp - timeStart; // TODO: use better ease function const t = (1 - Math.cos((elapsed / duration) * Math.PI)) / 2; const interFocalPoint = vec3.create(); const interPosition = vec3.create(); let interRoll = 0; vec3.lerp(interFocalPoint, this.focalPoint, destFocalPoint, t); vec3.lerp(interPosition, this.position, destPosition, t); interRoll = this.roll * (1 - t) + destRoll * t; this.setFocalPoint(interFocalPoint); this.setPosition(interPosition); this.setRoll(interRoll); this.computeMatrix(); const dist = vec3.dist(interFocalPoint, destFocalPoint) + vec3.dist(interPosition, destPosition); if (dist > 0.01) { // } else { this.setFocalPoint(interFocalPoint); this.setPosition(interPosition); this.setRoll(interRoll); this.computeMatrix(); this.interactor.connect(); return; } if (elapsed < duration) { this.landmarkAnimationID = window.requestAnimationFrame(animate); } }; window.requestAnimationFrame(animate); } } /** * 根据相机矩阵重新计算各种相机参数 */ private _update() { this._getAxes(); this._getPosition(); this._getDistance(); this._getAngles(); } /** * 计算相机矩阵 */ private computeMatrix() { let rotX; let rotY; // 使用四元数描述 3D 旋转 // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html const rotZ = quat.setAxisAngle( quat.create(), [0, 0, 1], this.roll * DEG_2_RAD, ); mat4.identity(this.matrix); // only consider HCS for EXPLORING and ORBITING cameras rotX = quat.setAxisAngle( quat.create(), [1, 0, 0], ((this.rotateWorld && this.type !== CAMERA_TYPE.TRACKING) || this.type === CAMERA_TYPE.TRACKING ? 1 : -1) * this.elevation * DEG_2_RAD, ); rotY = quat.setAxisAngle( quat.create(), [0, 1, 0], ((this.rotateWorld && this.type !== CAMERA_TYPE.TRACKING) || this.type === CAMERA_TYPE.TRACKING ? 1 : -1) * this.azimuth * DEG_2_RAD, ); let rotQ = quat.multiply(quat.create(), rotY, rotX); rotQ = quat.multiply(quat.create(), rotQ, rotZ); const rotMatrix = mat4.fromQuat(mat4.create(), rotQ); if ( this.type === CAMERA_TYPE.ORBITING || this.type === CAMERA_TYPE.EXPLORING ) { mat4.translate(this.matrix, this.matrix, this.focalPoint); mat4.multiply(this.matrix, this.matrix, rotMatrix); mat4.translate(this.matrix, this.matrix, [0, 0, this.distance]); } else if (this.type === CAMERA_TYPE.TRACKING) { mat4.translate(this.matrix, this.matrix, this.position); mat4.multiply(this.matrix, this.matrix, rotMatrix); } } /** * Sets the camera position in the camera matrix */ private _setPosition(x: number | vec3, y?: number, z?: number) { this.position = createVec3(x, y, z); const m = this.matrix; m[12] = this.position[0]; m[13] = this.position[1]; m[14] = this.position[2]; m[15] = 1; } /** * Recalculates axes based on the current matrix */ private _getAxes() { vec3.copy( this.right, createVec3(vec4.transformMat4(vec4.create(), [1, 0, 0, 0], this.matrix)), ); vec3.copy( this.up, createVec3(vec4.transformMat4(vec4.create(), [0, 1, 0, 0], this.matrix)), ); vec3.copy( this.forward, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 1, 0], this.matrix)), ); vec3.normalize(this.right, this.right); vec3.normalize(this.up, this.up); vec3.normalize(this.forward, this.forward); } /** * Recalculates euler angles based on the current state */ private _getAngles() { // Recalculates angles const x = this.distanceVector[0]; const y = this.distanceVector[1]; const z = this.distanceVector[2]; const r = vec3.length(this.distanceVector); // FAST FAIL: If there is no distance we cannot compute angles if (r === 0) { this.elevation = 0; this.azimuth = 0; return; } if (this.type === CAMERA_TYPE.TRACKING) { this.elevation = Math.asin(y / r) * RAD_2_DEG; this.azimuth = Math.atan2(-x, -z) * RAD_2_DEG; } else { if (this.rotateWorld) { this.elevation = Math.asin(y / r) * RAD_2_DEG; this.azimuth = Math.atan2(-x, -z) * RAD_2_DEG; } else { this.elevation = -Math.asin(y / r) * RAD_2_DEG; this.azimuth = -Math.atan2(-x, -z) * RAD_2_DEG; } } } /** * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化 */ private _getPosition() { vec3.copy( this.position, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 0, 1], this.matrix)), ); // 相机位置变化,需要重新计算视距 this._getDistance(); } /** * 重新计算视点,只有 TRACKING 模式视点才会发生变化 */ private _getFocalPoint() { vec3.transformMat3( this.distanceVector, [0, 0, -this.distance], mat3.fromMat4(mat3.create(), this.matrix), ); vec3.add(this.focalPoint, this.position, this.distanceVector); // 视点变化,需要重新计算视距 this._getDistance(); } /** * 重新计算视距 */ private _getDistance() { this.distanceVector = vec3.subtract( vec3.create(), this.focalPoint, this.position, ); this.distance = vec3.length(this.distanceVector); this.dollyingStep = this.distance / 100; } }
the_stack
import * as React from 'react'; import { View, TouchableOpacity, Text, ScrollView, TextInput } from 'react-native'; import { HmsLocalNotification } from '@hmscore/react-native-hms-push'; const defaultNotification = { [HmsLocalNotification.Attr.title]: 'Notification Title', [HmsLocalNotification.Attr.message]: 'Notification Message', // (required) [HmsLocalNotification.Attr.ticker]: 'Optional Ticker', [HmsLocalNotification.Attr.showWhen]: true, // [HmsLocalNotification.Attr.largeIconUrl]: 'https://developer.huawei.com/Enexport/sites/default/images/en/Develop/hms/push/push2-tuidedao.png', // [HmsLocalNotification.Attr.largeIcon]: 'ic_launcher', [HmsLocalNotification.Attr.smallIcon]: 'ic_notification', [HmsLocalNotification.Attr.bigText]: 'This is a bigText', [HmsLocalNotification.Attr.subText]: 'This is a subText', [HmsLocalNotification.Attr.color]: 'white', [HmsLocalNotification.Attr.vibrate]: false, [HmsLocalNotification.Attr.vibrateDuration]: 1000, [HmsLocalNotification.Attr.tag]: 'hms_tag', [HmsLocalNotification.Attr.groupSummary]: false, [HmsLocalNotification.Attr.ongoing]: false, [HmsLocalNotification.Attr.importance]: HmsLocalNotification.Importance.max, [HmsLocalNotification.Attr.dontNotifyInForeground]: false, [HmsLocalNotification.Attr.autoCancel]: false, // for Custom Actions, it should be false [HmsLocalNotification.Attr.actions]: '["Yes", "No"]', [HmsLocalNotification.Attr.invokeApp]: false, // [HmsLocalNotification.Attr.channelId]: 'huawei-hms-rn-push-channel-id', // Please read the documentation before using this param }; interface State { title: string; message: string; bigText: string; subText: string; tag: string | undefined; [k: string]: unknown; } export default class App extends React.Component<{}, State> { constructor(props: {}) { super(props); this.state = { title: 'HMS Push', message: 'This is Local Notification', bigText: 'This is a bigText', subText: 'This is a subText', tag: undefined, }; } changeNotificationValue(key: string, data: unknown) { this.setState({ [key]: data, }); } localNotificationScheduled() { HmsLocalNotification.localNotificationSchedule({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, [HmsLocalNotification.Attr.fireDate]: new Date(Date.now() + 60 * 1000).getTime(), // in 1 min [HmsLocalNotification.Attr.allowWhileIdle]: true, }) .then(result => { console.log('LocalNotification Scheduled', result); }) .catch(err => { console.log('[LocalNotification Scheduled] Error/Exception: ' + JSON.stringify(err)); }); } localNotification() { HmsLocalNotification.localNotification({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, }) .then(result => { console.log('LocalNotification Default', result); }) .catch(err => { console.log('[LocalNotification Default] Error/Exception: ' + JSON.stringify(err)); }); } localNotificationVibrate() { HmsLocalNotification.localNotification({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, [HmsLocalNotification.Attr.vibrate]: true, [HmsLocalNotification.Attr.vibrateDuration]: 5000, }) .then(result => { console.log('LocalNotification Vibrate', result); }) .catch(err => { console.log('[LocalNotification Vibrate] Error/Exception: ' + JSON.stringify(err)); }); } localNotificationRepeat() { HmsLocalNotification.localNotification({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, [HmsLocalNotification.Attr.repeatType]: HmsLocalNotification.RepeatType.minute, }) .then(result => { console.log('LocalNotification Repeat', result); }) .catch(err => { console.log('[LocalNotification Repeat] Error/Exception: ' + JSON.stringify(err)); }); } localNotificationSound() { HmsLocalNotification.localNotification({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, [HmsLocalNotification.Attr.playSound]: true, [HmsLocalNotification.Attr.soundName]: 'huawei_bounce.mp3', }) .then(result => { console.log('LocalNotification Sound', result); }) .catch(err => { console.log('[LocalNotification Sound] Error/Exception: ' + JSON.stringify(err)); }); } localNotificationPriority() { HmsLocalNotification.localNotification({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, [HmsLocalNotification.Attr.priority]: HmsLocalNotification.Priority.max, }) .then(result => { console.log('LocalNotification Priority', result); }) .catch(err => { console.log('[LocalNotification Priority] Error/Exception: ' + JSON.stringify(err)); }); } localNotificationOngoing() { HmsLocalNotification.localNotification({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, [HmsLocalNotification.Attr.ongoing]: true, }) .then(result => { console.log('LocalNotification Ongoing', result); }) .catch(err => { console.log('[LocalNotification Ongoing] Error/Exception: ' + JSON.stringify(err)); }); } localNotificationBigImage() { HmsLocalNotification.localNotification({ ...defaultNotification, [HmsLocalNotification.Attr.title]: this.state.title, [HmsLocalNotification.Attr.message]: this.state.message, [HmsLocalNotification.Attr.bigText]: this.state.bigText, [HmsLocalNotification.Attr.subText]: this.state.subText, [HmsLocalNotification.Attr.tag]: this.state.tag, [HmsLocalNotification.Attr.bigPictureUrl]: 'https://www-file.huawei.com/-/media/corp/home/image/logo_400x200.png', }) .then(result => { console.log('LocalNotification BigImage', result); }) .catch(err => { console.log('[LocalNotification BigImage] Error/Exception: ' + JSON.stringify(err)); }); } render() { return ( <ScrollView> <View> <Text>Title :</Text> <TextInput value={this.state.title} placeholder="title" onChangeText={e => this.changeNotificationValue('title', e)} /> <TextInput value={this.state.tag} placeholder="tag" onChangeText={e => this.changeNotificationValue('tag', e)} /> </View> <View> <Text>Message :</Text> <TextInput value={this.state.message} placeholder="message" onChangeText={e => this.changeNotificationValue('message', e)} /> </View> <View> <Text>BigText :</Text> <TextInput value={this.state.bigText} placeholder="bigText" onChangeText={e => this.changeNotificationValue('bigText', e)} /> </View> <View> <Text>SubText :</Text> <TextInput value={this.state.subText} placeholder="subText" onChangeText={e => this.changeNotificationValue('subText', e)} /> </View> <View> <TouchableOpacity onPress={() => this.localNotification()}> <Text>Local Notification (Default)</Text> </TouchableOpacity> </View> <View> <TouchableOpacity onPress={() => this.localNotificationOngoing()}> <Text>+ Ongoing</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.localNotificationSound()}> <Text>+ Sound</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.localNotificationVibrate()}> <Text>+ Vibrate</Text> </TouchableOpacity> </View> <View> <TouchableOpacity onPress={() => this.localNotificationBigImage()}> <Text>+ BigImage</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.localNotificationRepeat()}> <Text>+ Repeat</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.localNotificationScheduled()}> <Text>+ Scheduled</Text> </TouchableOpacity> </View> <View> <TouchableOpacity onPress={() => { HmsLocalNotification.cancelAllNotifications() .then(result => { console.log('cancelAllNotifications', result); }) .catch(err => { console.log('[cancelAllNotifications] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>cancelAllNotifications</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { HmsLocalNotification.getNotifications() .then(result => { console.log('getNotifications', result); }) .catch(err => { console.log('[getNotifications] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>getNotifications</Text> </TouchableOpacity> </View> <View> <TouchableOpacity onPress={() => { HmsLocalNotification.cancelScheduledNotifications() .then(result => { console.log('cancelScheduledNotifications', result); }) .catch(err => { console.log( '[cancelScheduledNotifications] Error/Exception: ' + JSON.stringify(err), ); }); }} > <Text>cancelScheduledNotifications</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { HmsLocalNotification.getScheduledNotifications() .then(result => { console.log('getScheduledNotifications', result); }) .catch(err => { console.log('[getScheduledNotifications] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>getScheduledLocalNotifications</Text> </TouchableOpacity> </View> <View> <TouchableOpacity onPress={() => { HmsLocalNotification.cancelNotificationsWithTag('tag') .then(result => { console.log('cancelNotificationsWithTag', result); }) .catch(err => { console.log('[cancelNotificationsWithTag] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>cancelNotificationsWithTag(tag)</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { HmsLocalNotification.getChannels() .then(result => { console.log('getChannels', result); }) .catch(err => { console.log('[getChannels] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>getChannels</Text> </TouchableOpacity> </View> <View> <TouchableOpacity onPress={() => { HmsLocalNotification.cancelNotifications() .then(result => { console.log('cancelNotifications', result); }) .catch(err => { console.log('[cancelNotifications] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>cancelNotifications</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { HmsLocalNotification.deleteChannel('hms-channel-custom') .then(result => { console.log('deleteChannel', result); }) .catch(err => { console.log('[deleteChannel] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>deleteChannel</Text> </TouchableOpacity> </View> <View> <TouchableOpacity onPress={() => { HmsLocalNotification.channelBlocked('huawei-hms-rn-push-channel-id') .then(result => { console.log('channelBlocked', result); }) .catch(err => { console.log('[channelBlocked] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>channelBlocked</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { HmsLocalNotification.channelExists('huawei-hms-rn-push-channel-id') .then(result => { console.log('channelExists', result); }) .catch(err => { console.log('[channelExists] Error/Exception: ' + JSON.stringify(err)); }); }} > <Text>channelExists</Text> </TouchableOpacity> </View> </ScrollView> ); } }
the_stack
import React, { PureComponent } from 'react'; import cls from 'classnames'; import PropTypes from 'prop-types'; import { cssClasses, strings } from '@douyinfe/semi-foundation/cascader/constants'; import isEnterPress from '@douyinfe/semi-foundation/utils/isEnterPress'; import { includes } from 'lodash'; import ConfigContext, { ContextValue } from '../configProvider/context'; import LocaleConsumer from '../locale/localeConsumer'; import { IconChevronRight, IconTick } from '@douyinfe/semi-icons'; import { Locale } from '../locale/interface'; import Spin from '../spin'; import Checkbox, { CheckboxEvent } from '../checkbox'; import { BasicCascaderData, BasicEntity, ShowNextType, BasicData } from '@douyinfe/semi-foundation/cascader/foundation'; export interface CascaderData extends BasicCascaderData { label: React.ReactNode; } export interface Entity extends BasicEntity { /* children list */ children?: Array<Entity>; /* treedata */ data: CascaderData; /* parent data */ parent?: Entity; } export interface Entities { [idx: string]: Entity; } export interface Data extends BasicData { data: CascaderData; searchText: React.ReactNode[]; } export interface CascaderItemProps { activeKeys: Set<string>; selectedKeys: Set<string>; loadedKeys: Set<string>; loadingKeys: Set<string>; onItemClick: (e: React.MouseEvent | React.KeyboardEvent, item: Entity | Data) => void; onItemHover: (e: React.MouseEvent, item: Entity) => void; showNext: ShowNextType; onItemCheckboxClick: (item: Entity | Data) => void; onListScroll: (e: React.UIEvent<HTMLUListElement, UIEvent>, ind: number) => void; searchable: boolean; keyword: string; empty: boolean; emptyContent: React.ReactNode; loadData: (selectOptions: CascaderData[]) => Promise<void>; data: Array<Data | Entity>; separator: string; multiple: boolean; checkedKeys: Set<string>; halfCheckedKeys: Set<string>; } const prefixcls = cssClasses.PREFIX_OPTION; export default class Item extends PureComponent<CascaderItemProps> { static contextType = ConfigContext; static propTypes = { data: PropTypes.array, emptyContent: PropTypes.node, searchable: PropTypes.bool, onItemClick: PropTypes.func, onItemHover: PropTypes.func, multiple: PropTypes.bool, showNext: PropTypes.oneOf([strings.SHOW_NEXT_BY_CLICK, strings.SHOW_NEXT_BY_HOVER]), checkedKeys: PropTypes.object, halfCheckedKeys: PropTypes.object, onItemCheckboxClick: PropTypes.func, separator: PropTypes.string, keyword: PropTypes.string }; static defaultProps = { empty: false, }; context: ContextValue; onClick = (e: React.MouseEvent | React.KeyboardEvent, item: Entity | Data) => { const { onItemClick } = this.props; if (item.data.disabled || ('disabled' in item && item.disabled)) { return; } onItemClick(e, item); }; /** * A11y: simulate item click */ handleItemEnterPress = (keyboardEvent: React.KeyboardEvent, item: Entity | Data) => { if (isEnterPress(keyboardEvent)) { this.onClick(keyboardEvent, item); } } onHover = (e: React.MouseEvent, item: Entity) => { const { showNext, onItemHover } = this.props; if (item.data.disabled) { return; } if (showNext === strings.SHOW_NEXT_BY_HOVER) { onItemHover(e, item); } }; onCheckboxChange = (e: CheckboxEvent, item: Entity | Data) => { const { onItemCheckboxClick } = this.props; // Prevent Checkbox's click event bubbling to trigger the li click event e.stopPropagation(); if (e.nativeEvent && typeof e.nativeEvent.stopImmediatePropagation === 'function') { e.nativeEvent.stopImmediatePropagation(); } onItemCheckboxClick(item); }; getItemStatus = (key: string) => { const { activeKeys, selectedKeys, loadedKeys, loadingKeys } = this.props; const state = { active: false, selected: false, loading: false }; if (activeKeys.has(key)) { state.active = true; } if (selectedKeys.has(key)) { state.selected = true; } if (loadingKeys.has(key) && !loadedKeys.has(key)) { state.loading = true; } return state; }; renderIcon = (type: string) => { switch (type) { case 'child': return (<IconChevronRight className={`${prefixcls}-icon ${prefixcls}-icon-expand`} />); case 'tick': return (<IconTick className={`${prefixcls}-icon ${prefixcls}-icon-active`} />); case 'loading': return <Spin wrapperClassName={`${prefixcls}-spin-icon`} />; case 'empty': return (<span aria-hidden={true} className={`${prefixcls}-icon ${prefixcls}-icon-empty`} />); default: return null; } }; highlight = (searchText: React.ReactNode[]) => { const content: React.ReactNode[] = []; const { keyword, separator } = this.props; searchText.forEach((item, idx) => { if (typeof item === 'string' && includes(item, keyword)) { item.split(keyword).forEach((node, index) => { if (index > 0) { content.push( <span className={`${prefixcls}-label-highlight`} key={`${index}-${idx}`}> {keyword} </span> ); } content.push(node); }); } else { content.push(item); } if (idx !== searchText.length - 1) { content.push(separator); } }); return content; }; renderFlattenOption = (data: Data[]) => { const { multiple, checkedKeys, halfCheckedKeys } = this.props; const content = ( <ul className={`${prefixcls}-list`} key={'flatten-list'}> {data.map(item => { const { searchText, key, disabled } = item; const className = cls(prefixcls, { [`${prefixcls}-flatten`]: true, [`${prefixcls}-disabled`]: disabled }); return ( <li role='menuitem' className={className} key={key} onClick={e => { this.onClick(e, item); }} onKeyPress={e => this.handleItemEnterPress(e, item)} > <span className={`${prefixcls}-label`}> {!multiple && this.renderIcon('empty')} {multiple && ( <Checkbox onChange={(e: CheckboxEvent) => this.onCheckboxChange(e, item)} disabled={disabled} indeterminate={halfCheckedKeys.has(item.key)} checked={checkedKeys.has(item.key)} className={`${prefixcls}-label-checkbox`} /> )} {this.highlight(searchText)} </span> </li> ); })} </ul> ); return content; }; renderItem(renderData: Array<Entity>, content: Array<React.ReactNode> = []) { const { multiple, checkedKeys, halfCheckedKeys } = this.props; let showChildItem: Entity; const ind = content.length; content.push( <ul role='menu' className={`${prefixcls}-list`} key={renderData[0].key} onScroll={e => this.props.onListScroll(e, ind)}> {renderData.map(item => { const { data, key, parentKey } = item; const { children, label, disabled, isLeaf } = data; const { active, selected, loading } = this.getItemStatus(key); const hasChild = Boolean(children) && children.length; const showExpand = hasChild || (this.props.loadData && !isLeaf); if (active && hasChild) { showChildItem = item; } const className = cls(prefixcls, { [`${prefixcls}-active`]: active && !selected, [`${prefixcls}-select`]: selected && !multiple, [`${prefixcls}-disabled`]: disabled }); const otherAriaProps = parentKey ? { ['aria-owns']: `cascaderItem-${parentKey}` } : {}; return ( <li role='menuitem' id={`cascaderItem-${key}`} aria-expanded={active} aria-haspopup={Boolean(showExpand)} aria-disabled={disabled} {...otherAriaProps} className={className} key={key} onClick={e => { this.onClick(e, item); }} onKeyPress={e => this.handleItemEnterPress(e, item)} onMouseEnter={e => { this.onHover(e, item); }} > <span className={`${prefixcls}-label`}> {selected && !multiple && this.renderIcon('tick')} {!selected && !multiple && this.renderIcon('empty')} {multiple && ( <Checkbox onChange={(e: CheckboxEvent) => this.onCheckboxChange(e, item)} disabled={disabled} indeterminate={halfCheckedKeys.has(item.key)} checked={checkedKeys.has(item.key)} className={`${prefixcls}-label-checkbox`} /> )} <span>{label}</span> </span> {showExpand ? this.renderIcon(loading ? 'loading' : 'child') : null} </li> ); })} </ul> ); if (showChildItem) { content.concat(this.renderItem(showChildItem.children, content)); } return content; } renderEmpty() { const { emptyContent } = this.props; return ( <LocaleConsumer componentName="Cascader"> {(locale: Locale['Cascader']) => ( <ul className={`${prefixcls} ${prefixcls}-empty`} key={'empty-list'}> <span className={`${prefixcls}-label`}> {emptyContent || locale.emptyText} </span> </ul> )} </LocaleConsumer> ); } render() { const { data, searchable } = this.props; const { direction } = this.context; const isEmpty = !data || !data.length; let content; const listsCls = cls({ [`${prefixcls}-lists`]: true, [`${prefixcls}-lists-rtl`]: direction === 'rtl', [`${prefixcls}-lists-empty`]: isEmpty, }); if (isEmpty) { content = this.renderEmpty(); } else { content = searchable ? this.renderFlattenOption(data as Data[]) : this.renderItem(data as Entity[]); } return ( <div className={listsCls}> {content} </div> ); } }
the_stack
import _ from 'lodash' import { Element, ObjectType, isContainerType, MapType, ListType, InstanceElement, CORE_ANNOTATIONS, Values, isAdditionOrModificationChange, isInstanceChange, getChangeElement, Change, isMapType, isListType, isInstanceElement, createRefToElmWithValue, getDeepInnerType, isObjectType, } from '@salto-io/adapter-api' import { collections } from '@salto-io/lowerdash' import { naclCase, applyFunctionToChangeData } from '@salto-io/adapter-utils' import { logger } from '@salto-io/logging' import { FilterCreator } from '../filter' import { API_NAME_SEPARATOR, PROFILE_METADATA_TYPE, BUSINESS_HOURS_METADATA_TYPE } from '../constants' import { metadataType } from '../transformers/transformer' const { awu } = collections.asynciterable const { makeArray } = collections.array const log = logger(module) type MapKeyFunc = (value: Values) => string type MapDef = { // the name of the field whose value should be used to generate the map key key: string // when true, the map will have two levels instead of one nested?: boolean // use lists as map values, in order to allow multiple values under the same map key mapToList?: boolean } /** * Convert a string value into the map index keys. * Note: Reference expressions are not supported yet (the resolved value is not populated in fetch) * so this filter has to run before any filter adding references on the objects with the specified * metadata types (e.g Profile). */ export const defaultMapper = (val: string): string[] => ( val.split(API_NAME_SEPARATOR).map(v => naclCase(v)) ) const BUSINESS_HOURS_MAP_FIELD_DEF: Record<string, MapDef> = { // One-level maps businessHours: { key: 'name' }, } export const PROFILE_MAP_FIELD_DEF: Record<string, MapDef> = { // One-level maps applicationVisibilities: { key: 'application' }, classAccesses: { key: 'apexClass' }, customMetadataTypeAccesses: { key: 'name' }, customPermissions: { key: 'name' }, customSettingAccesses: { key: 'name' }, externalDataSourceAccesses: { key: 'externalDataSource' }, flowAccesses: { key: 'flow' }, objectPermissions: { key: 'object' }, pageAccesses: { key: 'apexPage' }, userPermissions: { key: 'name' }, // Non-unique maps (multiple values can have the same key) categoryGroupVisibilities: { key: 'dataCategoryGroup', mapToList: true }, layoutAssignments: { key: 'layout', mapToList: true }, // Two-level maps fieldPermissions: { key: 'field', nested: true }, fieldLevelSecurities: { key: 'field', nested: true }, // only available in API version 22.0 and earlier recordTypeVisibilities: { key: 'recordType', nested: true }, } export const metadataTypeToFieldToMapDef: Record<string, Record<string, MapDef>> = { [BUSINESS_HOURS_METADATA_TYPE]: BUSINESS_HOURS_MAP_FIELD_DEF, [PROFILE_METADATA_TYPE]: PROFILE_MAP_FIELD_DEF, } /** * Convert the specified instance fields into maps. * Choose between unique maps and lists based on each field's conversion definition. If a field * should use a unique map but fails due to conflicts, convert it to a list map, and include it * in the returned list so that it can be converted across the board. * * @param instance The instance to modify * @param instanceMapFieldDef The definitions of the fields to covert * @returns The list of fields that were converted to non-unique due to duplicates */ const convertArraysToMaps = ( instance: InstanceElement, instanceMapFieldDef: Record<string, MapDef>, ): string[] => { // fields that were intended to be unique, but have multiple values under to the same map key const nonUniqueMapFields: string[] = [] const convertField = ( values: Values[], keyFunc: MapKeyFunc, useList: boolean, fieldName: string, ): Values => { if (!useList) { const res = _.keyBy(values, item => keyFunc(item)) if (Object.keys(res).length === values.length) { return res } nonUniqueMapFields.push(fieldName) } return _.groupBy(values, item => keyFunc(item)) } Object.entries(instanceMapFieldDef).filter( ([fieldName]) => instance.value[fieldName] !== undefined ).forEach(([fieldName, mapDef]) => { if (mapDef.nested) { const firstLevelGroups = _.groupBy( makeArray(instance.value[fieldName]), item => defaultMapper(item[mapDef.key])[0] ) instance.value[fieldName] = _.mapValues( firstLevelGroups, firstLevelValues => convertField( firstLevelValues, item => defaultMapper(item[mapDef.key])[1], !!mapDef.mapToList, fieldName, ) ) } else { instance.value[fieldName] = convertField( makeArray(instance.value[fieldName]), item => defaultMapper(item[mapDef.key])[0], !!mapDef.mapToList, fieldName, ) } }) return nonUniqueMapFields } /** * Make sure all values in the specified non-unique fields are arrays. * * @param instance The instance instance to update * @param nonUniqueMapFields The list of fields to convert to arrays * @param instanceMapFieldDef The original field mapping definition */ const convertValuesToMapArrays = ( instance: InstanceElement, nonUniqueMapFields: string[], instanceMapFieldDef: Record<string, MapDef>, ): void => { nonUniqueMapFields.forEach(fieldName => { if (instanceMapFieldDef[fieldName]?.nested) { instance.value[fieldName] = _.mapValues( instance.value[fieldName], val => _.mapValues(val, makeArray), ) } else { instance.value[fieldName] = _.mapValues( instance.value[fieldName], makeArray, ) } }) } /** * Update the instance object type's fields to use maps. * * @param instanceType The instance to update * @param nonUniqueMapFields The list of fields to convert to arrays * @param instanceMapFieldDef The original field mapping definition */ const updateFieldTypes = async ( instanceType: ObjectType, nonUniqueMapFields: string[], instanceMapFieldDef: Record<string, MapDef>, ): Promise<void> => { await awu(Object.values(instanceType.fields)).filter( async f => instanceMapFieldDef[f.name] !== undefined && !isMapType(await f.getType()) ).forEach(async f => { const mapDef = instanceMapFieldDef[f.name] const fieldType = await f.getType() let innerType = isContainerType(fieldType) ? await fieldType.getInnerType() : fieldType if (mapDef.mapToList || nonUniqueMapFields.includes(f.name)) { innerType = new ListType(innerType) } if (mapDef.nested) { f.refType = createRefToElmWithValue(new MapType(new MapType(innerType))) } else { f.refType = createRefToElmWithValue(new MapType(innerType)) } // make the key field required const deepInnerType = await getDeepInnerType(innerType) if (isObjectType(deepInnerType)) { const keyFieldType = deepInnerType.fields[mapDef.key] if (!keyFieldType) { log.error('could not find key field %s for field %s', f.elemID.getFullName()) return } keyFieldType.annotations[CORE_ANNOTATIONS.REQUIRED] = true } }) } const convertInstanceFieldsToMaps = async ( instancesToConvert: InstanceElement[], instanceMapFieldDef: Record<string, MapDef>, ): Promise<string[]> => { const nonUniqueMapFields = _.uniq(instancesToConvert.flatMap( instance => convertArraysToMaps(instance, instanceMapFieldDef) )) if (nonUniqueMapFields.length > 0) { log.info(`Converting the following fields to non-unique maps: ${nonUniqueMapFields}, instances types are: ${ await awu(instancesToConvert).map(inst => metadataType(inst)).toArray() }`) instancesToConvert.forEach(instance => { convertValuesToMapArrays(instance, nonUniqueMapFields, instanceMapFieldDef) }) } return nonUniqueMapFields } /** * Convert instance field values from maps back to arrays before deploy. * * @param instanceChanges The instance changes to deploy * @param instanceMapFieldDef The definitions of the fields to covert */ const convertFieldsBackToLists = async ( instanceChanges: ReadonlyArray<Change<InstanceElement>>, instanceMapFieldDef: Record<string, MapDef>, ): Promise<void> => { const toVals = (values: Values): Values[] => Object.values(values).flat() const backToArrays = (instance: InstanceElement): InstanceElement => { Object.keys(instanceMapFieldDef).filter( fieldName => instance.value[fieldName] !== undefined ).forEach(fieldName => { if (Array.isArray(instance.value[fieldName])) { // should not happen return } if (instanceMapFieldDef[fieldName].nested) { // first convert the inner levels to arrays, then merge into one array instance.value[fieldName] = _.mapValues(instance.value[fieldName], toVals) } instance.value[fieldName] = toVals(instance.value[fieldName]) }) return instance } await awu(instanceChanges).forEach(instanceChange => applyFunctionToChangeData( instanceChange, backToArrays, )) } /** * Convert instance's field values from arrays back to maps after deploy. * * @param instanceChanges The instance changes to deploy * @param instanceMapFieldDef The definitions of the fields to covert */ const convertFieldsBackToMaps = ( instanceChanges: ReadonlyArray<Change<InstanceElement>>, instanceMapFieldDef: Record<string, MapDef>, ): void => { instanceChanges.forEach(instanceChange => applyFunctionToChangeData( instanceChange, instance => { convertArraysToMaps(instance, instanceMapFieldDef) return instance }, )) } /** * Convert fields from maps back to lists pre-deploy. * * @param instanceType The type to update * @param instanceMapFieldDef The field mapping definition */ const convertFieldTypesBackToLists = async ( instanceType: ObjectType, instanceMapFieldDef: Record<string, MapDef>, ): Promise<void> => { await awu(Object.values(instanceType.fields)).filter( async f => instanceMapFieldDef[f.name] !== undefined && isMapType(await f.getType()) ).forEach(async f => { const fieldType = await f.getType() if (isMapType(fieldType)) { f.refType = createRefToElmWithValue(await fieldType.getInnerType()) } // for nested fields (not using while to avoid edge cases) const newFieldType = await f.getType() if (isMapType(newFieldType)) { f.refType = createRefToElmWithValue(await newFieldType.getInnerType()) } }) } export const getInstanceChanges = ( changes: ReadonlyArray<Change>, targetMetadataType: string, ): Promise<ReadonlyArray<Change<InstanceElement>>> => ( awu(changes) .filter(isAdditionOrModificationChange) .filter(isInstanceChange) .filter(async change => await metadataType(getChangeElement(change)) === targetMetadataType) .toArray() ) export const findInstancesToConvert = ( elements: Element[], targetMetadataType: string, ): Promise<InstanceElement[]> => { const instances = elements.filter(isInstanceElement) return awu(instances).filter(async e => await metadataType(e) === targetMetadataType).toArray() } /** * Convert certain instances' fields into maps, so that they are easier to view, * could be referenced, and can be split across multiple files. */ const filter: FilterCreator = ({ config }) => ({ onFetch: async (elements: Element[]) => { await awu(Object.keys(metadataTypeToFieldToMapDef)).forEach(async targetMetadataType => { if (targetMetadataType === PROFILE_METADATA_TYPE && config.useOldProfiles) { return } const instancesToConvert = await findInstancesToConvert(elements, targetMetadataType) if (instancesToConvert.length === 0) { return } const mapFieldDef = metadataTypeToFieldToMapDef[targetMetadataType] const nonUniqueMapFields = await convertInstanceFieldsToMaps(instancesToConvert, mapFieldDef) await updateFieldTypes(await instancesToConvert[0].getType(), nonUniqueMapFields, mapFieldDef) }) }, preDeploy: async changes => { await awu(Object.keys(metadataTypeToFieldToMapDef)).forEach(async targetMetadataType => { if (targetMetadataType === PROFILE_METADATA_TYPE && config.useOldProfiles) { return } const instanceChanges = await getInstanceChanges(changes, targetMetadataType) if (instanceChanges.length === 0) { return } const mapFieldDef = metadataTypeToFieldToMapDef[targetMetadataType] // since transformElement and salesforce do not require list fields to be defined as lists, // we only mark fields as lists of their map inner value is a list, // so that we can convert the object back correctly in onDeploy await convertFieldsBackToLists(instanceChanges, mapFieldDef) const instanceType = await getChangeElement(instanceChanges[0]).getType() await convertFieldTypesBackToLists(instanceType, mapFieldDef) }) }, onDeploy: async changes => { await awu(Object.keys(metadataTypeToFieldToMapDef)).forEach(async targetMetadataType => { if (targetMetadataType === PROFILE_METADATA_TYPE && config.useOldProfiles) { return } const instanceChanges = await getInstanceChanges(changes, targetMetadataType) if (instanceChanges.length === 0) { return } const mapFieldDef = metadataTypeToFieldToMapDef[targetMetadataType] convertFieldsBackToMaps(instanceChanges, mapFieldDef) const instanceType = await getChangeElement(instanceChanges[0]).getType() // after preDeploy, the fields with lists are exactly the ones that should be converted // back to lists const nonUniqueMapFields = await awu(Object.keys(instanceType.fields)).filter( async fieldName => isListType(await (instanceType.fields[fieldName].getType())) ).toArray() await updateFieldTypes(instanceType, nonUniqueMapFields, mapFieldDef) }) }, }) export default filter
the_stack
import * as React from "react"; import { fireEvent, render, waitFor } from "@testing-library/react"; import * as SolidFns from "@inrupt/solid-client"; import * as helpers from "../../../helpers"; import DatetimeValue from "./index"; const mockPredicate = "http://www.w3.org/2006/vcard/ns#bday"; const mockBday = new Date("2021-05-04T06:00:00.000Z"); const testBday = new Date("2007-08-14T11:20:00.000Z"); const mockThing = SolidFns.addDatetime( SolidFns.createThing(), mockPredicate, mockBday ); const mockDataset = SolidFns.setThing( SolidFns.mockSolidDatasetFrom("https://some-interesting-value.com"), mockThing ); const mockDatasetWithResourceInfo = SolidFns.setThing( SolidFns.mockContainerFrom("https://some-interesting-value.com/"), mockThing ); const savedDataset = SolidFns.setThing( SolidFns.mockSolidDatasetFrom("https://example.pod/resource"), SolidFns.createThing() ); const latestDataset = SolidFns.setThing(savedDataset, SolidFns.createThing()); jest.spyOn(SolidFns, "saveSolidDatasetAt").mockResolvedValue(savedDataset); jest.spyOn(SolidFns, "getSolidDataset").mockResolvedValue(latestDataset); describe("<DatetimeValue /> component functional testing", () => { beforeEach(() => { jest.spyOn(helpers, "useDatetimeBrowserSupport").mockReturnValue(true); }); it("calls getDatetime and sets value", () => { const mockGetter = jest .spyOn(SolidFns, "getDatetime" as any) .mockImplementationOnce(() => mockBday); const { getByText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} /> ); expect(mockGetter).toHaveBeenCalled(); expect(getByText("2021-05-04T06:00:00")).toBeDefined(); }); it("should call setDatetime on blur", () => { jest .spyOn(SolidFns, "setDatetime" as any) .mockImplementationOnce(() => null); const mockSetter = jest .spyOn(SolidFns, "setDatetime" as any) .mockImplementation(() => mockThing); jest.spyOn(SolidFns, "saveSolidDatasetAt").mockResolvedValue(savedDataset); const { getByTitle } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} edit autosave inputProps={{ title: "test title" }} /> ); const input = getByTitle("test title"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); expect(mockSetter).toHaveBeenCalled(); }); it("Should not call setter on blur if the value of the input hasn't changed", async () => { jest.spyOn(SolidFns, "setDatetime").mockImplementation(() => mockThing); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); input.blur(); expect(SolidFns.setDatetime).toHaveBeenCalledTimes(0); }); it("Should not call saveSolidDatasetAt onBlur if autosave is false", async () => { jest.spyOn(SolidFns, "saveSolidDatasetAt").mockResolvedValue(savedDataset); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} edit /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); expect(SolidFns.saveSolidDatasetAt).toHaveBeenCalledTimes(0); }); it("Should call saveSolidDatasetAt onBlur if autosave is true", async () => { const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); await waitFor(() => expect(SolidFns.saveSolidDatasetAt).toHaveBeenCalled()); }); it("Should call onSave if it is passed", async () => { const onSave = jest.fn(); const onError = jest.fn(); jest.spyOn(SolidFns, "saveSolidDatasetAt").mockResolvedValue(savedDataset); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} onSave={onSave} onError={onError} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); await waitFor(() => expect(onSave).toHaveBeenCalled()); }); it("Should call onSave for fetched dataset with custom location if it is passed", async () => { const onSave = jest.fn(); const onError = jest.fn(); jest.spyOn(SolidFns, "saveSolidDatasetAt").mockResolvedValue(savedDataset); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} saveDatasetTo="https://ldp.demo-ess.inrupt.com/norbertand/profile/card" onSave={onSave} onError={onError} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); await waitFor(() => expect(onSave).toHaveBeenCalled()); }); it("Should call onError if saving fails", async () => { (SolidFns.saveSolidDatasetAt as jest.Mock).mockRejectedValueOnce(null); const onError = jest.fn(); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDataset} thing={mockThing} property={mockPredicate} saveDatasetTo="https://ldp.demo-ess.inrupt.com/norbertand/profile/card" onError={onError} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); await waitFor(() => expect(onError).toHaveBeenCalled()); }); it("Should call onError if Thing not found", async () => { (SolidFns.saveSolidDatasetAt as jest.Mock).mockRejectedValueOnce(null); const onError = jest.fn(); render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={undefined} property={mockPredicate} saveDatasetTo="https://ldp.demo-ess.inrupt.com/norbertand/profile/card" onError={onError} /> ); await waitFor(() => expect(onError).toHaveBeenCalled()); }); it("Should call onError if saving fetched dataset to custom location fails", async () => { (SolidFns.saveSolidDatasetAt as jest.Mock).mockRejectedValueOnce(null); const onError = jest.fn(); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} saveDatasetTo="https://ldp.demo-ess.inrupt.com/norbertand/profile/card" onError={onError} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); await waitFor(() => expect(onError).toHaveBeenCalled()); }); it("Should call onError if trying to save a non-fetched dataset without saveDatasetTo", async () => { const mockUnfetchedDataset = SolidFns.setThing( SolidFns.createSolidDataset(), mockThing ); const onError = jest.fn(); const { getByLabelText } = render( <DatetimeValue solidDataset={mockUnfetchedDataset} thing={mockThing} property={mockPredicate} onError={onError} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: testBday } }); input.blur(); await waitFor(() => expect(onError).toHaveBeenCalled()); }); it("when datetime-local is unsupported, it calls setDatetime with the correct value", () => { jest.spyOn(helpers, "useDatetimeBrowserSupport").mockReturnValue(false); jest.spyOn(SolidFns, "getDatetime").mockImplementationOnce(() => null); const mockSetter = jest.spyOn(SolidFns, "setDatetime"); jest.spyOn(SolidFns, "saveSolidDatasetAt").mockResolvedValue(savedDataset); jest.spyOn(SolidFns, "getSolidDataset").mockResolvedValue(latestDataset); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} edit autosave /> ); const dateInput = getByLabelText("Date"); dateInput.focus(); fireEvent.change(dateInput, { target: { value: "2020-03-03" } }); dateInput.blur(); const timeInput = getByLabelText("Time"); timeInput.focus(); fireEvent.change(timeInput, { target: { value: "05:45" } }); timeInput.blur(); const expectedDate = new Date(Date.UTC(2020, 2, 3, 0, 0, 0)); const expectedDateAndTime = new Date(Date.UTC(2020, 2, 3, 5, 45, 0)); expect(mockSetter.mock.calls).toEqual([ [mockThing, mockPredicate, expectedDate], [mockThing, mockPredicate, expectedDateAndTime], ]); }); it("Should update context with latest dataset after saving", async () => { const setDataset = jest.fn(); const setThing = jest.fn(); jest.spyOn(helpers, "useProperty").mockReturnValue({ dataset: mockDatasetWithResourceInfo, setDataset, setThing, error: undefined, value: mockBday, thing: mockThing, property: mockPredicate, }); const { getByLabelText } = render( <DatetimeValue solidDataset={mockDatasetWithResourceInfo} thing={mockThing} property={mockPredicate} edit autosave /> ); const input = getByLabelText("Date and Time"); input.focus(); fireEvent.change(input, { target: { value: "2007-08-14T11:20:00" } }); input.blur(); await waitFor(() => { expect(SolidFns.saveSolidDatasetAt).toHaveBeenCalled(); expect(setDataset).toHaveBeenCalledWith(latestDataset); }); }); });
the_stack
declare class FBSDKAccessToken extends NSObject implements FBSDKCopying, NSSecureCoding { static alloc(): FBSDKAccessToken; // inherited from NSObject static new(): FBSDKAccessToken; // inherited from NSObject static refreshCurrentAccessToken(completionHandler: (p1: FBSDKGraphRequestConnection, p2: any, p3: NSError) => void): void; readonly appID: string; readonly dataAccessExpirationDate: Date; readonly dataAccessExpired: boolean; readonly declinedPermissions: NSSet<string>; readonly expirationDate: Date; readonly expired: boolean; readonly expiredPermissions: NSSet<string>; readonly permissions: NSSet<string>; readonly refreshDate: Date; readonly tokenString: string; readonly userID: string; static currentAccessToken: FBSDKAccessToken; static readonly currentAccessTokenIsActive: boolean; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { tokenString: string; permissions: NSArray<string> | string[]; declinedPermissions: NSArray<string> | string[]; expiredPermissions: NSArray<string> | string[]; appID: string; userID: string; expirationDate: Date; refreshDate: Date; dataAccessExpirationDate: Date; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; copy(): any; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(aCoder: NSCoder): void; hasGranted(permission: string): boolean; initWithCoder(aDecoder: NSCoder): this; initWithTokenStringPermissionsDeclinedPermissionsExpiredPermissionsAppIDUserIDExpirationDateRefreshDateDataAccessExpirationDate(tokenString: string, permissions: NSArray<string> | string[], declinedPermissions: NSArray<string> | string[], expiredPermissions: NSArray<string> | string[], appID: string, userID: string, expirationDate: Date, refreshDate: Date, dataAccessExpirationDate: Date): this; isEqual(object: any): boolean; isEqualToAccessToken(token: FBSDKAccessToken): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } declare var FBSDKAccessTokenChangeNewKey: string; declare var FBSDKAccessTokenChangeOldKey: string; declare var FBSDKAccessTokenDidChangeNotification: string; declare var FBSDKAccessTokenDidChangeUserIDKey: string; declare var FBSDKAccessTokenDidExpireKey: string; declare var FBSDKAppEventCity: string; declare var FBSDKAppEventCountry: string; declare var FBSDKAppEventDateOfBirth: string; declare var FBSDKAppEventEmail: string; declare var FBSDKAppEventFirstName: string; declare var FBSDKAppEventGender: string; declare var FBSDKAppEventLastName: string; declare var FBSDKAppEventNameAchievedLevel: string; declare var FBSDKAppEventNameAdClick: string; declare var FBSDKAppEventNameAdImpression: string; declare var FBSDKAppEventNameAddedPaymentInfo: string; declare var FBSDKAppEventNameAddedToCart: string; declare var FBSDKAppEventNameAddedToWishlist: string; declare var FBSDKAppEventNameCompletedRegistration: string; declare var FBSDKAppEventNameCompletedTutorial: string; declare var FBSDKAppEventNameContact: string; declare var FBSDKAppEventNameCustomizeProduct: string; declare var FBSDKAppEventNameDonate: string; declare var FBSDKAppEventNameFindLocation: string; declare var FBSDKAppEventNameInitiatedCheckout: string; declare var FBSDKAppEventNamePurchased: string; declare var FBSDKAppEventNameRated: string; declare var FBSDKAppEventNameSchedule: string; declare var FBSDKAppEventNameSearched: string; declare var FBSDKAppEventNameSpentCredits: string; declare var FBSDKAppEventNameStartTrial: string; declare var FBSDKAppEventNameSubmitApplication: string; declare var FBSDKAppEventNameSubscribe: string; declare var FBSDKAppEventNameSubscriptionHeartbeat: string; declare var FBSDKAppEventNameUnlockedAchievement: string; declare var FBSDKAppEventNameViewedContent: string; declare var FBSDKAppEventParameterNameAdType: string; declare var FBSDKAppEventParameterNameContent: string; declare var FBSDKAppEventParameterNameContentID: string; declare var FBSDKAppEventParameterNameContentType: string; declare var FBSDKAppEventParameterNameCurrency: string; declare var FBSDKAppEventParameterNameDescription: string; declare var FBSDKAppEventParameterNameLevel: string; declare var FBSDKAppEventParameterNameMaxRatingValue: string; declare var FBSDKAppEventParameterNameNumItems: string; declare var FBSDKAppEventParameterNameOrderID: string; declare var FBSDKAppEventParameterNamePaymentInfoAvailable: string; declare var FBSDKAppEventParameterNameRegistrationMethod: string; declare var FBSDKAppEventParameterNameSearchString: string; declare var FBSDKAppEventParameterNameSuccess: string; declare var FBSDKAppEventParameterProductAppLinkAndroidAppName: string; declare var FBSDKAppEventParameterProductAppLinkAndroidPackage: string; declare var FBSDKAppEventParameterProductAppLinkAndroidUrl: string; declare var FBSDKAppEventParameterProductAppLinkIOSAppName: string; declare var FBSDKAppEventParameterProductAppLinkIOSAppStoreID: string; declare var FBSDKAppEventParameterProductAppLinkIOSUrl: string; declare var FBSDKAppEventParameterProductAppLinkIPadAppName: string; declare var FBSDKAppEventParameterProductAppLinkIPadAppStoreID: string; declare var FBSDKAppEventParameterProductAppLinkIPadUrl: string; declare var FBSDKAppEventParameterProductAppLinkIPhoneAppName: string; declare var FBSDKAppEventParameterProductAppLinkIPhoneAppStoreID: string; declare var FBSDKAppEventParameterProductAppLinkIPhoneUrl: string; declare var FBSDKAppEventParameterProductAppLinkWindowsPhoneAppID: string; declare var FBSDKAppEventParameterProductAppLinkWindowsPhoneAppName: string; declare var FBSDKAppEventParameterProductAppLinkWindowsPhoneUrl: string; declare var FBSDKAppEventParameterProductCategory: string; declare var FBSDKAppEventParameterProductCustomLabel0: string; declare var FBSDKAppEventParameterProductCustomLabel1: string; declare var FBSDKAppEventParameterProductCustomLabel2: string; declare var FBSDKAppEventParameterProductCustomLabel3: string; declare var FBSDKAppEventParameterProductCustomLabel4: string; declare var FBSDKAppEventParameterValueNo: string; declare var FBSDKAppEventParameterValueYes: string; declare var FBSDKAppEventPhone: string; declare var FBSDKAppEventState: string; declare var FBSDKAppEventZip: string; declare class FBSDKAppEvents extends NSObject { static activateApp(): void; static alloc(): FBSDKAppEvents; // inherited from NSObject static augmentHybridWKWebView(webView: WKWebView): void; static clearUserData(): void; static clearUserDataForType(type: string): void; static clearUserID(): void; static flush(): void; static getUserData(): string; static logEvent(eventName: string): void; static logEventParameters(eventName: string, parameters: NSDictionary<string, any>): void; static logEventValueToSum(eventName: string, valueToSum: number): void; static logEventValueToSumParameters(eventName: string, valueToSum: number, parameters: NSDictionary<string, any>): void; static logEventValueToSumParametersAccessToken(eventName: string, valueToSum: number, parameters: NSDictionary<string, any>, accessToken: FBSDKAccessToken): void; static logProductItemAvailabilityConditionDescriptionImageLinkLinkTitlePriceAmountCurrencyGtinMpnBrandParameters(itemID: string, availability: FBSDKProductAvailability, condition: FBSDKProductCondition, description: string, imageLink: string, link: string, title: string, priceAmount: number, currency: string, gtin: string, mpn: string, brand: string, parameters: NSDictionary<string, any>): void; static logPurchaseCurrency(purchaseAmount: number, currency: string): void; static logPurchaseCurrencyParameters(purchaseAmount: number, currency: string, parameters: NSDictionary<string, any>): void; static logPurchaseCurrencyParametersAccessToken(purchaseAmount: number, currency: string, parameters: NSDictionary<string, any>, accessToken: FBSDKAccessToken): void; static logPushNotificationOpen(payload: NSDictionary<any, any>): void; static logPushNotificationOpenAction(payload: NSDictionary<any, any>, action: string): void; static new(): FBSDKAppEvents; // inherited from NSObject static requestForCustomAudienceThirdPartyIDWithAccessToken(accessToken: FBSDKAccessToken): FBSDKGraphRequest; static sendEventBindingsToUnity(): void; static setIsUnityInit(isUnityInit: boolean): void; static setPushNotificationsDeviceToken(deviceToken: NSData): void; static setPushNotificationsDeviceTokenString(deviceTokenString: string): void; static setUserDataForType(data: string, type: string): void; static setUserEmailFirstNameLastNamePhoneDateOfBirthGenderCityStateZipCountry(email: string, firstName: string, lastName: string, phone: string, dateOfBirth: string, gender: string, city: string, state: string, zip: string, country: string): void; static updateUserPropertiesHandler(properties: NSDictionary<string, any>, handler: (p1: FBSDKGraphRequestConnection, p2: any, p3: NSError) => void): void; static flushBehavior: FBSDKAppEventsFlushBehavior; static loggingOverrideAppID: string; static userID: string; } declare const enum FBSDKAppEventsFlushBehavior { Auto = 0, ExplicitOnly = 1 } declare var FBSDKAppEventsLoggingResultNotification: string; declare var FBSDKAppEventsOverrideAppIDBundleKey: string; declare class FBSDKAppLink extends NSObject { static alloc(): FBSDKAppLink; // inherited from NSObject static appLinkWithSourceURLTargetsWebURL(sourceURL: NSURL, targets: NSArray<FBSDKAppLinkTarget> | FBSDKAppLinkTarget[], webURL: NSURL): FBSDKAppLink; static new(): FBSDKAppLink; // inherited from NSObject readonly sourceURL: NSURL; readonly targets: NSArray<FBSDKAppLinkTarget>; readonly webURL: NSURL; } declare var FBSDKAppLinkNavigateBackToReferrerEventName: string; declare var FBSDKAppLinkNavigateInEventName: string; declare var FBSDKAppLinkNavigateOutEventName: string; declare class FBSDKAppLinkNavigation extends NSObject { static alloc(): FBSDKAppLinkNavigation; // inherited from NSObject static callbackAppLinkDataForAppWithNameUrl(appName: string, url: string): NSDictionary<string, NSDictionary<string, string>>; static navigateToAppLinkError(link: FBSDKAppLink): FBSDKAppLinkNavigationType; static navigateToURLHandler(destination: NSURL, handler: (p1: FBSDKAppLinkNavigationType, p2: NSError) => void): void; static navigateToURLResolverHandler(destination: NSURL, resolver: FBSDKAppLinkResolving, handler: (p1: FBSDKAppLinkNavigationType, p2: NSError) => void): void; static navigationTypeForLink(link: FBSDKAppLink): FBSDKAppLinkNavigationType; static navigationWithAppLinkExtrasAppLinkData(appLink: FBSDKAppLink, extras: NSDictionary<string, any>, appLinkData: NSDictionary<string, any>): FBSDKAppLinkNavigation; static new(): FBSDKAppLinkNavigation; // inherited from NSObject static resolveAppLinkHandler(destination: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void; static resolveAppLinkResolverHandler(destination: NSURL, resolver: FBSDKAppLinkResolving, handler: (p1: FBSDKAppLink, p2: NSError) => void): void; readonly appLink: FBSDKAppLink; readonly appLinkData: NSDictionary<string, any>; readonly extras: NSDictionary<string, any>; readonly navigationType: FBSDKAppLinkNavigationType; static defaultResolver: FBSDKAppLinkResolving; navigate(): FBSDKAppLinkNavigationType; } declare const enum FBSDKAppLinkNavigationType { Failure = 0, Browser = 1, App = 2 } declare var FBSDKAppLinkParseEventName: string; declare class FBSDKAppLinkResolver extends NSObject implements FBSDKAppLinkResolving { static alloc(): FBSDKAppLinkResolver; // inherited from NSObject static new(): FBSDKAppLinkResolver; // inherited from NSObject static resolver(): FBSDKAppLinkResolver; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol appLinkFromURLHandler(url: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void; appLinksFromURLsHandler(urls: NSArray<NSURL> | NSURL[], handler: (p1: NSDictionary<NSURL, FBSDKAppLink>, p2: NSError) => void): void; class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } interface FBSDKAppLinkResolving extends NSObjectProtocol { appLinkFromURLHandler(url: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void; } declare var FBSDKAppLinkResolving: { prototype: FBSDKAppLinkResolving; }; declare class FBSDKAppLinkReturnToRefererController extends NSObject implements FBSDKAppLinkReturnToRefererViewDelegate { static alloc(): FBSDKAppLinkReturnToRefererController; // inherited from NSObject static new(): FBSDKAppLinkReturnToRefererController; // inherited from NSObject delegate: FBSDKAppLinkReturnToRefererControllerDelegate; view: FBSDKAppLinkReturnToRefererView; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol constructor(o: { forDisplayAboveNavController: UINavigationController; }); class(): typeof NSObject; closeViewAnimated(animated: boolean): void; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initForDisplayAboveNavController(navController: UINavigationController): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; removeFromNavController(): void; respondsToSelector(aSelector: string): boolean; retainCount(): number; returnToRefererViewDidTapInsideCloseButton(view: FBSDKAppLinkReturnToRefererView): void; returnToRefererViewDidTapInsideLinkLink(view: FBSDKAppLinkReturnToRefererView, link: FBSDKAppLink): void; self(): this; showViewForRefererAppLink(refererAppLink: FBSDKAppLink): void; showViewForRefererURL(url: NSURL): void; } interface FBSDKAppLinkReturnToRefererControllerDelegate extends NSObjectProtocol { returnToRefererControllerDidNavigateToAppLinkType?(controller: FBSDKAppLinkReturnToRefererController, url: FBSDKAppLink, type: FBSDKAppLinkNavigationType): void; returnToRefererControllerWillNavigateToAppLink?(controller: FBSDKAppLinkReturnToRefererController, appLink: FBSDKAppLink): void; } declare var FBSDKAppLinkReturnToRefererControllerDelegate: { prototype: FBSDKAppLinkReturnToRefererControllerDelegate; }; declare class FBSDKAppLinkReturnToRefererView extends UIView { static alloc(): FBSDKAppLinkReturnToRefererView; // inherited from NSObject static appearance(): FBSDKAppLinkReturnToRefererView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): FBSDKAppLinkReturnToRefererView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKAppLinkReturnToRefererView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKAppLinkReturnToRefererView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKAppLinkReturnToRefererView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKAppLinkReturnToRefererView; // inherited from UIAppearance static new(): FBSDKAppLinkReturnToRefererView; // inherited from NSObject closed: boolean; delegate: FBSDKAppLinkReturnToRefererViewDelegate; includeStatusBarInSize: FBSDKIncludeStatusBarInSize; refererAppLink: FBSDKAppLink; textColor: UIColor; } interface FBSDKAppLinkReturnToRefererViewDelegate extends NSObjectProtocol { returnToRefererViewDidTapInsideCloseButton(view: FBSDKAppLinkReturnToRefererView): void; returnToRefererViewDidTapInsideLinkLink(view: FBSDKAppLinkReturnToRefererView, link: FBSDKAppLink): void; } declare var FBSDKAppLinkReturnToRefererViewDelegate: { prototype: FBSDKAppLinkReturnToRefererViewDelegate; }; declare class FBSDKAppLinkTarget extends NSObject { static alloc(): FBSDKAppLinkTarget; // inherited from NSObject static appLinkTargetWithURLAppStoreIdAppName(url: NSURL, appStoreId: string, appName: string): FBSDKAppLinkTarget; static new(): FBSDKAppLinkTarget; // inherited from NSObject readonly URL: NSURL; readonly appName: string; readonly appStoreId: string; } declare class FBSDKAppLinkUtility extends NSObject { static alloc(): FBSDKAppLinkUtility; // inherited from NSObject static appInvitePromotionCodeFromURL(url: NSURL): string; static fetchDeferredAppLink(handler: (p1: NSURL, p2: NSError) => void): void; static new(): FBSDKAppLinkUtility; // inherited from NSObject } declare var FBSDKAppLinkVersion: string; declare class FBSDKApplicationDelegate extends NSObject { static alloc(): FBSDKApplicationDelegate; // inherited from NSObject static initializeSDK(launchOptions: NSDictionary<string, any>): void; static new(): FBSDKApplicationDelegate; // inherited from NSObject static readonly sharedInstance: FBSDKApplicationDelegate; applicationDidFinishLaunchingWithOptions(application: UIApplication, launchOptions: NSDictionary<string, any>): boolean; applicationOpenURLOptions(application: UIApplication, url: NSURL, options: NSDictionary<string, any>): boolean; applicationOpenURLSourceApplicationAnnotation(application: UIApplication, url: NSURL, sourceApplication: string, annotation: any): boolean; } declare class FBSDKBasicUtility extends NSObject { static alloc(): FBSDKBasicUtility; // inherited from NSObject static new(): FBSDKBasicUtility; // inherited from NSObject } declare class FBSDKButton extends UIButton { static alloc(): FBSDKButton; // inherited from NSObject static appearance(): FBSDKButton; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): FBSDKButton; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKButton; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKButton; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKButton; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKButton; // inherited from UIAppearance static buttonWithType(buttonType: UIButtonType): FBSDKButton; // inherited from UIButton static new(): FBSDKButton; // inherited from NSObject } interface FBSDKCopying extends NSCopying, NSObjectProtocol { copy(): any; } declare var FBSDKCopying: { prototype: FBSDKCopying; }; declare var FBSDKCoreKitVersionNumber: number; declare var FBSDKCoreKitVersionString: interop.Reference<number>; declare const enum FBSDKError { Reserved = 0, Encryption = 1, InvalidArgument = 2, Unknown = 3, Network = 4, AppEventsFlush = 5, GraphRequestNonTextMimeTypeReturned = 6, GraphRequestProtocolMismatch = 7, GraphRequestGraphAPI = 8, DialogUnavailable = 9, AccessTokenRequired = 10, AppVersionUnsupported = 11, BrowserUnavailable = 12 } declare var FBSDKErrorArgumentCollectionKey: string; declare var FBSDKErrorArgumentNameKey: string; declare var FBSDKErrorArgumentValueKey: string; declare var FBSDKErrorDeveloperMessageKey: string; declare var FBSDKErrorDomain: string; declare var FBSDKErrorLocalizedDescriptionKey: string; declare var FBSDKErrorLocalizedTitleKey: string; interface FBSDKErrorRecoveryAttempting extends NSObjectProtocol { attemptRecoveryFromErrorOptionIndexDelegateDidRecoverSelectorContextInfo(error: NSError, recoveryOptionIndex: number, delegate: any, didRecoverSelector: string, contextInfo: interop.Pointer | interop.Reference<any>): void; } declare var FBSDKErrorRecoveryAttempting: { prototype: FBSDKErrorRecoveryAttempting; }; declare class FBSDKGraphErrorRecoveryProcessor extends NSObject { static alloc(): FBSDKGraphErrorRecoveryProcessor; // inherited from NSObject static new(): FBSDKGraphErrorRecoveryProcessor; // inherited from NSObject readonly delegate: FBSDKGraphErrorRecoveryProcessorDelegate; didPresentErrorWithRecoveryContextInfo(didRecover: boolean, contextInfo: interop.Pointer | interop.Reference<any>): void; processErrorRequestDelegate(error: NSError, request: FBSDKGraphRequest, delegate: FBSDKGraphErrorRecoveryProcessorDelegate): boolean; } interface FBSDKGraphErrorRecoveryProcessorDelegate extends NSObjectProtocol { processorDidAttemptRecoveryDidRecoverError(processor: FBSDKGraphErrorRecoveryProcessor, didRecover: boolean, error: NSError): void; processorWillProcessErrorError?(processor: FBSDKGraphErrorRecoveryProcessor, error: NSError): boolean; } declare var FBSDKGraphErrorRecoveryProcessorDelegate: { prototype: FBSDKGraphErrorRecoveryProcessorDelegate; }; declare class FBSDKGraphRequest extends NSObject { static alloc(): FBSDKGraphRequest; // inherited from NSObject static new(): FBSDKGraphRequest; // inherited from NSObject readonly HTTPMethod: string; readonly graphPath: string; parameters: NSDictionary<string, any>; readonly tokenString: string; readonly version: string; constructor(o: { graphPath: string; }); constructor(o: { graphPath: string; HTTPMethod: string; }); constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; }); constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; HTTPMethod: string; }); constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; tokenString: string; version: string; HTTPMethod: string; }); initWithGraphPath(graphPath: string): this; initWithGraphPathHTTPMethod(graphPath: string, method: string): this; initWithGraphPathParameters(graphPath: string, parameters: NSDictionary<string, any>): this; initWithGraphPathParametersHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, method: string): this; initWithGraphPathParametersTokenStringVersionHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, tokenString: string, version: string, method: string): this; setGraphErrorRecoveryDisabled(disable: boolean): void; startWithCompletionHandler(handler: (p1: FBSDKGraphRequestConnection, p2: any, p3: NSError) => void): FBSDKGraphRequestConnection; } declare class FBSDKGraphRequestConnection extends NSObject { static alloc(): FBSDKGraphRequestConnection; // inherited from NSObject static new(): FBSDKGraphRequestConnection; // inherited from NSObject delegate: FBSDKGraphRequestConnectionDelegate; delegateQueue: NSOperationQueue; timeout: number; readonly urlResponse: NSHTTPURLResponse; static defaultConnectionTimeout: number; addRequestBatchEntryNameCompletionHandler(request: FBSDKGraphRequest, name: string, handler: (p1: FBSDKGraphRequestConnection, p2: any, p3: NSError) => void): void; addRequestBatchParametersCompletionHandler(request: FBSDKGraphRequest, batchParameters: NSDictionary<string, any>, handler: (p1: FBSDKGraphRequestConnection, p2: any, p3: NSError) => void): void; addRequestCompletionHandler(request: FBSDKGraphRequest, handler: (p1: FBSDKGraphRequestConnection, p2: any, p3: NSError) => void): void; cancel(): void; overrideGraphAPIVersion(version: string): void; start(): void; } interface FBSDKGraphRequestConnectionDelegate extends NSObjectProtocol { requestConnectionDidFailWithError?(connection: FBSDKGraphRequestConnection, error: NSError): void; requestConnectionDidFinishLoading?(connection: FBSDKGraphRequestConnection): void; requestConnectionDidSendBodyDataTotalBytesWrittenTotalBytesExpectedToWrite?(connection: FBSDKGraphRequestConnection, bytesWritten: number, totalBytesWritten: number, totalBytesExpectedToWrite: number): void; requestConnectionWillBeginLoading?(connection: FBSDKGraphRequestConnection): void; } declare var FBSDKGraphRequestConnectionDelegate: { prototype: FBSDKGraphRequestConnectionDelegate; }; declare class FBSDKGraphRequestDataAttachment extends NSObject { static alloc(): FBSDKGraphRequestDataAttachment; // inherited from NSObject static new(): FBSDKGraphRequestDataAttachment; // inherited from NSObject readonly contentType: string; readonly data: NSData; readonly filename: string; constructor(o: { data: NSData; filename: string; contentType: string; }); initWithDataFilenameContentType(data: NSData, filename: string, contentType: string): this; } declare const enum FBSDKGraphRequestError { Other = 0, Transient = 1, Recoverable = 2 } declare var FBSDKGraphRequestErrorGraphErrorCodeKey: string; declare var FBSDKGraphRequestErrorGraphErrorSubcodeKey: string; declare var FBSDKGraphRequestErrorHTTPStatusCodeKey: string; declare var FBSDKGraphRequestErrorKey: string; declare var FBSDKGraphRequestErrorParsedJSONResponseKey: string; declare var FBSDKHTTPMethodDELETE: string; declare var FBSDKHTTPMethodGET: string; declare var FBSDKHTTPMethodPOST: string; declare const enum FBSDKIncludeStatusBarInSize { Never = 0, Always = 1 } declare var FBSDKLoggingBehaviorAccessTokens: string; declare var FBSDKLoggingBehaviorAppEvents: string; declare var FBSDKLoggingBehaviorCacheErrors: string; declare var FBSDKLoggingBehaviorDeveloperErrors: string; declare var FBSDKLoggingBehaviorGraphAPIDebugInfo: string; declare var FBSDKLoggingBehaviorGraphAPIDebugWarning: string; declare var FBSDKLoggingBehaviorInformational: string; declare var FBSDKLoggingBehaviorNetworkRequests: string; declare var FBSDKLoggingBehaviorPerformanceCharacteristics: string; declare var FBSDKLoggingBehaviorUIControlErrors: string; declare class FBSDKMeasurementEvent extends NSObject { static alloc(): FBSDKMeasurementEvent; // inherited from NSObject static new(): FBSDKMeasurementEvent; // inherited from NSObject } declare var FBSDKMeasurementEventArgsKey: string; declare var FBSDKMeasurementEventNameKey: string; declare var FBSDKMeasurementEventNotification: string; interface FBSDKMutableCopying extends FBSDKCopying, NSMutableCopying { mutableCopy(): any; } declare var FBSDKMutableCopying: { prototype: FBSDKMutableCopying; }; declare var FBSDKNonJSONResponseProperty: string; declare const enum FBSDKProductAvailability { InStock = 0, OutOfStock = 1, PreOrder = 2, AvailableForOrder = 3, Discontinued = 4 } declare const enum FBSDKProductCondition { New = 0, Refurbished = 1, Used = 2 } declare class FBSDKProfile extends NSObject implements NSCopying, NSSecureCoding { static alloc(): FBSDKProfile; // inherited from NSObject static enableUpdatesOnAccessTokenChange(enable: boolean): void; static loadCurrentProfileWithCompletion(completion: (p1: FBSDKProfile, p2: NSError) => void): void; static new(): FBSDKProfile; // inherited from NSObject readonly firstName: string; readonly lastName: string; readonly linkURL: NSURL; readonly middleName: string; readonly name: string; readonly refreshDate: Date; readonly userID: string; static currentProfile: FBSDKProfile; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { userID: string; firstName: string; middleName: string; lastName: string; name: string; linkURL: NSURL; refreshDate: Date; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(aCoder: NSCoder): void; imageURLForPictureModeSize(mode: FBSDKProfilePictureMode, size: CGSize): NSURL; initWithCoder(aDecoder: NSCoder): this; initWithUserIDFirstNameMiddleNameLastNameNameLinkURLRefreshDate(userID: string, firstName: string, middleName: string, lastName: string, name: string, linkURL: NSURL, refreshDate: Date): this; isEqualToProfile(profile: FBSDKProfile): boolean; } declare var FBSDKProfileChangeNewKey: string; declare var FBSDKProfileChangeOldKey: string; declare var FBSDKProfileDidChangeNotification: string; declare const enum FBSDKProfilePictureMode { Square = 0, Normal = 1 } declare class FBSDKProfilePictureView extends UIView { static alloc(): FBSDKProfilePictureView; // inherited from NSObject static appearance(): FBSDKProfilePictureView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): FBSDKProfilePictureView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKProfilePictureView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKProfilePictureView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKProfilePictureView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKProfilePictureView; // inherited from UIAppearance static new(): FBSDKProfilePictureView; // inherited from NSObject pictureMode: FBSDKProfilePictureMode; profileID: string; setNeedsImageUpdate(): void; } declare class FBSDKSettings extends NSObject { static alloc(): FBSDKSettings; // inherited from NSObject static disableLoggingBehavior(loggingBehavior: string): void; static enableLoggingBehavior(loggingBehavior: string): void; static new(): FBSDKSettings; // inherited from NSObject static JPEGCompressionQuality: number; static advertiserIDCollectionEnabled: boolean; static appID: string; static appURLSchemeSuffix: string; static autoInitEnabled: boolean; static autoLogAppEventsEnabled: boolean; static clientToken: string; static codelessDebugLogEnabled: boolean; static readonly defaultGraphAPIVersion: string; static displayName: string; static facebookDomainPart: string; static graphAPIVersion: string; static graphErrorRecoveryEnabled: boolean; static limitEventAndDataUsage: boolean; static loggingBehaviors: NSSet<string>; static readonly sdkVersion: string; } declare class FBSDKTestUsersManager extends NSObject { static alloc(): FBSDKTestUsersManager; // inherited from NSObject static new(): FBSDKTestUsersManager; // inherited from NSObject static sharedInstanceForAppIDAppSecret(appID: string, appSecret: string): FBSDKTestUsersManager; addTestAccountWithPermissionsCompletionHandler(permissions: NSSet<string>, handler: (p1: NSArray<FBSDKAccessToken>, p2: NSError) => void): void; makeFriendsWithFirstSecondCallback(first: FBSDKAccessToken, second: FBSDKAccessToken, callback: (p1: NSError) => void): void; removeTestAccountCompletionHandler(userId: string, handler: (p1: NSError) => void): void; requestTestAccountTokensWithArraysOfPermissionsCreateIfNotFoundCompletionHandler(arraysOfPermissions: NSArray<NSSet<string>> | NSSet<string>[], createIfNotFound: boolean, handler: (p1: NSArray<FBSDKAccessToken>, p2: NSError) => void): void; } declare class FBSDKURL extends NSObject { static URLWithInboundURLSourceApplication(url: NSURL, sourceApplication: string): FBSDKURL; static URLWithURL(url: NSURL): FBSDKURL; static alloc(): FBSDKURL; // inherited from NSObject static new(): FBSDKURL; // inherited from NSObject readonly appLinkData: NSDictionary<string, any>; readonly appLinkExtras: NSDictionary<string, any>; readonly appLinkReferer: FBSDKAppLink; readonly inputQueryParameters: NSDictionary<string, any>; readonly inputURL: NSURL; readonly targetQueryParameters: NSDictionary<string, any>; readonly targetURL: NSURL; } declare class FBSDKUtility extends NSObject { static SHA256Hash(input: NSObject): string; static URLDecode(value: string): string; static URLEncode(value: string): string; static alloc(): FBSDKUtility; // inherited from NSObject static dictionaryWithQueryString(queryString: string): NSDictionary<string, string>; static new(): FBSDKUtility; // inherited from NSObject static queryStringWithDictionaryError(dictionary: NSDictionary<string, any>): string; static startGCDTimerWithIntervalBlock(interval: number, block: () => void): NSObject; static stopGCDTimer(timer: NSObject): void; } declare class FBSDKWebViewAppLinkResolver extends NSObject implements FBSDKAppLinkResolving { static alloc(): FBSDKWebViewAppLinkResolver; // inherited from NSObject static new(): FBSDKWebViewAppLinkResolver; // inherited from NSObject static readonly sharedInstance: FBSDKWebViewAppLinkResolver; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol appLinkFromURLHandler(url: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void; class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { BatchAccountOperations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { BatchManagementClient } from "../batchManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { BatchAccount, BatchAccountListNextOptionalParams, BatchAccountListOptionalParams, BatchAccountListByResourceGroupNextOptionalParams, BatchAccountListByResourceGroupOptionalParams, OutboundEnvironmentEndpoint, BatchAccountListOutboundNetworkDependenciesEndpointsNextOptionalParams, BatchAccountListOutboundNetworkDependenciesEndpointsOptionalParams, BatchAccountCreateParameters, BatchAccountCreateOptionalParams, BatchAccountCreateResponse, BatchAccountUpdateParameters, BatchAccountUpdateOptionalParams, BatchAccountUpdateResponse, BatchAccountDeleteOptionalParams, BatchAccountGetOptionalParams, BatchAccountGetResponse, BatchAccountListResponse, BatchAccountListByResourceGroupResponse, BatchAccountSynchronizeAutoStorageKeysOptionalParams, BatchAccountRegenerateKeyParameters, BatchAccountRegenerateKeyOptionalParams, BatchAccountRegenerateKeyResponse, BatchAccountGetKeysOptionalParams, BatchAccountGetKeysResponse, BatchAccountListOutboundNetworkDependenciesEndpointsResponse, BatchAccountListNextResponse, BatchAccountListByResourceGroupNextResponse, BatchAccountListOutboundNetworkDependenciesEndpointsNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing BatchAccountOperations operations. */ export class BatchAccountOperationsImpl implements BatchAccountOperations { private readonly client: BatchManagementClient; /** * Initialize a new instance of the class BatchAccountOperations class. * @param client Reference to the service client */ constructor(client: BatchManagementClient) { this.client = client; } /** * Gets information about the Batch accounts associated with the subscription. * @param options The options parameters. */ public list( options?: BatchAccountListOptionalParams ): PagedAsyncIterableIterator<BatchAccount> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: BatchAccountListOptionalParams ): AsyncIterableIterator<BatchAccount[]> { let result = await this._list(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( options?: BatchAccountListOptionalParams ): AsyncIterableIterator<BatchAccount> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * Gets information about the Batch accounts associated with the specified resource group. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: BatchAccountListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<BatchAccount> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: BatchAccountListByResourceGroupOptionalParams ): AsyncIterableIterator<BatchAccount[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: BatchAccountListByResourceGroupOptionalParams ): AsyncIterableIterator<BatchAccount> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Lists the endpoints that a Batch Compute Node under this Batch Account may call as part of Batch * service administration. If you are deploying a Pool inside of a virtual network that you specify, * you must make sure your network allows outbound access to these endpoints. Failure to allow access * to these endpoints may cause Batch to mark the affected nodes as unusable. For more information * about creating a pool inside of a virtual network, see * https://docs.microsoft.com/en-us/azure/batch/batch-virtual-network. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param options The options parameters. */ public listOutboundNetworkDependenciesEndpoints( resourceGroupName: string, accountName: string, options?: BatchAccountListOutboundNetworkDependenciesEndpointsOptionalParams ): PagedAsyncIterableIterator<OutboundEnvironmentEndpoint> { const iter = this.listOutboundNetworkDependenciesEndpointsPagingAll( resourceGroupName, accountName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listOutboundNetworkDependenciesEndpointsPagingPage( resourceGroupName, accountName, options ); } }; } private async *listOutboundNetworkDependenciesEndpointsPagingPage( resourceGroupName: string, accountName: string, options?: BatchAccountListOutboundNetworkDependenciesEndpointsOptionalParams ): AsyncIterableIterator<OutboundEnvironmentEndpoint[]> { let result = await this._listOutboundNetworkDependenciesEndpoints( resourceGroupName, accountName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listOutboundNetworkDependenciesEndpointsNext( resourceGroupName, accountName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listOutboundNetworkDependenciesEndpointsPagingAll( resourceGroupName: string, accountName: string, options?: BatchAccountListOutboundNetworkDependenciesEndpointsOptionalParams ): AsyncIterableIterator<OutboundEnvironmentEndpoint> { for await (const page of this.listOutboundNetworkDependenciesEndpointsPagingPage( resourceGroupName, accountName, options )) { yield* page; } } /** * Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with * this API and should instead be updated with the Update Batch Account API. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName A name for the Batch account which must be unique within the region. Batch * account names must be between 3 and 24 characters in length and must use only numbers and lowercase * letters. This name is used as part of the DNS name that is used to access the Batch service in the * region in which the account is created. For example: http://accountname.region.batch.azure.com/. * @param parameters Additional parameters for account creation. * @param options The options parameters. */ async beginCreate( resourceGroupName: string, accountName: string, parameters: BatchAccountCreateParameters, options?: BatchAccountCreateOptionalParams ): Promise< PollerLike< PollOperationState<BatchAccountCreateResponse>, BatchAccountCreateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<BatchAccountCreateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, accountName, parameters, options }, createOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Creates a new Batch account with the specified parameters. Existing accounts cannot be updated with * this API and should instead be updated with the Update Batch Account API. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName A name for the Batch account which must be unique within the region. Batch * account names must be between 3 and 24 characters in length and must use only numbers and lowercase * letters. This name is used as part of the DNS name that is used to access the Batch service in the * region in which the account is created. For example: http://accountname.region.batch.azure.com/. * @param parameters Additional parameters for account creation. * @param options The options parameters. */ async beginCreateAndWait( resourceGroupName: string, accountName: string, parameters: BatchAccountCreateParameters, options?: BatchAccountCreateOptionalParams ): Promise<BatchAccountCreateResponse> { const poller = await this.beginCreate( resourceGroupName, accountName, parameters, options ); return poller.pollUntilDone(); } /** * Updates the properties of an existing Batch account. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param parameters Additional parameters for account update. * @param options The options parameters. */ update( resourceGroupName: string, accountName: string, parameters: BatchAccountUpdateParameters, options?: BatchAccountUpdateOptionalParams ): Promise<BatchAccountUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, parameters, options }, updateOperationSpec ); } /** * Deletes the specified Batch account. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, accountName: string, options?: BatchAccountDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, accountName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Deletes the specified Batch account. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, accountName: string, options?: BatchAccountDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, accountName, options ); return poller.pollUntilDone(); } /** * Gets information about the specified Batch account. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param options The options parameters. */ get( resourceGroupName: string, accountName: string, options?: BatchAccountGetOptionalParams ): Promise<BatchAccountGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, getOperationSpec ); } /** * Gets information about the Batch accounts associated with the subscription. * @param options The options parameters. */ private _list( options?: BatchAccountListOptionalParams ): Promise<BatchAccountListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * Gets information about the Batch accounts associated with the specified resource group. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: BatchAccountListByResourceGroupOptionalParams ): Promise<BatchAccountListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Synchronizes access keys for the auto-storage account configured for the specified Batch account, * only if storage key authentication is being used. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param options The options parameters. */ synchronizeAutoStorageKeys( resourceGroupName: string, accountName: string, options?: BatchAccountSynchronizeAutoStorageKeysOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, synchronizeAutoStorageKeysOperationSpec ); } /** * This operation applies only to Batch accounts with allowedAuthenticationModes containing * 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, * clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes * instead. In this case, regenerating the keys will fail. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param parameters The type of key to regenerate. * @param options The options parameters. */ regenerateKey( resourceGroupName: string, accountName: string, parameters: BatchAccountRegenerateKeyParameters, options?: BatchAccountRegenerateKeyOptionalParams ): Promise<BatchAccountRegenerateKeyResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, parameters, options }, regenerateKeyOperationSpec ); } /** * This operation applies only to Batch accounts with allowedAuthenticationModes containing * 'SharedKey'. If the Batch account doesn't contain 'SharedKey' in its allowedAuthenticationMode, * clients cannot use shared keys to authenticate, and must use another allowedAuthenticationModes * instead. In this case, getting the keys will fail. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param options The options parameters. */ getKeys( resourceGroupName: string, accountName: string, options?: BatchAccountGetKeysOptionalParams ): Promise<BatchAccountGetKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, getKeysOperationSpec ); } /** * Lists the endpoints that a Batch Compute Node under this Batch Account may call as part of Batch * service administration. If you are deploying a Pool inside of a virtual network that you specify, * you must make sure your network allows outbound access to these endpoints. Failure to allow access * to these endpoints may cause Batch to mark the affected nodes as unusable. For more information * about creating a pool inside of a virtual network, see * https://docs.microsoft.com/en-us/azure/batch/batch-virtual-network. * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param options The options parameters. */ private _listOutboundNetworkDependenciesEndpoints( resourceGroupName: string, accountName: string, options?: BatchAccountListOutboundNetworkDependenciesEndpointsOptionalParams ): Promise<BatchAccountListOutboundNetworkDependenciesEndpointsResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, listOutboundNetworkDependenciesEndpointsOperationSpec ); } /** * ListNext * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( nextLink: string, options?: BatchAccountListNextOptionalParams ): Promise<BatchAccountListNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listNextOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group that contains the Batch account. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: BatchAccountListByResourceGroupNextOptionalParams ): Promise<BatchAccountListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListOutboundNetworkDependenciesEndpointsNext * @param resourceGroupName The name of the resource group that contains the Batch account. * @param accountName The name of the Batch account. * @param nextLink The nextLink from the previous successful call to the * ListOutboundNetworkDependenciesEndpoints method. * @param options The options parameters. */ private _listOutboundNetworkDependenciesEndpointsNext( resourceGroupName: string, accountName: string, nextLink: string, options?: BatchAccountListOutboundNetworkDependenciesEndpointsNextOptionalParams ): Promise<BatchAccountListOutboundNetworkDependenciesEndpointsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, nextLink, options }, listOutboundNetworkDependenciesEndpointsNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.BatchAccount }, 201: { bodyMapper: Mappers.BatchAccount }, 202: { bodyMapper: Mappers.BatchAccount }, 204: { bodyMapper: Mappers.BatchAccount }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.accountName, Parameters.subscriptionId ], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.BatchAccount }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1 ], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1 ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.BatchAccount }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1 ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.BatchAccountListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.BatchAccountListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const synchronizeAutoStorageKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys", httpMethod: "POST", responses: { 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1 ], headerParameters: [Parameters.accept], serializer }; const regenerateKeyOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.BatchAccountKeys }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters2, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1 ], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "json", serializer }; const getKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.BatchAccountKeys }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1 ], headerParameters: [Parameters.accept], serializer }; const listOutboundNetworkDependenciesEndpointsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/outboundNetworkDependenciesEndpoints", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OutboundEnvironmentEndpointCollection }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1 ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.BatchAccountListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.BatchAccountListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listOutboundNetworkDependenciesEndpointsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OutboundEnvironmentEndpointCollection }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.accountName1, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import { ext } from '@antv/matrix-util'; import { ICanvas, IGroup } from '@antv/g-base'; import { isNumber, isString } from '@antv/util'; import { ShapeStyle, IAbstractGraph as IGraph } from '@antv/g6-core'; import TimeBarTooltip from './timeBarTooltip'; import ControllerBtn from './controllerBtn'; import { VALUE_CHANGE, TIMELINE_START, TIMELINE_END, PLAY_PAUSE_BTN, NEXT_STEP_BTN, PRE_STEP_BTN, TIMEBAR_CONFIG_CHANGE, } from './constant'; const transform = ext.transform; const DEFAULT_SELECTEDTICK_STYLE = { fill: '#5B8FF9', }; const DEFAULT_UNSELECTEDTICK_STYLE = { fill: '#e6e8e9', }; export interface TimeBarSliceOption { // position size readonly x?: number; readonly y?: number; readonly width?: number; readonly height?: number; readonly padding?: number; // styles readonly selectedTickStyle?: ShapeStyle; readonly unselectedTickStyle?: ShapeStyle; readonly tooltipBackgroundColor?: string; readonly start?: number; readonly end?: number; // 数据 readonly data: { date: string; value: string; }[]; // 自定义标签格式化函数 readonly tickLabelFormatter?: (d: any) => string | boolean; // 自定义 tooltip 内容格式化函数 readonly tooltipFomatter?: (d: any) => string; } export interface TimeBarSliceConfig extends TimeBarSliceOption { readonly graph: IGraph; readonly group: IGroup; readonly canvas: ICanvas; // style readonly x: number; readonly y: number; readonly tickLabelStyle?: Object; } export default class TimeBarSlice { private graph: IGraph; private canvas: ICanvas; private group: IGroup; private sliceGroup: IGroup; private width: number; private height: number; private padding: number; private data: { date: string; value: string; }[]; private start: number; private end: number; // style public x: number; public y: number; private selectedTickStyle: ShapeStyle; private unselectedTickStyle: ShapeStyle; private tickLabelFormatter: (d: any) => string | boolean; private tickLabelStyle?: ShapeStyle; private tickRects: any[]; private tickWidth: number; private startTickRectId: number; private endTickRectId: number; private tooltipBackgroundColor: string; private tooltipFomatter: (d: any) => string; private dragging: boolean; // play controller private controllerBtnGroup: ControllerBtn; /** 是否处于播放状态 */ private isPlay: boolean; // 调整后的播放速度 private currentSpeed: number; /** 动画 id */ private playHandler: number; private frameCount: number = 0; private fontFamily: string = 'Arial, sans-serif'; constructor(cfgs?: TimeBarSliceConfig) { const { graph, canvas, group, width, height, padding, data, start, end, x = 0, y = 0, tickLabelFormatter, selectedTickStyle = DEFAULT_SELECTEDTICK_STYLE, unselectedTickStyle = DEFAULT_UNSELECTEDTICK_STYLE, tooltipBackgroundColor, tooltipFomatter, tickLabelStyle } = cfgs; this.graph = graph; this.group = group; this.sliceGroup = group.addGroup({ name: 'slice-group', }); this.canvas = canvas; this.width = width; this.height = height; this.padding = padding; this.data = data; this.start = start; this.end = end; this.tickLabelFormatter = tickLabelFormatter; this.tickLabelStyle = tickLabelStyle || {}; this.selectedTickStyle = selectedTickStyle; this.unselectedTickStyle = unselectedTickStyle; this.x = x; this.y = y; this.tooltipBackgroundColor = tooltipBackgroundColor; this.tooltipFomatter = tooltipFomatter; // 初始化 fontFamily,如果有浏览器,取 body 上的字体,防止文字更新时局部渲染造成的重影 this.fontFamily = typeof window !== 'undefined' ? window.getComputedStyle(document.body, null).getPropertyValue('font-family') || 'Arial, sans-serif' : 'Arial, sans-serif'; this.renderSlices(); this.initEvent(); } private renderSlices() { const { width, height, padding, data, start, end, tickLabelFormatter, selectedTickStyle, unselectedTickStyle, tickLabelStyle } = this; const realWidth = width - 2 * padding; const fontSize = 10; const labelLineHeight = 4; const labelAreaHeight = 3 * padding + labelLineHeight + fontSize; const ticksAreaHeight = height - labelAreaHeight - 2 * padding; const gap = 2; const ticksLength = data.length; const tickWidth = (realWidth - gap * (ticksLength - 1)) / ticksLength; this.tickWidth = tickWidth; const sliceGroup = this.sliceGroup; const tickRects = []; const labels = []; const startTickId = Math.round(ticksLength * start); const endTickId = Math.round(ticksLength * end); this.startTickRectId = startTickId; this.endTickRectId = endTickId; const rotate = tickLabelStyle.rotate; delete tickLabelStyle.rotate; data.forEach((d, i) => { // draw the tick rects const selected = i >= startTickId && i <= endTickId; const tickStyle = selected ? selectedTickStyle : unselectedTickStyle; const rect = sliceGroup.addShape('rect', { attrs: { x: padding + i * (tickWidth + gap), y: padding, width: tickWidth, height: ticksAreaHeight, ...tickStyle, }, draggable: true, name: `tick-rect-${i}`, }); // draw the pick tick rects const pickRect = sliceGroup.addShape('rect', { attrs: { x: padding + i * tickWidth + (gap * (2 * i - 1)) / 2, y: padding, width: i === 0 || i === ticksLength - 1 ? tickWidth + gap / 2 : tickWidth + gap, height: ticksAreaHeight, fill: '#fff', opacity: 0, }, draggable: true, name: `pick-rect-${i}`, }); pickRect.toFront(); const rectBBox = rect.getBBox(); const centerX = (rectBBox.minX + rectBBox.maxX) / 2; tickRects.push({ rect, pickRect, value: d.date, x: centerX, y: rectBBox.minY, }); let label; if (tickLabelFormatter) { label = tickLabelFormatter(d); if (!isString(label) && label) { // return true label = d.date; } } else if (i % Math.round(ticksLength / 10) === 0) { label = d.date; } if (label) { labels.push(label); // draw tick lines const lineStartY = rectBBox.maxY + padding * 2; sliceGroup.addShape('line', { attrs: { stroke: '#BFBFBF', x1: centerX, y1: lineStartY, x2: centerX, y2: lineStartY + labelLineHeight, }, name: 'tick-line' }); const labelStartY = lineStartY + labelLineHeight + padding; const text = sliceGroup.addShape('text', { attrs: { fill: '#8c8c8c', stroke: '#fff', lineWidth: 1, x: centerX, y: labelStartY, textAlign: 'center', text: label, textBaseline: 'top', fontSize: 10, fontFamily: this.fontFamily || 'Arial, sans-serif', ...tickLabelStyle }, capture: false, name: 'tick-label' }); const textBBox = text.getBBox(); if (textBBox.maxX > width) { text.attr('textAlign', 'right'); } else if (textBBox.minX < 0) { text.attr('textAlign', 'left'); } if (isNumber(rotate) && labels.length !== 10) { const matrix = transform( [1, 0, 0, 0, 1, 0, 0, 0, 1], [ ['t', -centerX!, -labelStartY!], ['r', rotate], ['t', centerX - 5, labelStartY + 2], ], ); text.attr({ textAlign: 'left', matrix, }); } if (labels.length === 1) { text.attr({ textAlign: 'left', }); } else if (labels.length === 10) { text.attr({ textAlign: 'right', }); } // draw tick labels } }); this.tickRects = tickRects; // 渲染播放、快进和后退的控制按钮 const group = this.group; this.currentSpeed = 1; this.controllerBtnGroup = new ControllerBtn({ group, x: this.x, y: this.y + height + 5, width, height: 40, hideTimeTypeController: true, speed: this.currentSpeed, fontFamily: this.fontFamily || 'Arial, sans-serif', }); } private initEvent() { const sliceGroup = this.sliceGroup; sliceGroup.on('click', (e) => { const targetRect = e.target; if (targetRect.get('type') !== 'rect' || !targetRect.get('name')) return; const id = parseInt(targetRect.get('name').split('-')[2], 10); if (!isNaN(id)) { const tickRects = this.tickRects; // cancel the selected ticks const unselectedTickStyle = this.unselectedTickStyle; tickRects.forEach((tickRect) => { tickRect.rect.attr(unselectedTickStyle); }); const selectedTickStyle = this.selectedTickStyle; tickRects[id].rect.attr(selectedTickStyle); this.startTickRectId = id; this.endTickRectId = id; const ticksLength = tickRects.length; const start = id / ticksLength; this.graph.emit(VALUE_CHANGE, { value: [start, start] }); } }); sliceGroup.on('dragstart', (e) => { const tickRects = this.tickRects; // cancel the selected ticks const unselectedTickStyle = this.unselectedTickStyle; tickRects.forEach((tickRect) => { tickRect.rect.attr(unselectedTickStyle); }); const targetRect = e.target; const id = parseInt(targetRect.get('name').split('-')[2], 10); const selectedTickStyle = this.selectedTickStyle; tickRects[id].rect.attr(selectedTickStyle); this.startTickRectId = id; const ticksLength = tickRects.length; const start = id / ticksLength; this.graph.emit(VALUE_CHANGE, { value: [start, start] }); this.dragging = true; }); sliceGroup.on('dragover', (e) => { if (!this.dragging) return; if (e.target.get('type') !== 'rect') return; const id = parseInt(e.target.get('name').split('-')[2], 10); const startTickRectId = this.startTickRectId; const tickRects = this.tickRects; const selectedTickStyle = this.selectedTickStyle; const unselectedTickStyle = this.unselectedTickStyle; for (let i = 0; i < tickRects.length; i++) { const style = i >= startTickRectId && i <= id ? selectedTickStyle : unselectedTickStyle; tickRects[i].rect.attr(style); } const ticksLength = tickRects.length; this.endTickRectId = id; const start = startTickRectId / ticksLength; const end = id / ticksLength; this.graph.emit(VALUE_CHANGE, { value: [start, end] }); }); sliceGroup.on('drop', (e) => { if (!this.dragging) return; this.dragging = false; if (e.target.get('type') !== 'rect') return; const startTickRectId = this.startTickRectId; const id = parseInt(e.target.get('name').split('-')[2], 10); if (id < startTickRectId) return; const selectedTickStyle = this.selectedTickStyle; const tickRects = this.tickRects; tickRects[id].rect.attr(selectedTickStyle); this.endTickRectId = id; const ticksLength = tickRects.length; const start = startTickRectId / ticksLength; const end = id / ticksLength; this.graph.emit(VALUE_CHANGE, { value: [start, end] }); }); // tooltip const { tooltipBackgroundColor, tooltipFomatter, canvas } = this; const tooltip = new TimeBarTooltip({ container: canvas.get('container') as HTMLElement, backgroundColor: tooltipBackgroundColor, }); const tickRects = this.tickRects; tickRects.forEach((tickRect) => { const pickRect = tickRect.pickRect; pickRect.on('mouseenter', (e) => { const rect = e.target; if (rect.get('type') !== 'rect') return; const id = parseInt(rect.get('name').split('-')[2], 10); const clientPoint = canvas.getClientByPoint(tickRects[id].x, tickRects[id].y); tooltip.show({ x: tickRects[id].x, y: tickRects[id].y, clientX: clientPoint.x, clientY: clientPoint.y, text: tooltipFomatter ? tooltipFomatter(tickRects[id].value) : tickRects[id].value, }); }); pickRect.on('mouseleave', (e) => { tooltip.hide(); }); }); // play controller events const group = this.group; // 播放区按钮控制 /** 播放/暂停事件 */ group.on(`${PLAY_PAUSE_BTN}:click`, () => { this.isPlay = !this.isPlay; this.changePlayStatus(); }); // 处理前进一步的事件 group.on(`${NEXT_STEP_BTN}:click`, () => { this.updateStartEnd(1); }); // 处理后退一步的事件 group.on(`${PRE_STEP_BTN}:click`, () => { this.updateStartEnd(-1); }); group.on(TIMEBAR_CONFIG_CHANGE, ({ type, speed }) => { this.currentSpeed = speed; }); } private changePlayStatus(isSync = true) { this.controllerBtnGroup.playButton.update({ isPlay: this.isPlay, }); if (this.isPlay) { // 开始播放 this.playHandler = this.startPlay(); this.graph.emit(TIMELINE_START, null); } else { // 结束播放 if (this.playHandler) { if (typeof window !== 'undefined') window.cancelAnimationFrame(this.playHandler); if (isSync) { this.graph.emit(TIMELINE_END, null); } } } } private startPlay() { return typeof window !== 'undefined' ? window.requestAnimationFrame(() => { const speed = this.currentSpeed; // 一分钟刷新一次 if (this.frameCount % (60 / speed) === 0) { this.frameCount = 0; this.updateStartEnd(1); } this.frameCount++; if (this.isPlay) { this.playHandler = this.startPlay(); } }) : undefined; } private updateStartEnd(sign) { const self = this; const tickRects = this.tickRects; const ticksLength = tickRects.length; const unselectedTickStyle = this.unselectedTickStyle; const selectedTickStyle = this.selectedTickStyle; const previousEndTickRectId = self.endTickRectId; if (sign > 0) { self.endTickRectId++; } else { tickRects[self.endTickRectId].rect.attr(unselectedTickStyle); self.endTickRectId--; } // 若此时 start 与 end 不同,范围前进/后退/播放 if (previousEndTickRectId !== self.startTickRectId) { if (self.endTickRectId < self.startTickRectId) { self.startTickRectId = self.endTickRectId; } } else { // 否则是单帧的前进/后退/播放 for (let i = self.startTickRectId; i <= self.endTickRectId - 1; i++) { tickRects[i].rect.attr(unselectedTickStyle); } self.startTickRectId = self.endTickRectId; } if (tickRects[self.endTickRectId]) { tickRects[self.endTickRectId].rect.attr(selectedTickStyle); const start = self.startTickRectId / ticksLength; const end = self.endTickRectId / ticksLength; this.graph.emit(VALUE_CHANGE, { value: [start, end] }); } } public destory() { this.graph.off(VALUE_CHANGE, () => { /* do nothing */}); const group = this.sliceGroup; group.off('click'); group.off('dragstart'); group.off('dragover'); group.off('drop'); this.tickRects.forEach((tickRect) => { const pickRect = tickRect.pickRect; pickRect.off('mouseenter'); pickRect.off('mouseleave'); }); this.tickRects.length = 0; group.off(`${PLAY_PAUSE_BTN}:click`); group.off(`${NEXT_STEP_BTN}:click`); group.off(`${PRE_STEP_BTN}:click`); group.off(TIMEBAR_CONFIG_CHANGE); this.sliceGroup.destroy(); } }
the_stack
interface DOMElement {} interface Promise<T> {} declare class Registry {} declare class Transition {} declare namespace Handlebars { class SafeString {} } declare class JQuery {} declare module 'ember' { export namespace Ember { /** * Define an assertion that will throw an exception if the condition is not met. Ember build tools will remove any calls to `Ember.assert()` when doing a production build. Example: */ function assert(desc: string, test: boolean); /** * Display a warning with the provided message. Ember build tools will remove any calls to `Ember.warn()` when doing a production build. */ function warn(message: string, test: boolean); /** * Display a debug notice. Ember build tools will remove any calls to `Ember.debug()` when doing a production build. */ function debug(message: string); /** * Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). Ember build tools will remove any calls to `Ember.deprecate()` when doing a production build. */ function deprecate(message: string, test: boolean); /** * Alias an old, deprecated method with its new counterpart. */ function deprecateFunc(message: string, func: Function): Function; /** * Run a function meant for debugging. Ember build tools will remove any calls to `Ember.runInDebug()` when doing a production build. */ function runInDebug(func: Function); /** * Identical to `Object.create()`. Implements if not available natively. */ function create(); /** * Array polyfills to support ES5 features in older browsers. */ var ArrayPolyfills: any; /** * Debug parameter you can turn on. This will log all bindings that fire to the console. This should be disabled in production code. Note that you can also enable this from the console or temporarily. */ var LOG_BINDINGS: boolean; /** * Global helper method to create a new binding. Just pass the root object along with a `to` and `from` path to create and connect the binding. */ function bind(obj: {}, to: string, from: string): Binding; function oneWay(obj: {}, to: string, from: string): Binding; /** * This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with mixins or via `Ember.defineProperty()`. */ function computed(...dependentKeys: string[]): ComputedProperty; function computed(func: Function): ComputedProperty; /** * Returns the cached value for a property, if one exists. This can be useful for peeking at the value of a computed property that is generated lazily, without accidentally causing it to be created. */ function cacheFor(obj: {}, key: string): {}; /** * A computed property that returns true if the value of the dependent property is null, an empty string, empty array, or empty function. */ function 'computed.empty'(dependentKey: string): ComputedProperty; /** * A computed property that returns true if the value of the dependent property is NOT null, an empty string, empty array, or empty function. */ function 'computed.notEmpty'(dependentKey: string): ComputedProperty; /** * A computed property that returns true if the value of the dependent property is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. */ function 'computed.none'(dependentKey: string): ComputedProperty; /** * A computed property that returns the inverse boolean value of the original value for the dependent property. */ function 'computed.not'(dependentKey: string): ComputedProperty; /** * A computed property that converts the provided dependent property into a boolean value. */ function 'computed.bool'(dependentKey: string): ComputedProperty; /** * A computed property which matches the original value for the dependent property against a given RegExp, returning `true` if they values matches the RegExp and `false` if it does not. */ function 'computed.match'(dependentKey: string, regexp: RegExp): ComputedProperty; /** * A computed property that returns true if the provided dependent property is equal to the given value. */ function 'computed.equal'(dependentKey: string, value: string|number|{}): ComputedProperty; /** * A computed property that returns true if the provided dependent property is greater than the provided value. */ function 'computed.gt'(dependentKey: string, value: number): ComputedProperty; /** * A computed property that returns true if the provided dependent property is greater than or equal to the provided value. */ function 'computed.gte'(dependentKey: string, value: number): ComputedProperty; /** * A computed property that returns true if the provided dependent property is less than the provided value. */ function 'computed.lt'(dependentKey: string, value: number): ComputedProperty; /** * A computed property that returns true if the provided dependent property is less than or equal to the provided value. */ function 'computed.lte'(dependentKey: string, value: number): ComputedProperty; /** * A computed property that performs a logical `and` on the original values for the provided dependent properties. */ function 'computed.and'(dependentKey: string): ComputedProperty; /** * A computed property which performs a logical `or` on the original values for the provided dependent properties. */ function 'computed.or'(dependentKey: string): ComputedProperty; /** * A computed property that returns the first truthy value from a list of dependent properties. */ function 'computed.any'(dependentKey: string): ComputedProperty; /** * A computed property that returns the array of values for the provided dependent properties. */ function 'computed.collect'(dependentKey: string): ComputedProperty; /** * Creates a new property that is an alias for another property on an object. Calls to `get` or `set` this property behave as though they were called on the original property. */ function 'computed.alias'(dependentKey: string): ComputedProperty; /** * Where `computed.alias` aliases `get` and `set`, and allows for bidirectional data flow, `computed.oneWay` only provides an aliased `get`. The `set` will not mutate the upstream property, rather causes the current property to become the value set. This causes the downstream property to permanently diverge from the upstream property. */ function 'computed.oneWay'(dependentKey: string): ComputedProperty; /** * This is a more semantically meaningful alias of `computed.oneWay`, whose name is somewhat ambiguous as to which direction the data flows. */ function 'computed.reads'(dependentKey: string): ComputedProperty; /** * Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides a readOnly one way binding. Very often when using `computed.oneWay` one does not also want changes to propogate back up, as they will replace the value. */ function 'computed.readOnly'(dependentKey: string): ComputedProperty; /** * DEPRECATED: Use `Ember.computed.oneWay` or custom CP with default instead. * A computed property that acts like a standard getter and setter, but returns the value at the provided `defaultPath` if the property itself has not been set to a value */ function 'computed.defaultTo'(defaultPath: string): ComputedProperty; /** * Creates a new property that is an alias for another property on an object. Calls to `get` or `set` this property behave as though they were called on the original property, but also print a deprecation warning. */ function 'computed.deprecatingAlias'(dependentKey: string): ComputedProperty; var VERSION: string; /** * Standard environmental variables. You can define these in a global `EmberENV` variable before loading Ember to control various configuration settings. */ var ENV: {}; /** * Determines whether Ember should enhance some built-in object prototypes to provide a more friendly API. If enabled, a few methods will be added to `Function`, `String`, and `Array`. `Object.prototype` will not be enhanced, which is the one that causes most trouble for people. */ var EXTEND_PROTOTYPES: boolean; /** * Determines whether Ember logs a full stack trace during deprecation warnings */ var LOG_STACKTRACE_ON_DEPRECATION: boolean; /** * Determines whether Ember should add ECMAScript 5 Array shims to older browsers. */ var SHIM_ES5: boolean; /** * Determines whether Ember logs info about version of used libraries */ var LOG_VERSION: boolean; /** * Add an event listener */ function addListener(obj: any, eventName: string, target: {}|Function, method: Function|string, once: boolean); /** * Remove an event listener */ function removeListener(obj: any, eventName: string, target: {}|Function, method: Function|string); /** * Send an event. The execution of suspended listeners is skipped, and once listeners are removed. A listener without a target is executed on the passed object. If an array of actions is not passed, the actions stored on the passed object are invoked. */ function sendEvent(obj: any, eventName: string, params: Ember.Array, actions: Ember.Array): void; /** * Define a property as a function that should be executed when a specified event or events are triggered. */ function on(eventNames: string, func: Function): void; /** * A value is blank if it is empty or a whitespace string. */ function isBlank(obj: {}): boolean; /** * Verifies that a value is `null` or an empty string, empty array, or empty function. */ function isEmpty(obj: {}): boolean; /** * Returns true if the passed value is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. */ function isNone(obj: {}): boolean; /** * A value is present if it not `isBlank`. */ function isPresent(obj: {}): boolean; /** * Returns all of the keys defined on an object or hash. This is useful when inspecting objects for debugging. On browsers that support it, this uses the native `Object.keys` implementation. */ function keys(obj: {}): Ember.Array; /** * Merge the contents of two objects together into the first object. */ function merge(original: {}, updates: {}): {}; function mixin(obj: any, mixins: any): void; /** * Denotes a required property for a mixin */ function required(); /** * Makes a method available via an additional name. */ function aliasMethod(methodName: string): Descriptor; /** * Specify a method that observes property changes. */ function observer(propertyNames: string, func: Function): void; /** * Specify a method that observes property changes. */ function immediateObserver(propertyNames: string, func: Function): void; /** * When observers fire, they are called with the arguments `obj`, `keyName`. */ function beforeObserver(propertyNames: string, func: Function): void; function addObserver(obj: any, path: string, targetOrMethod: {}|Function, method: Function|string); function removeObserver(obj: any, path: string, target: {}|Function, method: Function|string); function addBeforeObserver(obj: any, path: string, target: {}|Function, method: Function|string); function removeBeforeObserver(obj: any, path: string, target: {}|Function, method: Function|string); /** * This function is called just before an object property is about to change. It will notify any before observers and prepare caches among other things. */ function propertyWillChange(obj: {}, keyName: string): void; /** * This function is called just after an object property has changed. It will notify any observers and clear caches among other things. */ function propertyDidChange(obj: {}, keyName: string): void; /** * Make a series of property changes together in an exception-safe way. */ function changeProperties(callback: Function, binding: any); /** * Gets the value of a property on an object. If the property is computed, the function will be invoked. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked. */ function get(obj: {}, keyName: string): {}; /** * Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `setUnknownProperty` method then that will be invoked as well. */ function set(obj: {}, keyName: string, value: {}): {}; /** * Error-tolerant form of `Ember.set`. Will not blow up if any part of the chain is `undefined`, `null`, or destroyed. */ function trySet(obj: {}, path: string, value: {}); /** * Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. */ function setProperties(obj: any, properties: {}): void; /** * Returns true if the passed object is an array or Array-like. */ function isArray(obj: {}): boolean; /** * Forces the passed object to be part of an array. If the object is already an array or array-like, it will return the object. Otherwise, it will add the object to an array. If obj is `null` or `undefined`, it will return an empty array. */ function makeArray(obj: {}): Ember.Array; /** * Checks to see if the `methodName` exists on the `obj`. */ function canInvoke(obj: {}, methodName: string): boolean; /** * Checks to see if the `methodName` exists on the `obj`, and if it does, invokes it with the arguments passed. */ function tryInvoke(obj: {}, methodName: string, args: Ember.Array): any; /** * Provides try/finally functionality, while working around Safari's double finally bug. */ function tryFinally(tryable: Function, finalizer: Function, binding: {}): any; /** * Provides try/catch/finally functionality, while working around Safari's double finally bug. */ function tryCatchFinally(tryable: Function, catchable: Function, finalizer: Function, binding: {}): any; /** * Returns a consistent type for the passed item. */ function typeOf(item: {}): string; /** * Convenience method to inspect an object. This method will attempt to convert the object into a useful string description. */ function inspect(obj: {}): string; /** * Tears down the meta on an object so that it can be garbage collected. Multiple calls will have no effect. */ function destroy(obj: {}): void; /** * Creates a computed property which operates on dependent arrays and is updated with "one at a time" semantics. When items are added or removed from the dependent array(s) an array computed only operates on the change instead of re-evaluating the entire array. This should return an array, if you'd like to use "one at a time" semantics and compute some value other then an array look at `Ember.reduceComputed`. */ function arrayComputed(...dependentKeys: string[]): ComputedProperty; function arrayComputed(options: {}): ComputedProperty; /** * Creates a computed property which operates on dependent arrays and is updated with "one at a time" semantics. When items are added or removed from the dependent array(s) a reduce computed only operates on the change instead of re-evaluating the entire array. */ function reduceComputed(...dependentKeys: string[]): ComputedProperty; function reduceComputed(options: {}): ComputedProperty; /** * A computed property that returns the sum of the value in the dependent array. */ function 'computed.sum'(dependentKey: string): ComputedProperty; /** * A computed property that calculates the maximum value in the dependent array. This will return `-Infinity` when the dependent array is empty. */ function 'computed.max'(dependentKey: string): ComputedProperty; /** * A computed property that calculates the minimum value in the dependent array. This will return `Infinity` when the dependent array is empty. */ function 'computed.min'(dependentKey: string): ComputedProperty; /** * Returns an array mapped via the callback */ function 'computed.map'(dependentKey: string, callback: Function): ComputedProperty; /** * Returns an array mapped to the specified key. */ function 'computed.mapBy'(dependentKey: string, propertyKey: string): ComputedProperty; /** * DEPRECATED: Use `Ember.computed.mapBy` instead */ function 'computed.mapProperty'(dependentKey: any, propertyKey: any); /** * Filters the array by the callback. */ function 'computed.filter'(dependentKey: string, callback: Function): ComputedProperty; /** * Filters the array by the property and value */ function 'computed.filterBy'(dependentKey: string, propertyKey: string, value: any): ComputedProperty; /** * DEPRECATED: Use `Ember.computed.filterBy` instead */ function 'computed.filterProperty'(dependentKey: any, propertyKey: any, value: any); /** * A computed property which returns a new array with all the unique elements from one or more dependent arrays. */ function 'computed.uniq'(propertyKey: string): ComputedProperty; /** * Alias for [Ember.computed.uniq](/api/#method_computed_uniq). */ function 'computed.union'(propertyKey: string): ComputedProperty; /** * A computed property which returns a new array with all the duplicated elements from two or more dependent arrays. */ function 'computed.intersect'(propertyKey: string): ComputedProperty; /** * A computed property which returns a new array with all the properties from the first dependent array that are not in the second dependent array. */ function 'computed.setDiff'(setAProperty: string, setBProperty: string): ComputedProperty; /** * A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function. */ function 'computed.sort'(dependentKey: string, sortDefinition: string): ComputedProperty; /** * Creates a property that lazily looks up another controller in the container. Can only be used when defining another controller. */ function 'inject.controller'(name: string): InjectedProperty; /** * Detects when a specific package of Ember (e.g. 'Ember.Handlebars') has fully loaded and is available for extension. */ function onLoad(name: string, callback: Function); /** * Called when an Ember.js package (e.g Ember.Handlebars) has finished loading. Triggers any callbacks registered for this event. */ function runLoadHooks(name: string, object: {}); /** * Creates an `Ember.NativeArray` from an Array like object. Does not modify the original object. Ember.A is not needed if `Ember.EXTEND_PROTOTYPES` is `true` (the default value). However, it is recommended that you use Ember.A when creating addons for ember or when you can not guarantee that `Ember.EXTEND_PROTOTYPES` will be `true`. */ function A(): NativeArray; /** * Creates a property that lazily looks up a service in the container. There are no restrictions as to what objects a service can be injected into. */ function 'inject.service'(name: string): InjectedProperty; /** * Defines the hash of localized strings for the current language. Used by the `Ember.String.loc()` helper. To localize, add string values to this hash. */ var STRINGS: {}; /** * This will compare two javascript values of possibly different types. It will tell you which one is greater than the other by returning: */ function compare(v: {}, w: {}): number; /** * Creates a clone of the passed object. This function can take just about any type of object and create a clone of it, including primitive values (which are not actually cloned because they are immutable). */ function copy(obj: {}, deep: boolean): {}; /** * Compares two objects, returning true if they are logically equal. This is a deeper comparison than a simple triple equal. For sets it will compare the internal objects. For any other object that implements `isEqual()` it will respect that method. */ function isEqual(a: {}, b: {}): boolean; /** * Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime. */ var TEMPLATES: {}; /** * Alias for jQuery */ function $(); export namespace Handlebars { /** * DEPRECATED: * Lookup both on root and on window. If the path starts with a keyword, the corresponding object will be looked up in the template's data hash and used to resolve the path. */ function get(root: {}, path: string, options: {}); /** * Register a bound handlebars helper. Bound helpers behave similarly to regular handlebars helpers, with the added ability to re-render when the underlying data changes. */ function registerBoundHelper(name: string, function: Function, dependentKeys: string); /** * A helper function used by `registerBoundHelper`. Takes the provided Handlebars helper function fn and returns it in wrapped bound helper form. */ function makeBoundHelper(function: Function, dependentKeys: string); /** * Register a bound helper or custom view helper. */ function helper(name: string, function: Function|View, dependentKeys: string); /** * Used for precompilation of Ember Handlebars templates. This will not be used during normal app execution. */ function precompile(value: string|{}, asObject: boolean); /** * The entry point for Ember Handlebars. This replaces the default `Handlebars.compile` and turns on template-local data and String parameters. */ function compile(string: string): Function; export class helpers { /** * `bind-attr` allows you to create a binding between DOM element attributes and Ember objects. For example: */ 'bind-attr'(options: {}): string; /** * DEPRECATED: * See `bind-attr` */ bindAttr(context: Function, options: {}): string; /** * DEPRECATED: Use `{{each}}` helper instead. * `{{collection}}` is a `Ember.Handlebars` helper for adding instances of `Ember.CollectionView` to a template. See [Ember.CollectionView](/api/classes/Ember.CollectionView.html) for additional information on how a `CollectionView` functions. */ collection(path: string, options: {}): string; /** * `log` allows you to output the value of variables in the current rendering context. `log` also accepts primitive types such as strings or numbers. */ log(property: string); /** * Execute the `debugger` statement in the current context. */ debugger(property: string); /** * The `{{#each}}` helper loops over elements in a collection. It is an extension of the base Handlebars `{{#each}}` helper. */ each(name: string, path: string, options: {}); /** * See [boundIf](/api/classes/Ember.Handlebars.helpers.html#method_boundIf) and [unboundIf](/api/classes/Ember.Handlebars.helpers.html#method_unboundIf) */ if(context: Function, options: {}): string; unless(context: Function, options: {}): string; /** * Calls [Ember.String.loc](/api/classes/Ember.String.html#method_loc) with the provided string. */ loc(str: string); /** * The `partial` helper renders another template without changing the template context: */ partial(partialName: string); /** * DEPRECATED: */ template(templateName: string); /** * `unbound` allows you to output a property without binding. *Important:* The output will not be updated if the property changes. Use with caution. */ unbound(property: string): string; /** * `{{view}}` inserts a new instance of an `Ember.View` into a template passing its options to the `Ember.View`'s `create` method and using the supplied block as the view's own template. */ view(path: string, options: {}): string; /** * Use the `{{with}}` helper when you want to aliases the to a new name. It's helpful for semantic clarity and to retain default scope or to reference from another `{{with}}` block. */ with(context: Function, options: {}): string; /** * `{{yield}}` denotes an area of a template that will be rendered inside of another template. It has two main uses: */ yield(options: {}): string; /** * The `{{input}}` helper inserts an HTML `<input>` tag into the template, with a `type` value of either `text` or `checkbox`. If no `type` is provided, `text` will be the default value applied. The attributes of `{{input}}` match those of the native HTML tag as closely as possible for these two types. ## Use as text field An `{{input}}` with no `type` or a `type` of `text` will render an HTML text input. The following HTML attributes can be set via the helper: */ input(options: {}); /** * `{{textarea}}` inserts a new instance of `<textarea>` tag into the template. The attributes of `{{textarea}}` match those of the native HTML tags as closely as possible. */ textarea(options: {}); /** * The `{{action}}` helper provides a useful shortcut for registering an HTML element within a template for a single DOM event and forwarding that interaction to the template's controller or specified `target` option. */ action(actionName: string, context: {}, options: {}); /** * The `{{link-to}}` helper renders a link to the supplied `routeName` passing an optionally supplied model to the route as its `model` context of the route. The block for `{{link-to}}` becomes the innerHTML of the rendered element: */ 'link-to'(routeName: string, context: {}, options: {}): string; /** * This is a sub-expression to be used in conjunction with the link-to helper. It will supply url query parameters to the target route. */ 'query-params'(hash: {}): string; /** * DEPRECATED: * See [link-to](/api/classes/Ember.Handlebars.helpers.html#method_link-to) */ linkTo(routeName: string, context: {}): string; /** * The `outlet` helper is a placeholder that the router will fill in with the appropriate template based on the current state of the application. */ outlet(property: string): string; /** * Calling ``{{render}}`` from within a template will insert another template that matches the provided name. The inserted template will access its properties on its own controller (rather than the controller of the parent template). */ render(name: string, contextString: {}, options: {}): string; } /** * Override the the opcode compiler and JavaScript compiler for Handlebars. */ export class Compiler { } export class JavaScriptCompiler { } } export namespace Test { /** * Loads a route, sets up any controllers, and renders any templates associated with the route as though a real user had triggered the route change while using your app. */ function visit(url: string): RSVP.Promise<any>; /** * Clicks an element and triggers any actions triggered by the element's `click` event. */ function click(selector: string): RSVP.Promise<any>; /** * Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode */ function keyEvent(selector: string, type: string, keyCode: number): RSVP.Promise<any>; /** * Fills in an input element with some text. */ function fillIn(selector: string, text: string): RSVP.Promise<any>; /** * Finds an element in the context of the app's container element. A simple alias for `app.$(selector)`. */ function find(selector: string): {}; /** * Like `find`, but throws an error if the element selector returns no results. */ function findWithAssert(selector: string): {}; /** * Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. */ function wait(value: {}): RSVP.Promise<any>; /** * Returns the currently active route name. */ function currentRouteName(): {}; /** * Returns the current path. */ function currentPath(): {}; /** * Returns the current URL. */ function currentURL(): {}; /** * Pauses the current test - this is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. */ function pauseTest(): {}; /** * Triggers the given DOM event on the element identified by the provided selector. */ function triggerEvent(selector: string, context: string, type: string, options: {}): RSVP.Promise<any>; /** * This hook defers the readiness of the application, so that you can start the app when your tests are ready to run. It also sets the router's location to 'none', so that the window's location will not be modified (preventing both accidental leaking of state between tests and interference with your testing framework). */ function setupForTesting(); /** * `registerHelper` is used to register a test helper that will be injected when `App.injectTestHelpers` is called. */ function registerHelper(name: string, helperMethod: Function, options: {}); /** * `registerAsyncHelper` is used to register an async test helper that will be injected when `App.injectTestHelpers` is called. */ function registerAsyncHelper(name: string, helperMethod: Function); /** * Remove a previously added helper method. */ function unregisterHelper(name: string); /** * Used to register callbacks to be fired whenever `App.injectTestHelpers` is called. */ function onInjectHelpers(callback: Function); /** * This returns a thenable tailored for testing. It catches failed `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` callback in the last chained then. */ function promise(resolver: Function); /** * Used to allow ember-testing to communicate with a specific testing framework. */ var adapter: any; /** * Replacement for `Ember.RSVP.resolve` The only difference is this uses an instance of `Ember.Test.Promise` */ function resolve(The: any); /** * This allows ember-testing to play nicely with other asynchronous events, such as an application that is waiting for a CSS3 transition or an IndexDB transaction. */ function registerWaiter(context: {}, callback: Function); /** * `unregisterWaiter` is used to unregister a callback that was registered with `registerWaiter`. */ function unregisterWaiter(context: {}, callback: Function); /** * This property contains the testing helpers for the current application. These are created once you call `injectTestHelpers` on your `Ember.Application` instance. The included helpers are also available on the `window` object by default, but can be used from this object on the individual application also. */ var testHelpers: {}; /** * This property indicates whether or not this application is currently in testing mode. This is set when `setupForTesting` is called on the current application. */ var testing: boolean; /** * This will be used as the container to inject the test helpers into. By default the helpers are injected into `window`. */ var helperContainer: {}; /** * This injects the test helpers into the `helperContainer` object. If an object is provided it will be used as the helperContainer. If `helperContainer` is not set it will default to `window`. If a function of the same name has already been defined it will be cached (so that it can be reset if the helper is removed with `unregisterHelper` or `removeTestHelpers`). */ function injectTestHelpers(); /** * This removes all helpers that have been registered, and resets and functions that were overridden by the helpers. */ function removeTestHelpers(); /** * The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks. */ export class Adapter { /** * This callback will be called whenever an async operation is about to start. */ asyncStart(); /** * This callback will be called whenever an async operation has completed. */ asyncEnd(); /** * Override this method with your testing framework's false assertion. This function is called whenever an exception occurs causing the testing promise to fail. */ exception(error: string); } /** * This class implements the methods defined by Ember.Test.Adapter for the QUnit testing framework. */ export class QUnitAdapter extends Adapter { } } /** * `Ember.ControllerMixin` provides a standard interface for all classes that compose Ember's controller layer: `Ember.Controller`, `Ember.ArrayController`, and `Ember.ObjectController`. */ export class ControllerMixin implements ActionHandler { parent: Container; children: Ember.Array; resolver: function; registry: InheritingDict; cache: InheritingDict; typeInjections: InheritingDict; injections: {}; /** * Returns a new child of the current container. These children are configured to correctly inherit from the current container. */ child(): Container; /** * Registers a factory for later injection. */ register(fullName: string, factory: Function, options: {}); /** * Unregister a fullName */ unregister(fullName: string); /** * Given a fullName return the corresponding factory. */ resolve(fullName: string): Function; /** * A hook that can be used to describe how the resolver will attempt to find the factory. */ describe(fullName: string): string; /** * A hook to enable custom fullName normalization behaviour */ normalizeFullName(fullName: string): string; /** * normalize a fullName based on the applications conventions */ normalize(fullName: string): string; makeToString(factory: any, fullName: string): Function; /** * Given a fullName return a corresponding instance. */ lookup(fullName: string, options: {}): any; /** * Given a fullName return the corresponding factory. */ lookupFactory(fullName: string): any; /** * Given a fullName check if the container is aware of its factory or singleton instance. */ has(fullName: string): boolean; /** * Allow registering options for all factories of a type. */ optionsForType(type: string, options: {}); options(fullName: string, options: {}); /** * Defines injection rules. */ injection(factoryName: string, property: string, injectionName: string); /** * Defines factory injection rules. */ factoryInjection(factoryName: string, property: string, injectionName: string); /** * A depth first traversal, destroying the container, its descendant containers and all their managed objects. */ destroy(); reset(); /** * An array of other controller objects available inside instances of this controller via the `controllers` property: */ needs: Ember.Array; /** * DEPRECATED: Use `needs` instead */ controllerFor(); /** * Stores the instances of other controllers available from within this controller. Any controller listed by name in the `needs` property will be accessible by name through this property. */ controllers: {}; /** * Defines which query parameters the controller accepts. If you give the names ['category','page'] it will bind the values of these query parameters to the variables `this.category` and `this.page` */ queryParams: any; /** * Transition the application into another route. The route may be either a single route or route path: */ transitionToRoute(name: string, ...models: any[]); /** * DEPRECATED: */ transitionTo(); /** * Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to `transitionToRoute` in all other respects. */ replaceRoute(name: string, ...models: any[]); /** * DEPRECATED: */ replaceWith(); /** * The object to which actions from the view should be sent. */ target: any; /** * The controller's current model. When retrieving or modifying a controller's model, this property should be used instead of the `content` property. */ model: any; /** * The collection of functions, keyed by name, available on this `ActionHandler` as action targets. */ actions: {}; /** * Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. */ send(actionName: string, context: any); } /** * An instance of `Ember.Application` is the starting point for every Ember application. It helps to instantiate, initialize and coordinate the many objects that make up your app. */ export class Application extends Namespace { /** * The root DOM element of the Application. This can be specified as an element or a [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). */ rootElement: DOMElement; /** * The `Ember.EventDispatcher` responsible for delegating events to this application's views. */ eventDispatcher: EventDispatcher; /** * The DOM events for which the event dispatcher should listen. */ customEvents: {}; /** * Use this to defer readiness until some condition is true. */ deferReadiness(); /** * Call `advanceReadiness` after any asynchronous setup logic has completed. Each call to `deferReadiness` must be matched by a call to `advanceReadiness` or the application will never become ready and routing will not begin. */ advanceReadiness(); /** * Registers a factory that can be used for dependency injection (with `App.inject`) or for service lookup. Each factory is registered with a full name including two parts: `type:name`. */ register(fullName: string, factory: Function, options: {}); /** * Define a dependency injection onto a specific factory or all factories of a type. */ inject(factoryNameOrType: string, property: string, injectionName: string); /** * Reset the application. This is typically used only in tests. It cleans up the application in the following order: */ reset(); /** * Set this to provide an alternate class to `Ember.DefaultResolver` */ resolver: any; /** * Initializer receives an object which has the following attributes: `name`, `before`, `after`, `initialize`. The only required attribute is `initialize, all others are optional. */ initializer(initializer: {}); } /** * The DefaultResolver defines the default lookup rules to resolve container lookups before consulting the container for registered items: */ export class DefaultResolver extends Object { /** * This will be set to the Application instance when it is created. */ namespace: any; /** * This method is called via the container's resolver method. It parses the provided `fullName` and then looks up and returns the appropriate template or class. */ resolve(fullName: string): {}; /** * Convert the string name of the form 'type:name' to a Javascript object with the parsed aspects of the name broken out. */ parseName(fullName: string); /** * Returns a human-readable description for a fullName. Used by the Application namespace in assertions to describe the precise name of the class that Ember is looking for, rather than container keys. */ lookupDescription(fullName: string); /** * Given a parseName object (output from `parseName`), apply the conventions expected by `Ember.Router` */ useRouterNaming(parsedName: {}); /** * Look up the template in Ember.TEMPLATES */ resolveTemplate(parsedName: {}); /** * Lookup the view using `resolveOther` */ resolveView(parsedName: {}); /** * Lookup the controller using `resolveOther` */ resolveController(parsedName: {}); /** * Lookup the route using `resolveOther` */ resolveRoute(parsedName: {}); /** * Lookup the model on the Application namespace */ resolveModel(parsedName: {}); /** * Look up the specified object (from parsedName) on the appropriate namespace (usually on the Application) */ resolveHelper(parsedName: {}); /** * Look up the specified object (from parsedName) on the appropriate namespace (usually on the Application) */ resolveOther(parsedName: {}); } /** * The `ContainerDebugAdapter` helps the container and resolver interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. */ export class ContainerDebugAdapter { /** * The container of the application being debugged. This property will be injected on creation. */ container: any; /** * The resolver instance of the application being debugged. This property will be injected on creation. */ resolver: any; /** * Returns true if it is possible to catalog a list of available classes in the resolver for a given type. */ canCatalogEntriesByType(type: string): boolean; /** * Returns the available classes a given type. */ catalogEntriesByType(type: string): Ember.Array; } /** * The `DataAdapter` helps a data persistence library interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. */ export class DataAdapter { /** * The container of the application being debugged. This property will be injected on creation. */ container: any; /** * The container-debug-adapter which is used to list all models. */ containerDebugAdapter: any; /** * Specifies how records can be filtered. Records returned will need to have a `filterValues` property with a key for every name in the returned array. */ getFilters(): Ember.Array; /** * Fetch the model types and observe them for changes. */ watchModelTypes(typesAdded: Function, typesUpdated: Function): Function; /** * Fetch the records of a given type and observe them for changes. */ watchRecords(recordsAdded: Function, recordsUpdated: Function, recordsRemoved: Function): Function; } /** * The internal class used to create text inputs when the `{{input}}` helper is used with `type` of `checkbox`. */ export class Checkbox extends View { } /** * The `Ember.Select` view class renders a [select](https://developer.mozilla.org/en/HTML/Element/select) HTML element, allowing the user to choose from a list of options. */ export class Select extends View { /** * The `multiple` attribute of the select element. Indicates whether multiple options can be selected. */ multiple: boolean; /** * The `disabled` attribute of the select element. Indicates whether the element is disabled from interactions. */ disabled: boolean; /** * The `required` attribute of the select element. Indicates whether a selected option is required for form validation. */ required: boolean; /** * The list of options. */ content: Ember.Array; /** * When `multiple` is `false`, the element of `content` that is currently selected, if any. */ selection: {}; /** * In single selection mode (when `multiple` is `false`), value can be used to get the current selection's value or set the selection by it's value. */ value: string; /** * If given, a top-most dummy option will be rendered to serve as a user prompt. */ prompt: string; /** * The path of the option labels. See [content](/api/classes/Ember.Select.html#property_content). */ optionLabelPath: string; /** * The path of the option values. See [content](/api/classes/Ember.Select.html#property_content). */ optionValuePath: string; /** * The path of the option group. When this property is used, `content` should be sorted by `optionGroupPath`. */ optionGroupPath: string; /** * The view class for optgroup. */ groupView: View; /** * The view class for option. */ optionView: View; } /** * The internal class used to create textarea element when the `{{textarea}}` helper is used. */ export class TextArea extends Component implements TextSupport { /** * The action to be sent when the user presses the return key. */ action: string; /** * The event that should send the action. */ onEvent: string; /** * Whether the `keyUp` event that triggers an `action` to be sent continues propagating to other views. */ bubbles: boolean; /** * Called when the user inserts a new line. */ insertNewline(event: Event); /** * Called when the user hits escape. */ cancel(event: Event); /** * Called when the text area is focused. */ focusIn(event: Event); /** * Called when the text area is blurred. */ focusOut(event: Event); /** * Called when the user presses a key. Enabled by setting the `onEvent` property to `keyPress`. */ keyPress(event: Event); /** * Called when the browser triggers a `keyup` event on the element. */ keyUp(event: Event); /** * Called when the browser triggers a `keydown` event on the element. */ keyDown(event: Event); /** * Send an `action` with an `actionContext` to a `target`. The action, actionContext and target will be retrieved from properties of the object. For example: */ triggerAction(opts: {}): boolean; } /** * The internal class used to create text inputs when the `{{input}}` helper is used with `type` of `text`. See [Handlebars.helpers.input](/api/classes/Ember.Handlebars.helpers.html#method_input) for usage details. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s layout section for more information. */ export class TextField extends Component implements TextSupport { /** * The `value` attribute of the input element. As the user inputs text, this property is updated live. */ value: string; /** * The `type` attribute of the input element. */ type: string; /** * The `size` of the text field in characters. */ size: string; /** * The `pattern` attribute of input element. */ pattern: string; /** * The `min` attribute of input element used with `type="number"` or `type="range"`. */ min: string; /** * The `max` attribute of input element used with `type="number"` or `type="range"`. */ max: string; /** * The action to be sent when the user presses the return key. */ action: string; /** * The event that should send the action. */ onEvent: string; /** * Whether the `keyUp` event that triggers an `action` to be sent continues propagating to other views. */ bubbles: boolean; /** * Called when the user inserts a new line. */ insertNewline(event: Event); /** * Called when the user hits escape. */ cancel(event: Event); /** * Called when the text area is focused. */ focusIn(event: Event); /** * Called when the text area is blurred. */ focusOut(event: Event); /** * Called when the user presses a key. Enabled by setting the `onEvent` property to `keyPress`. */ keyPress(event: Event); /** * Called when the browser triggers a `keyup` event on the element. */ keyUp(event: Event); /** * Called when the browser triggers a `keydown` event on the element. */ keyDown(event: Event); /** * Send an `action` with an `actionContext` to a `target`. The action, actionContext and target will be retrieved from properties of the object. For example: */ triggerAction(opts: {}): boolean; } /** * Shared mixin used by `Ember.TextField` and `Ember.TextArea`. */ export class TextSupport extends Mixin implements TargetActionSupport { /** * The action to be sent when the user presses the return key. */ action: string; /** * The event that should send the action. */ onEvent: string; /** * Whether the `keyUp` event that triggers an `action` to be sent continues propagating to other views. */ bubbles: boolean; /** * Called when the user inserts a new line. */ insertNewline(event: Event); /** * Called when the user hits escape. */ cancel(event: Event); /** * Called when the text area is focused. */ focusIn(event: Event); /** * Called when the text area is blurred. */ focusOut(event: Event); /** * Called when the user presses a key. Enabled by setting the `onEvent` property to `keyPress`. */ keyPress(event: Event); /** * Called when the browser triggers a `keyup` event on the element. */ keyUp(event: Event); /** * Called when the browser triggers a `keydown` event on the element. */ keyDown(event: Event); /** * Send an `action` with an `actionContext` to a `target`. The action, actionContext and target will be retrieved from properties of the object. For example: */ triggerAction(opts: {}): boolean; } /** * `Ember._HandlebarsBoundView` is a private view created by the Handlebars `{{bind}}` helpers that is used to keep track of bound properties. */ export class _HandlebarsBoundView extends _MetamorphView { /** * The function used to determine if the `displayTemplate` or `inverseTemplate` should be rendered. This should be a function that takes a value and returns a Boolean. */ shouldDisplayFunc: Function; /** * Whether the template rendered by this view gets passed the context object of its parent template, or gets passed the value of retrieving `path` from the `pathRoot`. */ preserveContext: boolean; /** * If `preserveContext` is true, this is the object that will be used to render the template. */ previousContext: {}; /** * The template to render when `shouldDisplayFunc` evaluates to `true`. */ displayTemplate: Function; /** * The template to render when `shouldDisplayFunc` evaluates to `false`. */ inverseTemplate: Function; /** * Determines which template to invoke, sets up the correct state based on that logic, then invokes the default `Ember.View` `render` implementation. */ render(buffer: RenderBuffer); } export class _Metamorph { } export class _MetamorphView extends View implements _Metamorph { } export class _SimpleMetamorphView extends CoreView implements _Metamorph { } /** * Defines string helper methods including string formatting and localization. Unless `Ember.EXTEND_PROTOTYPES.String` is `false` these methods will also be added to the `String.prototype` as well. */ export class String { /** * Mark a string as safe for unescaped output with Handlebars. If you return HTML from a Handlebars helper, use this function to ensure Handlebars does not escape the HTML. */ static htmlSafe(): Handlebars.SafeString; /** * Apply formatting options to the string. This will look for occurrences of "%@" in your string and substitute them with the arguments you pass into this method. If you want to control the specific order of replacement, you can add a number after the key as well to indicate which argument you want to insert. */ fmt(str: string, formats: Ember.Array): string; /** * Formats the passed string, but first looks up the string in the localized strings hash. This is a convenient way to localize text. See `Ember.String.fmt()` for more information on formatting. */ loc(str: string, formats: Ember.Array): string; /** * Splits a string into separate units separated by spaces, eliminating any empty strings in the process. This is a convenience method for split that is mostly useful when applied to the `String.prototype`. */ w(str: string): Ember.Array; /** * Converts a camelized string into all lower case separated by underscores. */ decamelize(str: string): string; /** * Replaces underscores, spaces, or camelCase with dashes. */ dasherize(str: string): string; /** * Returns the lowerCamelCase form of a string. */ camelize(str: string): string; /** * Returns the UpperCamelCase form of a string. */ classify(str: string): string; /** * More general than decamelize. Returns the lower\_case\_and\_underscored form of a string. */ underscore(str: string): string; /** * Returns the Capitalized form of a string */ capitalize(str: string): string; } /** * Platform specific methods and feature detectors needed by the framework. */ export class platform { /** * Set to true if the platform supports native getters and setters. */ hasPropertyAccessors: any; /** * Identical to `Object.defineProperty()`. Implements as much functionality as possible if not available natively. */ defineProperty(obj: {}, keyName: string, desc: {}): void; } /** * An `Ember.Binding` connects the properties of two objects so that whenever the value of one property changes, the other property will be changed also. */ export class Binding { /** * This copies the Binding so it can be connected to another object. */ copy(): Binding; /** * This will set `from` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. */ from(path: string): Binding; /** * This will set the `to` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. */ to(path: string|any[]): Binding; /** * Creates a new Binding instance and makes it apply in a single direction. A one-way binding will relay changes on the `from` side object (supplied as the `from` argument) the `to` side, but not the other way around. This means that if you change the "to" side directly, the "from" side may have a different value. */ oneWay(from: string, flag: boolean): Binding; toString(): string; /** * Attempts to connect this binding instance so that it can receive and relay changes. This method will raise an exception if you have not set the from/to properties yet. */ connect(obj: {}): Binding; /** * Disconnects the binding instance. Changes will no longer be relayed. You will not usually need to call this method. */ disconnect(obj: {}): Binding; } /** * A computed property transforms an object's function into a property. */ export class ComputedProperty extends Descriptor { /** * Properties are cacheable by default. Computed property will automatically cache the return value of your function until one of the dependent keys changes. */ cacheable(aFlag: boolean): ComputedProperty; /** * Call on a computed property to set it into non-cached mode. When in this mode the computed property will not automatically cache the return value. */ volatile(): ComputedProperty; /** * Call on a computed property to set it into read-only mode. When in this mode the computed property will throw an error when set. */ readOnly(): ComputedProperty; /** * Sets the dependent keys on this computed property. Pass any number of arguments containing key paths that this computed property depends on. */ property(path: string): ComputedProperty; /** * In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. */ meta(meta: {}); /** * Access the value of the function backing the computed property. If this property has already been cached, return the cached result. Otherwise, call the function passing the property name as an argument. */ get(keyName: string): {}; /** * Set the value of a computed property. If the function that backs your computed property does not accept arguments then the default action for setting would be to define the property on the current object, and set the value of the property to the value being set. */ set(keyName: string, newValue: {}, oldValue: string): {}; } /** * Hash of enabled Canary features. Add to this before creating your application. */ export class FEATURES { /** * Test that a feature is enabled. Parsed by Ember's build tools to leave experimental features out of beta/stable builds. */ isEnabled(feature: string): boolean; } /** * Defines some convenience methods for working with Enumerables. `Ember.EnumerableUtils` uses `Ember.ArrayPolyfills` when necessary. */ export class EnumerableUtils { /** * Calls the map function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-map method when necessary. */ map(obj: {}, callback: Function, thisArg: {}): Ember.Array; /** * Calls the forEach function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-forEach method when necessary. */ forEach(obj: {}, callback: Function, thisArg: {}); /** * Calls the filter function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-filter method when necessary. */ filter(obj: {}, callback: Function, thisArg: {}): Ember.Array; /** * Calls the indexOf function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-indexOf method when necessary. */ indexOf(obj: {}, callback: Function, index: {}); /** * Returns an array of indexes of the first occurrences of the passed elements on the passed object. */ indexesOf(obj: {}, elements: Ember.Array): Ember.Array; /** * Adds an object to an array. If the array already includes the object this method has no effect. */ addObject(array: Ember.Array, item: {}): void; /** * Removes an object from an array. If the array does not contain the passed object this method has no effect. */ removeObject(array: Ember.Array, item: {}): void; /** * Replaces objects in an array with the passed objects. */ replace(array: Ember.Array, idx: number, amt: number, objects: Ember.Array): Ember.Array; /** * Calculates the intersection of two arrays. This method returns a new array filled with the records that the two passed arrays share with each other. If there is no intersection, an empty array will be returned. */ intersection(array1: Ember.Array, array2: Ember.Array): Ember.Array; } /** * A subclass of the JavaScript Error object for use in Ember. */ export class Error { } /** * Read-only property that returns the result of a container lookup. */ export class InjectedProperty extends Descriptor { /** * To get multiple properties at once, call `Ember.getProperties` with an object followed by a list of strings or an array: */ getProperties(obj: any, ...list: string[]): {}; } /** * The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember. */ export class Instrumentation { /** * Notifies event's subscribers, calls `before` and `after` hooks. */ instrument(name: string, payload: {}, callback: Function, binding: {}); /** * Subscribes to a particular event or instrumented block of code. */ subscribe(pattern: string, object: {}): Subscriber; /** * Unsubscribes from a particular event or instrumented block of code. */ unsubscribe(subscriber: {}); /** * Resets `Ember.Instrumentation` by flushing list of subscribers. */ reset(); } /** * Inside Ember-Metal, simply uses the methods from `imports.console`. Override this to provide more robust logging functionality. */ export class Logger { /** * Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. */ log(args: any); /** * Prints the arguments to the console with a warning icon. You can pass as many arguments as you want and they will be joined together with a space. */ warn(args: any); /** * Prints the arguments to the console with an error icon, red text and a stack trace. You can pass as many arguments as you want and they will be joined together with a space. */ error(args: any); /** * Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. */ info(args: any); /** * Logs the arguments to the console in blue text. You can pass as many arguments as you want and they will be joined together with a space. */ debug(args: any); /** * If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace. */ assert(bool: boolean); } /** * This class is used internally by Ember and Ember Data. Please do not use it at this time. We plan to clean it up and add many tests soon. */ export class OrderedSet { static create(): OrderedSet; clear(); add(obj: any, guid: any): OrderedSet; /** * DEPRECATED: */ remove(obj: any, _guid: any): boolean; delete(obj: any, _guid: any): boolean; isEmpty(): boolean; has(obj: any): boolean; forEach(fn: Function, self: any); toArray(): Ember.Array; copy(): OrderedSet; } /** * A Map stores values indexed by keys. Unlike JavaScript's default Objects, the keys of a Map can be any JavaScript object. */ export class Map { static create(); /** * This property will change as the number of objects in the map changes. */ size: number; /** * Retrieve the value associated with a given key. */ get(key: any): any; /** * Adds a value to the map. If a value for the given key has already been provided, the new value will replace the old value. */ set(key: any, value: any): Map; /** * DEPRECATED: see delete Removes a value from the map for an associated key. */ remove(key: any): boolean; /** * Removes a value from the map for an associated key. */ delete(key: any): boolean; /** * Check whether a key is present. */ has(key: any): boolean; /** * Iterate over all the keys and values. Calls the function once for each key, passing in value, key, and the map being iterated over, in that order. */ forEach(callback: Function, self: any); clear(); copy(): Map; } export class MapWithDefault extends Map { static create(options: any): MapWithDefault|Map; /** * Retrieve the value associated with a given key. */ get(key: any): any; copy(): MapWithDefault; } /** * The `Ember.Mixin` class allows you to create mixins, whose properties can be added to other classes. For instance, */ export class Mixin { static create(args: any); reopen(args: any); apply(obj: any): void; detect(obj: any): boolean; } /** * Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties. */ export class Descriptor { } /** * Runs the passed target and method inside of a RunLoop, ensuring any deferred actions including bindings and views updates are flushed at the end. */ export class run { /** * If no run-loop is present, it creates a new one. If a run loop is present it will queue itself to run on the existing run-loops action queue. */ join(target: {}, method: Function|string, ...args: any[]): {}; /** * Allows you to specify which context to call the specified function in while adding the execution of that function to the Ember run loop. This ability makes this method a great way to asynchronusly integrate third-party libraries into your Ember application. */ bind(target: {}, method: Function|string, ...args: any[]): {}; /** * Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `run.end()`. This is a lower-level way to use a RunLoop instead of using `run()`. */ begin(): void; /** * Ends a RunLoop. This must be called sometime after you call `run.begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `run()`. */ end(): void; /** * Array of named queues. This array determines the order in which queues are flushed at the end of the RunLoop. You can define your own queues by simply adding the queue name to this array. Normally you should not need to inspect or modify this property. */ queues: Ember.Array; /** * Adds the passed target/method and any optional arguments to the named queue to be executed at the end of the RunLoop. If you have not already started a RunLoop when calling this method one will be started for you automatically. */ schedule(queue: string, target: {}, method: string|Function, ...args: any[]): void; /** * Immediately flushes any events scheduled in the 'sync' queue. Bindings use this queue so this method is a useful way to immediately force all bindings in the application to sync. */ sync(): void; /** * Invokes the passed target/method and optional arguments after a specified period of time. The last parameter of this method must always be a number of milliseconds. */ later(target: {}, method: Function|string, ...args: any[]): {}; later(target: {}, method: Function|string, wait: number): {}; /** * Schedule a function to run one time during the current RunLoop. This is equivalent to calling `scheduleOnce` with the "actions" queue. */ once(target: {}, method: Function|string, ...args: any[]): {}; /** * Schedules a function to run one time in a given queue of the current RunLoop. Calling this method with the same queue/target/method combination will have no effect (past the initial call). */ scheduleOnce(queue: string, target: {}, method: Function|string, ...args: any[]): {}; /** * Schedules an item to run from within a separate run loop, after control has been returned to the system. This is equivalent to calling `run.later` with a wait time of 1ms. */ next(target: {}, method: Function|string, ...args: any[]): {}; /** * Cancels a scheduled item. Must be a value returned by `run.later()`, `run.once()`, `run.next()`, `run.debounce()`, or `run.throttle()`. */ cancel(timer: {}): boolean; /** * Delay calling the target method until the debounce period has elapsed with no additional debounce calls. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the target method is called. */ debounce(target: {}, method: Function|string, ...args: any[]): Ember.Array; debounce(target: {}, method: Function|string, wait: number, immediate: boolean): Ember.Array; /** * Ensure that the target method is never called more frequently than the specified spacing period. The target method is called immediately. */ throttle(target: {}, method: Function|string, ...args: any[]): Ember.Array; throttle(target: {}, method: Function|string, spacing: number, immediate: boolean): Ember.Array; } /** * Ember.Location returns an instance of the correct implementation of the `location` API. */ export class Location { /** * Sets the private `_outlets` object on the view. */ init(); /** * Manually fill any of a view's `{{outlet}}` areas with the supplied view. */ connectOutlet(outletName: string, view: {}); /** * Removes an outlet from the view. */ disconnectOutlet(outletName: string); /** * DEPRECATED: Use the container to lookup the location implementation that you need. * This is deprecated in favor of using the container to lookup the location implementation as desired. */ create(options: {}): {}; /** * DEPRECATED: Register your custom location implementation with the container directly. * This is deprecated in favor of using the container to register the location implementation as desired. */ registerImplementation(name: string, implementation: {}); } /** * Ember.AutoLocation will select the best location option based off browser support with the priority order: history, hash, none. */ export class AutoLocation { /** * Selects the best location option based off browser support and returns an instance of that Location class. */ create(); } /** * `Ember.HashLocation` implements the location API using the browser's hash. At present, it relies on a `hashchange` event existing in the browser. */ export class HashLocation extends Object { } /** * Ember.HistoryLocation implements the location API using the browser's history.pushState API. */ export class HistoryLocation extends Object { /** * Will be pre-pended to path upon state change */ rootURL: any; } /** * Ember.NoneLocation does not interact with the browser. It is useful for testing, or when you need to manage state with your Router, but temporarily don't want it to muck with the URL (for example when you embed your application in a larger page). */ export class NoneLocation extends Object { } /** * The `Ember.Route` class is used to define individual routes. Refer to the [routing guide](http://emberjs.com/guides/routing/) for documentation. */ export class Route extends Object implements ActionHandler { /** * Configuration hash for this route's queryParams. The possible configuration options and their defaults are as follows (assuming a query param whose URL key is `page`): */ queryParams: {}; /** * Retrieves parameters, for current route using the state.params variable and getQueryParamsFor, using the supplied routeName. */ paramsFor(routename: string); /** * Serializes the query parameter key */ serializeQueryParamKey(controllerPropertyName: string); /** * Serializes value of the query parameter based on defaultValueType */ serializeQueryParam(value: {}, urlKey: string, defaultValueType: string); /** * Deserializes value of the query parameter based on defaultValueType */ deserializeQueryParam(value: {}, urlKey: string, defaultValueType: string); /** * A hook you can use to reset controller values either when the model changes or the route is exiting. */ resetController(controller: Controller, isExiting: boolean, transition: {}); /** * The name of the view to use by default when rendering this routes template. */ viewName: string; /** * The name of the template to use by default when rendering this routes template. */ templateName: string; /** * The name of the controller to associate with this route. */ controllerName: string; /** * The controller associated with this route. */ controller: Controller; /** * DEPRECATED: Please use `actions` instead. */ events(); /** * This hook is executed when the router completely exits this route. It is not executed when the model for the route changes. */ deactivate(); /** * This hook is executed when the router enters the route. It is not executed when the model for the route changes. */ activate(); /** * Transition the application into another route. The route may be either a single route or route path: */ transitionTo(name: string, ...models: any[]): Transition; /** * Perform a synchronous transition into another route without attempting to resolve promises, update the URL, or abort any currently active asynchronous transitions (i.e. regular transitions caused by `transitionTo` or URL changes). */ intermediateTransitionTo(name: string, ...models: any[]); /** * Refresh the model on this route and any child routes, firing the `beforeModel`, `model`, and `afterModel` hooks in a similar fashion to how routes are entered when transitioning in from other route. The current route params (e.g. `article_id`) will be passed in to the respective model hooks, and if a different model is returned, `setupController` and associated route hooks will re-fire as well. */ refresh(): Transition; /** * Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to `transitionTo` in all other respects. See 'transitionTo' for additional information regarding multiple models. */ replaceWith(name: string, ...models: any[]): Transition; /** * Sends an action to the router, which will delegate it to the currently active route hierarchy per the bubbling rules explained under `actions`. */ send(name: string, ...args: any[]); /** * This hook is the first of the route entry validation hooks called when an attempt is made to transition into a route or one of its children. It is called before `model` and `afterModel`, and is appropriate for cases when: */ beforeModel(transition: Transition, queryParams: {}): Promise<any>; /** * This hook is called after this route's model has resolved. It follows identical async/promise semantics to `beforeModel` but is provided the route's resolved model in addition to the `transition`, and is therefore suited to performing logic that can only take place after the model has already resolved. */ afterModel(resolvedModel: {}, transition: Transition, queryParams: {}): Promise<any>; /** * A hook you can implement to optionally redirect to another route. */ redirect(model: {}, transition: Transition); /** * A hook you can implement to convert the URL into the model for this route. */ model(params: {}, transition: Transition, queryParams: {}): {}|Promise<any>; findModel(type: string, value: {}); /** * Store property provides a hook for data persistence libraries to inject themselves. */ store(store: {}); /** * A hook you can implement to convert the route's model into parameters for the URL. */ serialize(model: {}, params: Ember.Array): {}; /** * A hook you can use to setup the controller for the current route. */ setupController(controller: Controller, model: {}); /** * Returns the controller for a particular route or name. */ controllerFor(name: string): Controller; /** * Generates a controller for a route. */ generateController(name: string, model: {}); /** * Returns the model of a parent (or any ancestor) route in a route hierarchy. During a transition, all routes must resolve a model object, and if a route needs access to a parent route's model in order to resolve a model (or just reuse the model from a parent), it can call `this.modelFor(theNameOfParentRoute)` to retrieve it. */ modelFor(name: string): {}; /** * A hook you can use to render the template for the current route. */ renderTemplate(controller: {}, model: {}); /** * `render` is used to render a template into a region of another template (indicated by an `{{outlet}}`). `render` is used both during the entry phase of routing (via the `renderTemplate` hook) and later in response to user interaction. */ render(name: string, options: {}); /** * Disconnects a view that has been rendered into an outlet. */ disconnectOutlet(options: {}|string); /** * The collection of functions, keyed by name, available on this `ActionHandler` as action targets. */ actions: {}; } /** * The `Ember.Router` class manages the application state and URLs. Refer to the [routing guide](http://emberjs.com/guides/routing/) for documentation. */ export class Router extends Object { /** * The `location` property determines the type of URL's that your application will use. */ location: any; /** * Represents the URL of the root of the application, often '/'. This prefix is assumed on all routes defined on this router. */ rootURL: any; /** * Represents the current URL. */ url(): string; /** * The `Router.map` function allows you to define mappings from URLs to routes and resources in your application. These mappings are defined within the supplied callback function using `this.resource` and `this.route`. */ map(callback: any); } /** * `Ember.LinkView` renders an element whose `click` event triggers a transition of the application's instance of `Ember.Router` to a supplied route by name. */ export class LinkView extends View { /** * Used to determine when this LinkView is active. */ currentWhen: any; /** * Sets the `title` attribute of the `LinkView`'s HTML element. */ title: any; /** * Sets the `rel` attribute of the `LinkView`'s HTML element. */ rel: any; /** * The CSS class to apply to `LinkView`'s element when its `active` property is `true`. */ activeClass: string; /** * The CSS class to apply to `LinkView`'s element when its `loading` property is `true`. */ loadingClass: string; /** * The CSS class to apply to a `LinkView`'s element when its `disabled` property is `true`. */ disabledClass: string; /** * Determines whether the `LinkView` will trigger routing via the `replaceWith` routing strategy. */ replace: boolean; /** * By default the `{{link-to}}` helper will bind to the `href` and `title` attributes. It's discourage that you override these defaults, however you can push onto the array if needed. */ attributeBindings: Ember.Array; /** * By default the `{{link-to}}` helper will bind to the `active`, `loading`, and `disabled` classes. It is discouraged to override these directly. */ classNameBindings: Ember.Array; /** * By default the `{{link-to}}` helper responds to the `click` event. You can override this globally by setting this property to your custom event name. */ eventName: string; /** * An overridable method called when LinkView objects are instantiated. */ init(); /** * Accessed as a classname binding to apply the `LinkView`'s `disabledClass` CSS `class` to the element when the link is disabled. When `true` interactions with the element will not trigger route changes. */ disabled: any; /** * Accessed as a classname binding to apply the `LinkView`'s `activeClass` CSS `class` to the element when the link is active. */ active: any; /** * Accessed as a classname binding to apply the `LinkView`'s `loadingClass` CSS `class` to the element when the link is loading. */ loading: any; /** * Sets the element's `href` attribute to the url for the `LinkView`'s targeted route. */ href: any; /** * The default href value to use while a link-to is loading. Only applies when tagName is 'a' */ loadingHref: string; /** * Sets the `target` attribute of the `LinkView`'s anchor element. */ target: any; } /** * A computed property whose dependent keys are arrays and which is updated with "one at a time" semantics. */ export class ReduceComputedProperty extends ComputedProperty { } /** * `Ember.ArrayController` provides a way for you to publish a collection of objects so that you can easily bind to the collection from a Handlebars `#each` helper, an `Ember.CollectionView`, or other controllers. */ export class ArrayController extends ArrayProxy implements SortableMixin, ControllerMixin { /** * The controller used to wrap items, if any. If the value is a string, it will be used to lookup the container for the controller. As an alternative, you can also provide a controller class as the value. */ itemController: string; /** * Return the name of the controller to wrap items, or `null` if items should be returned directly. The default implementation simply returns the `itemController` property, but subclasses can override this method to return different controllers for different objects. */ lookupItemController(object: {}): string; /** * Specifies which properties dictate the `arrangedContent`'s sort order. */ sortProperties: Ember.Array; /** * Specifies the `arrangedContent`'s sort direction. Sorts the content in ascending order by default. Set to `false` to use descending order. */ sortAscending: boolean; /** * The function used to compare two values. You can override this if you want to do custom comparisons. Functions must be of the type expected by Array#sort, i.e., */ sortFunction: Function; /** * Overrides the default `arrangedContent` from `ArrayProxy` in order to sort by `sortFunction`. Also sets up observers for each `sortProperty` on each item in the content Array. */ arrangedContent: any; /** * __Required.__ You must implement this method to apply this mixin. */ addObject(object: {}): {}; /** * Adds each object in the passed enumerable to the receiver. */ addObjects(objects: Enumerable): {}; /** * __Required.__ You must implement this method to apply this mixin. */ removeObject(object: {}): {}; /** * Removes each object in the passed enumerable from the receiver. */ removeObjects(objects: Enumerable): {}; /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerables content. */ '[]': Ember.Array; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; parent: Container; children: Ember.Array; resolver: function; registry: InheritingDict; cache: InheritingDict; typeInjections: InheritingDict; injections: {}; /** * Returns a new child of the current container. These children are configured to correctly inherit from the current container. */ child(): Container; /** * Registers a factory for later injection. */ register(fullName: string, factory: Function, options: {}); /** * Unregister a fullName */ unregister(fullName: string); /** * Given a fullName return the corresponding factory. */ resolve(fullName: string): Function; /** * A hook that can be used to describe how the resolver will attempt to find the factory. */ describe(fullName: string): string; /** * A hook to enable custom fullName normalization behaviour */ normalizeFullName(fullName: string): string; /** * normalize a fullName based on the applications conventions */ normalize(fullName: string): string; makeToString(factory: any, fullName: string): Function; /** * Given a fullName return a corresponding instance. */ lookup(fullName: string, options: {}): any; /** * Given a fullName return the corresponding factory. */ lookupFactory(fullName: string): any; /** * Given a fullName check if the container is aware of its factory or singleton instance. */ has(fullName: string): boolean; /** * Allow registering options for all factories of a type. */ optionsForType(type: string, options: {}); options(fullName: string, options: {}); /** * Defines injection rules. */ injection(factoryName: string, property: string, injectionName: string); /** * Defines factory injection rules. */ factoryInjection(factoryName: string, property: string, injectionName: string); /** * A depth first traversal, destroying the container, its descendant containers and all their managed objects. */ destroy(); reset(); /** * An array of other controller objects available inside instances of this controller via the `controllers` property: */ needs: Ember.Array; /** * DEPRECATED: Use `needs` instead */ controllerFor(); /** * Stores the instances of other controllers available from within this controller. Any controller listed by name in the `needs` property will be accessible by name through this property. */ controllers: {}; /** * Defines which query parameters the controller accepts. If you give the names ['category','page'] it will bind the values of these query parameters to the variables `this.category` and `this.page` */ queryParams: any; /** * Transition the application into another route. The route may be either a single route or route path: */ transitionToRoute(name: string, ...models: any[]); /** * DEPRECATED: */ transitionTo(); /** * Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to `transitionToRoute` in all other respects. */ replaceRoute(name: string, ...models: any[]); /** * DEPRECATED: */ replaceWith(); /** * The object to which actions from the view should be sent. */ target: any; /** * The controller's current model. When retrieving or modifying a controller's model, this property should be used instead of the `content` property. */ model: any; /** * The collection of functions, keyed by name, available on this `ActionHandler` as action targets. */ actions: {}; /** * Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. */ send(actionName: string, context: any); } export class Controller extends Object implements ControllerMixin { parent: Container; children: Ember.Array; resolver: function; registry: InheritingDict; cache: InheritingDict; typeInjections: InheritingDict; injections: {}; /** * Returns a new child of the current container. These children are configured to correctly inherit from the current container. */ child(): Container; /** * Registers a factory for later injection. */ register(fullName: string, factory: Function, options: {}); /** * Unregister a fullName */ unregister(fullName: string); /** * Given a fullName return the corresponding factory. */ resolve(fullName: string): Function; /** * A hook that can be used to describe how the resolver will attempt to find the factory. */ describe(fullName: string): string; /** * A hook to enable custom fullName normalization behaviour */ normalizeFullName(fullName: string): string; /** * normalize a fullName based on the applications conventions */ normalize(fullName: string): string; makeToString(factory: any, fullName: string): Function; /** * Given a fullName return a corresponding instance. */ lookup(fullName: string, options: {}): any; /** * Given a fullName return the corresponding factory. */ lookupFactory(fullName: string): any; /** * Given a fullName check if the container is aware of its factory or singleton instance. */ has(fullName: string): boolean; /** * Allow registering options for all factories of a type. */ optionsForType(type: string, options: {}); options(fullName: string, options: {}); /** * Defines injection rules. */ injection(factoryName: string, property: string, injectionName: string); /** * Defines factory injection rules. */ factoryInjection(factoryName: string, property: string, injectionName: string); /** * A depth first traversal, destroying the container, its descendant containers and all their managed objects. */ destroy(); reset(); /** * An array of other controller objects available inside instances of this controller via the `controllers` property: */ needs: Ember.Array; /** * DEPRECATED: Use `needs` instead */ controllerFor(); /** * Stores the instances of other controllers available from within this controller. Any controller listed by name in the `needs` property will be accessible by name through this property. */ controllers: {}; /** * Defines which query parameters the controller accepts. If you give the names ['category','page'] it will bind the values of these query parameters to the variables `this.category` and `this.page` */ queryParams: any; /** * Transition the application into another route. The route may be either a single route or route path: */ transitionToRoute(name: string, ...models: any[]); /** * DEPRECATED: */ transitionTo(); /** * Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to `transitionToRoute` in all other respects. */ replaceRoute(name: string, ...models: any[]); /** * DEPRECATED: */ replaceWith(); /** * The object to which actions from the view should be sent. */ target: any; /** * The controller's current model. When retrieving or modifying a controller's model, this property should be used instead of the `content` property. */ model: any; /** * The collection of functions, keyed by name, available on this `ActionHandler` as action targets. */ actions: {}; /** * Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. */ send(actionName: string, context: any); } /** * `Ember.ObjectController` is part of Ember's Controller layer. It is intended to wrap a single object, proxying unhandled attempts to `get` and `set` to the underlying model object, and to forward unhandled action attempts to its `target`. */ export class ObjectController extends ObjectProxy implements ControllerMixin { parent: Container; children: Ember.Array; resolver: function; registry: InheritingDict; cache: InheritingDict; typeInjections: InheritingDict; injections: {}; /** * Returns a new child of the current container. These children are configured to correctly inherit from the current container. */ child(): Container; /** * Registers a factory for later injection. */ register(fullName: string, factory: Function, options: {}); /** * Unregister a fullName */ unregister(fullName: string); /** * Given a fullName return the corresponding factory. */ resolve(fullName: string): Function; /** * A hook that can be used to describe how the resolver will attempt to find the factory. */ describe(fullName: string): string; /** * A hook to enable custom fullName normalization behaviour */ normalizeFullName(fullName: string): string; /** * normalize a fullName based on the applications conventions */ normalize(fullName: string): string; makeToString(factory: any, fullName: string): Function; /** * Given a fullName return a corresponding instance. */ lookup(fullName: string, options: {}): any; /** * Given a fullName return the corresponding factory. */ lookupFactory(fullName: string): any; /** * Given a fullName check if the container is aware of its factory or singleton instance. */ has(fullName: string): boolean; /** * Allow registering options for all factories of a type. */ optionsForType(type: string, options: {}); options(fullName: string, options: {}); /** * Defines injection rules. */ injection(factoryName: string, property: string, injectionName: string); /** * Defines factory injection rules. */ factoryInjection(factoryName: string, property: string, injectionName: string); /** * A depth first traversal, destroying the container, its descendant containers and all their managed objects. */ destroy(); reset(); /** * An array of other controller objects available inside instances of this controller via the `controllers` property: */ needs: Ember.Array; /** * DEPRECATED: Use `needs` instead */ controllerFor(); /** * Stores the instances of other controllers available from within this controller. Any controller listed by name in the `needs` property will be accessible by name through this property. */ controllers: {}; /** * Defines which query parameters the controller accepts. If you give the names ['category','page'] it will bind the values of these query parameters to the variables `this.category` and `this.page` */ queryParams: any; /** * Transition the application into another route. The route may be either a single route or route path: */ transitionToRoute(name: string, ...models: any[]); /** * DEPRECATED: */ transitionTo(); /** * Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to `transitionToRoute` in all other respects. */ replaceRoute(name: string, ...models: any[]); /** * DEPRECATED: */ replaceWith(); /** * The object to which actions from the view should be sent. */ target: any; /** * The controller's current model. When retrieving or modifying a controller's model, this property should be used instead of the `content` property. */ model: any; /** * The collection of functions, keyed by name, available on this `ActionHandler` as action targets. */ actions: {}; /** * Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. */ send(actionName: string, context: any); } /** * `Ember.ProxyMixin` forwards all properties not defined by the proxy itself to a proxied `content` object. See Ember.ObjectProxy for more details. */ export class ProxyMixin { /** * The object whose properties will be forwarded. */ content: {}; } /** * The `Ember.ActionHandler` mixin implements support for moving an `actions` property to an `_actions` property at extend time, and adding `_actions` to the object's mergedProperties list. */ export class ActionHandler { /** * The collection of functions, keyed by name, available on this `ActionHandler` as action targets. */ actions: {}; /** * Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. */ send(actionName: string, context: any); } /** * This mixin implements Observer-friendly Array-like behavior. It is not a concrete implementation, but it can be used up by other classes that want to appear like arrays. */ export class Array implements Enumerable { /** * Your array must support the `length` property. Your replace methods should set this property whenever it changes. */ length: number; /** * Returns the object at the given `index`. If the given `index` is negative or is greater or equal than the array length, returns `undefined`. */ objectAt(idx: number): any; /** * This returns the objects at the specified indexes, using `objectAt`. */ objectsAt(indexes: Ember.Array): Ember.Array; /** * This is the handler for the special array content property. If you get this property, it will return this. If you set this property to a new array, it will replace the current content. */ '[]': any; /** * Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice. */ slice(beginIndex: Integer, endIndex: Integer): Ember.Array; /** * Returns the index of the given object's first occurrence. If no `startAt` argument is given, the starting location to search is 0. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ indexOf(object: {}, startAt: number): number; /** * Returns the index of the given object's last occurrence. If no `startAt` argument is given, the search starts from the last position. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ lastIndexOf(object: {}, startAt: number): number; /** * Adds an array observer to the receiving array. The array observer object normally must implement two methods: */ addArrayObserver(target: {}, opts: {}): Ember.Array; /** * Removes an array observer from the object if the observer is current registered. Calling this method multiple times with the same object will have no effect. */ removeArrayObserver(target: {}, opts: {}): Ember.Array; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasArrayObservers: boolean; /** * If you are implementing an object that supports `Ember.Array`, call this method just before the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * If you are implementing an object that supports `Ember.Array`, call this method just after the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * Returns a special object that can be used to observe individual properties on the array. Just get an equivalent property on this object and it will return an enumerable that maps automatically to the named key on the member objects. */ '@each': any; /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; } /** * Implements some standard methods for comparing objects. Add this mixin to any class you create that can compare its instances. */ export class Comparable { /** * Override to return the result of the comparison of the two parameters. The compare method should return: */ compare(a: {}, b: {}): Integer; } /** * The ControllerContentModelAliasDeprecation mixin is used to provide a useful deprecation warning when specifying `content` directly on a `Ember.Controller` (without also specifying `model`). */ export class ControllerContentModelAliasDeprecation { } /** * Implements some standard methods for copying an object. Add this mixin to any object you create that can create a copy of itself. This mixin is added automatically to the built-in array. */ export class Copyable { /** * Override to return a copy of the receiver. Default implementation raises an exception. */ copy(deep: boolean): {}; /** * If the object implements `Ember.Freezable`, then this will return a new copy if the object is not frozen and the receiver if the object is frozen. */ frozenCopy(): {}; } export class Deferred { /** * Add handlers to be called when the Deferred object is resolved or rejected. */ then(resolve: Function, reject: Function); /** * Resolve a Deferred object and call any `doneCallbacks` with the given args. */ resolve(); /** * Reject a Deferred object and call any `failCallbacks` with the given args. */ reject(); } /** * This mixin defines the common interface implemented by enumerable objects in Ember. Most of these methods follow the standard Array iteration API defined up to JavaScript 1.8 (excluding language-specific features that cannot be emulated in older versions of JavaScript). */ export class Enumerable { /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerables content. */ '[]': Ember.Array; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; } /** * This mixin allows for Ember objects to subscribe to and emit events. */ export class Evented { /** * Subscribes to a named event with given function. */ on(name: string, target: {}, method: Function): void; /** * Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place. */ one(name: string, target: {}, method: Function): void; /** * Triggers a named event for the object. Any additional arguments will be passed as parameters to the functions that are subscribed to the event. */ trigger(name: string, ...args: any[]); /** * Cancels subscription for given name, target, and method. */ off(name: string, target: {}, method: Function): void; /** * Checks to see if object has any subscriptions for named event. */ has(name: string): boolean; } /** * The `Ember.Freezable` mixin implements some basic methods for marking an object as frozen. Once an object is frozen it should be read only. No changes may be made the internal state of the object. */ export class Freezable { /** * Set to `true` when the object is frozen. Use this property to detect whether your object is frozen or not. */ isFrozen: boolean; /** * Freezes the object. Once this method has been called the object should no longer allow any properties to be edited. */ freeze(): {}; } /** * This mixin defines the API for modifying array-like objects. These methods can be applied only to a collection that keeps its items in an ordered set. It builds upon the Array mixin and adds methods to modify the array. Concrete implementations of this class include ArrayProxy and ArrayController. */ export class MutableArray implements Ember.Array, MutableEnumerable { /** * __Required.__ You must implement this method to apply this mixin. */ replace(idx: number, amt: number, objects: Ember.Array); /** * Remove all elements from the array. This is useful if you want to reuse an existing array without having to recreate it. */ clear(): Ember.Array; /** * This will use the primitive `replace()` method to insert an object at the specified index. */ insertAt(idx: number, object: {}): Ember.Array; /** * Remove an object at the specified index using the `replace()` primitive method. You can pass either a single index, or a start and a length. */ removeAt(start: number, len: number): Ember.Array; /** * Push the object onto the end of the array. Works just like `push()` but it is KVO-compliant. */ pushObject(obj: any): void; /** * Add the objects in the passed numerable to the end of the array. Defers notifying observers of the change until all objects are added. */ pushObjects(objects: Enumerable): Ember.Array; /** * Pop object from array or nil if none are left. Works just like `pop()` but it is KVO-compliant. */ popObject(): void; /** * Shift an object from start of array or nil if none are left. Works just like `shift()` but it is KVO-compliant. */ shiftObject(): void; /** * Unshift an object to start of array. Works just like `unshift()` but it is KVO-compliant. */ unshiftObject(obj: any): void; /** * Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added. */ unshiftObjects(objects: Enumerable): Ember.Array; /** * Reverse objects in the array. Works just like `reverse()` but it is KVO-compliant. */ reverseObjects(): Ember.Array; /** * Replace all the receiver's content with content of the argument. If argument is an empty array receiver will be cleared. */ setObjects(objects: Ember.Array): Ember.Array; /** * Remove all occurrences of an object in the array. */ removeObject(obj: any): Ember.Array; /** * Push the object onto the end of the array if it is not already present in the array. */ addObject(obj: any): Ember.Array; /** * Your array must support the `length` property. Your replace methods should set this property whenever it changes. */ length: number; /** * Returns the object at the given `index`. If the given `index` is negative or is greater or equal than the array length, returns `undefined`. */ objectAt(idx: number): any; /** * This returns the objects at the specified indexes, using `objectAt`. */ objectsAt(indexes: Ember.Array): Ember.Array; /** * This is the handler for the special array content property. If you get this property, it will return this. If you set this property to a new array, it will replace the current content. */ '[]': any; /** * Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice. */ slice(beginIndex: Integer, endIndex: Integer): Ember.Array; /** * Returns the index of the given object's first occurrence. If no `startAt` argument is given, the starting location to search is 0. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ indexOf(object: {}, startAt: number): number; /** * Returns the index of the given object's last occurrence. If no `startAt` argument is given, the search starts from the last position. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ lastIndexOf(object: {}, startAt: number): number; /** * Adds an array observer to the receiving array. The array observer object normally must implement two methods: */ addArrayObserver(target: {}, opts: {}): Ember.Array; /** * Removes an array observer from the object if the observer is current registered. Calling this method multiple times with the same object will have no effect. */ removeArrayObserver(target: {}, opts: {}): Ember.Array; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasArrayObservers: boolean; /** * If you are implementing an object that supports `Ember.Array`, call this method just before the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * If you are implementing an object that supports `Ember.Array`, call this method just after the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * Returns a special object that can be used to observe individual properties on the array. Just get an equivalent property on this object and it will return an enumerable that maps automatically to the named key on the member objects. */ '@each': any; /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; /** * Adds each object in the passed enumerable to the receiver. */ addObjects(objects: Enumerable): {}; /** * Removes each object in the passed enumerable from the receiver. */ removeObjects(objects: Enumerable): {}; } /** * This mixin defines the API for modifying generic enumerables. These methods can be applied to an object regardless of whether it is ordered or unordered. */ export class MutableEnumerable implements Enumerable { /** * __Required.__ You must implement this method to apply this mixin. */ addObject(object: {}): {}; /** * Adds each object in the passed enumerable to the receiver. */ addObjects(objects: Enumerable): {}; /** * __Required.__ You must implement this method to apply this mixin. */ removeObject(object: {}): {}; /** * Removes each object in the passed enumerable from the receiver. */ removeObjects(objects: Enumerable): {}; /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerables content. */ '[]': Ember.Array; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; } /** * ## Overview */ export class Observable { /** * Retrieves the value of a property from the object. */ get(keyName: string): {}; /** * To get the values of multiple properties at once, call `getProperties` with a list of strings or an array: */ getProperties(...list: string[]): {}; /** * Sets the provided key or path to the value. */ set(keyName: string, value: {}): Observable; /** * Sets a list of properties at once. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. */ setProperties(hash: {}): Observable; /** * Begins a grouping of property changes. */ beginPropertyChanges(): Observable; /** * Ends a grouping of property changes. */ endPropertyChanges(): Observable; /** * Notify the observer system that a property is about to change. */ propertyWillChange(keyName: string): Observable; /** * Notify the observer system that a property has just changed. */ propertyDidChange(keyName: string): Observable; /** * Convenience method to call `propertyWillChange` and `propertyDidChange` in succession. */ notifyPropertyChange(keyName: string): Observable; /** * Adds an observer on a property. */ addObserver(key: string, target: {}, method: string|Function); /** * Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to `addObserver()` and your target will no longer receive notifications. */ removeObserver(key: string, target: {}, method: string|Function); /** * Returns `true` if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object. */ hasObserverFor(key: string): boolean; /** * Retrieves the value of a property, or a default value in the case that the property returns `undefined`. */ getWithDefault(keyName: string, defaultValue: {}): {}; /** * Set the value of a property to the current value plus some amount. */ incrementProperty(keyName: string, increment: number): number; /** * Set the value of a property to the current value minus some amount. */ decrementProperty(keyName: string, decrement: number): number; /** * Set the value of a boolean property to the opposite of it's current value. */ toggleProperty(keyName: string): {}; /** * Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily. */ cacheFor(keyName: string): {}; } /** * A low level mixin making ObjectProxy, ObjectController or ArrayController's promise aware. */ export class PromiseProxyMixin { /** * If the proxied promise is rejected this will contain the reason provided. */ reason: any; /** * Once the proxied promise has settled this will become `false`. */ isPending: any; /** * Once the proxied promise has settled this will become `true`. */ isSettled: any; /** * Will become `true` if the proxied promise is rejected. */ isRejected: any; /** * Will become `true` if the proxied promise is fulfilled. */ isFulfilled: any; /** * The promise whose fulfillment value is being proxied by this object. */ promise: any; /** * An alias to the proxied promise's `then`. */ then(callback: Function): RSVP.Promise<any>; /** * An alias to the proxied promise's `catch`. */ catch(callback: Function): RSVP.Promise<any>; /** * An alias to the proxied promise's `finally`. */ finally(callback: Function): RSVP.Promise<any>; } /** * `Ember.SortableMixin` provides a standard interface for array proxies to specify a sort order and maintain this sorting when objects are added, removed, or updated without changing the implicit order of their underlying model array: */ export class SortableMixin implements MutableEnumerable { /** * Specifies which properties dictate the `arrangedContent`'s sort order. */ sortProperties: Ember.Array; /** * Specifies the `arrangedContent`'s sort direction. Sorts the content in ascending order by default. Set to `false` to use descending order. */ sortAscending: boolean; /** * The function used to compare two values. You can override this if you want to do custom comparisons. Functions must be of the type expected by Array#sort, i.e., */ sortFunction: Function; /** * Overrides the default `arrangedContent` from `ArrayProxy` in order to sort by `sortFunction`. Also sets up observers for each `sortProperty` on each item in the content Array. */ arrangedContent: any; /** * __Required.__ You must implement this method to apply this mixin. */ addObject(object: {}): {}; /** * Adds each object in the passed enumerable to the receiver. */ addObjects(objects: Enumerable): {}; /** * __Required.__ You must implement this method to apply this mixin. */ removeObject(object: {}): {}; /** * Removes each object in the passed enumerable from the receiver. */ removeObjects(objects: Enumerable): {}; /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerables content. */ '[]': Ember.Array; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; } /** * `Ember.TargetActionSupport` is a mixin that can be included in a class to add a `triggerAction` method with semantics similar to the Handlebars `{{action}}` helper. In normal Ember usage, the `{{action}}` helper is usually the best choice. This mixin is most often useful when you are doing more complex event handling in View objects. */ export class TargetActionSupport extends Mixin { /** * Send an `action` with an `actionContext` to a `target`. The action, actionContext and target will be retrieved from properties of the object. For example: */ triggerAction(opts: {}): boolean; } /** * An ArrayProxy wraps any other object that implements `Ember.Array` and/or `Ember.MutableArray,` forwarding all requests. This makes it very useful for a number of binding use cases or other cases where being able to swap out the underlying array is useful. */ export class ArrayProxy extends Object implements MutableArray { /** * The content array. Must be an object that implements `Ember.Array` and/or `Ember.MutableArray.` */ content: Ember.Array; /** * The array that the proxy pretends to be. In the default `ArrayProxy` implementation, this and `content` are the same. Subclasses of `ArrayProxy` can override this property to provide things like sorting and filtering. */ arrangedContent: any; /** * Should actually retrieve the object at the specified index from the content. You can override this method in subclasses to transform the content item to something new. */ objectAtContent(idx: number): {}; /** * Should actually replace the specified objects on the content array. You can override this method in subclasses to transform the content item into something new. */ replaceContent(idx: number, amt: number, objects: Ember.Array): void; /** * Override to implement content array `willChange` observer. */ contentArrayWillChange(contentArray: Ember.Array, start: number, removeCount: number, addCount: number); /** * Override to implement content array `didChange` observer. */ contentArrayDidChange(contentArray: Ember.Array, start: number, removeCount: number, addCount: number); /** * __Required.__ You must implement this method to apply this mixin. */ replace(idx: number, amt: number, objects: Ember.Array); /** * Remove all elements from the array. This is useful if you want to reuse an existing array without having to recreate it. */ clear(): Ember.Array; /** * This will use the primitive `replace()` method to insert an object at the specified index. */ insertAt(idx: number, object: {}): Ember.Array; /** * Remove an object at the specified index using the `replace()` primitive method. You can pass either a single index, or a start and a length. */ removeAt(start: number, len: number): Ember.Array; /** * Push the object onto the end of the array. Works just like `push()` but it is KVO-compliant. */ pushObject(obj: any): void; /** * Add the objects in the passed numerable to the end of the array. Defers notifying observers of the change until all objects are added. */ pushObjects(objects: Enumerable): Ember.Array; /** * Pop object from array or nil if none are left. Works just like `pop()` but it is KVO-compliant. */ popObject(): void; /** * Shift an object from start of array or nil if none are left. Works just like `shift()` but it is KVO-compliant. */ shiftObject(): void; /** * Unshift an object to start of array. Works just like `unshift()` but it is KVO-compliant. */ unshiftObject(obj: any): void; /** * Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added. */ unshiftObjects(objects: Enumerable): Ember.Array; /** * Reverse objects in the array. Works just like `reverse()` but it is KVO-compliant. */ reverseObjects(): Ember.Array; /** * Replace all the receiver's content with content of the argument. If argument is an empty array receiver will be cleared. */ setObjects(objects: Ember.Array): Ember.Array; /** * Remove all occurrences of an object in the array. */ removeObject(obj: any): Ember.Array; /** * Push the object onto the end of the array if it is not already present in the array. */ addObject(obj: any): Ember.Array; /** * Your array must support the `length` property. Your replace methods should set this property whenever it changes. */ length: number; /** * Returns the object at the given `index`. If the given `index` is negative or is greater or equal than the array length, returns `undefined`. */ objectAt(idx: number): any; /** * This returns the objects at the specified indexes, using `objectAt`. */ objectsAt(indexes: Ember.Array): Ember.Array; /** * This is the handler for the special array content property. If you get this property, it will return this. If you set this property to a new array, it will replace the current content. */ '[]': any; /** * Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice. */ slice(beginIndex: Integer, endIndex: Integer): Ember.Array; /** * Returns the index of the given object's first occurrence. If no `startAt` argument is given, the starting location to search is 0. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ indexOf(object: {}, startAt: number): number; /** * Returns the index of the given object's last occurrence. If no `startAt` argument is given, the search starts from the last position. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ lastIndexOf(object: {}, startAt: number): number; /** * Adds an array observer to the receiving array. The array observer object normally must implement two methods: */ addArrayObserver(target: {}, opts: {}): Ember.Array; /** * Removes an array observer from the object if the observer is current registered. Calling this method multiple times with the same object will have no effect. */ removeArrayObserver(target: {}, opts: {}): Ember.Array; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasArrayObservers: boolean; /** * If you are implementing an object that supports `Ember.Array`, call this method just before the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * If you are implementing an object that supports `Ember.Array`, call this method just after the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * Returns a special object that can be used to observe individual properties on the array. Just get an equivalent property on this object and it will return an enumerable that maps automatically to the named key on the member objects. */ '@each': any; /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; /** * Adds each object in the passed enumerable to the receiver. */ addObjects(objects: Enumerable): {}; /** * Removes each object in the passed enumerable from the receiver. */ removeObjects(objects: Enumerable): {}; } export class CoreObject { /** * An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition. */ init(); /** * Defines the properties that will be concatenated from the superclass (instead of overridden). */ concatenatedProperties: Ember.Array; /** * Destroyed object property flag. */ isDestroyed: any; /** * Destruction scheduled flag. The `destroy()` method has been called. */ isDestroying: any; /** * Destroys an object by setting the `isDestroyed` flag and removing its metadata, which effectively destroys observers and bindings. */ destroy(): {}; /** * Override to implement teardown. */ willDestroy(); /** * Returns a string representation which attempts to provide more information than Javascript's `toString` typically does, in a generic way for all Ember objects. */ toString(): string; /** * Creates a new subclass. */ static extend(mixins: Mixin, args: {}); /** * Equivalent to doing `extend(arguments).create()`. If possible use the normal `create` method instead. */ static createWithMixins(args: any); /** * Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with. */ static create(args: any); /** * Augments a constructor's prototype with additional properties and functions: */ reopen(); /** * Augments a constructor's own properties and functions: */ reopenClass(); /** * In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. */ metaForProperty(key: string); /** * Iterate over each computed property for the class, passing its name and any associated metadata (see `metaForProperty`) to the callback. */ eachComputedProperty(callback: Function, binding: {}); /** * Returns a hash of property names and container names that injected properties will lookup on the container lazily. */ lazyInjections(): {}; } /** * This is the object instance returned when you get the `@each` property on an array. It uses the unknownProperty handler to automatically create EachArray instances for property names. */ export class EachProxy extends Object { /** * You can directly access mapped properties by simply requesting them. The `unknownProperty` handler will generate an EachArray of each item. */ unknownProperty(keyName: string, value: any); } /** * A Namespace is an object usually used to contain other objects or methods such as an application or framework. Create a namespace anytime you want to define one of these new containers. */ export class Namespace extends Object { } /** * The NativeArray mixin contains the properties needed to to make the native Array support Ember.MutableArray and all of its dependent APIs. Unless you have `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Array` set to false, this will be applied automatically. Otherwise you can apply the mixin at anytime by calling `Ember.NativeArray.activate`. */ export class NativeArray implements MutableArray, Observable, Copyable { /** * Activates the mixin on the Array.prototype if not already applied. Calling this method more than once is safe. This will be called when ember is loaded unless you have `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Array` set to `false`. */ static activate(): void; /** * __Required.__ You must implement this method to apply this mixin. */ replace(idx: number, amt: number, objects: Ember.Array); /** * Remove all elements from the array. This is useful if you want to reuse an existing array without having to recreate it. */ clear(): Ember.Array; /** * This will use the primitive `replace()` method to insert an object at the specified index. */ insertAt(idx: number, object: {}): Ember.Array; /** * Remove an object at the specified index using the `replace()` primitive method. You can pass either a single index, or a start and a length. */ removeAt(start: number, len: number): Ember.Array; /** * Push the object onto the end of the array. Works just like `push()` but it is KVO-compliant. */ pushObject(obj: any): void; /** * Add the objects in the passed numerable to the end of the array. Defers notifying observers of the change until all objects are added. */ pushObjects(objects: Enumerable): Ember.Array; /** * Pop object from array or nil if none are left. Works just like `pop()` but it is KVO-compliant. */ popObject(): void; /** * Shift an object from start of array or nil if none are left. Works just like `shift()` but it is KVO-compliant. */ shiftObject(): void; /** * Unshift an object to start of array. Works just like `unshift()` but it is KVO-compliant. */ unshiftObject(obj: any): void; /** * Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added. */ unshiftObjects(objects: Enumerable): Ember.Array; /** * Reverse objects in the array. Works just like `reverse()` but it is KVO-compliant. */ reverseObjects(): Ember.Array; /** * Replace all the receiver's content with content of the argument. If argument is an empty array receiver will be cleared. */ setObjects(objects: Ember.Array): Ember.Array; /** * Remove all occurrences of an object in the array. */ removeObject(obj: any): Ember.Array; /** * Push the object onto the end of the array if it is not already present in the array. */ addObject(obj: any): Ember.Array; /** * Your array must support the `length` property. Your replace methods should set this property whenever it changes. */ length: number; /** * Returns the object at the given `index`. If the given `index` is negative or is greater or equal than the array length, returns `undefined`. */ objectAt(idx: number): any; /** * This returns the objects at the specified indexes, using `objectAt`. */ objectsAt(indexes: Ember.Array): Ember.Array; /** * This is the handler for the special array content property. If you get this property, it will return this. If you set this property to a new array, it will replace the current content. */ '[]': any; /** * Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice. */ slice(beginIndex: Integer, endIndex: Integer): Ember.Array; /** * Returns the index of the given object's first occurrence. If no `startAt` argument is given, the starting location to search is 0. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ indexOf(object: {}, startAt: number): number; /** * Returns the index of the given object's last occurrence. If no `startAt` argument is given, the search starts from the last position. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. */ lastIndexOf(object: {}, startAt: number): number; /** * Adds an array observer to the receiving array. The array observer object normally must implement two methods: */ addArrayObserver(target: {}, opts: {}): Ember.Array; /** * Removes an array observer from the object if the observer is current registered. Calling this method multiple times with the same object will have no effect. */ removeArrayObserver(target: {}, opts: {}): Ember.Array; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasArrayObservers: boolean; /** * If you are implementing an object that supports `Ember.Array`, call this method just before the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * If you are implementing an object that supports `Ember.Array`, call this method just after the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. */ arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): Ember.Array; /** * Returns a special object that can be used to observe individual properties on the array. Just get an equivalent property on this object and it will return an enumerable that maps automatically to the named key on the member objects. */ '@each': any; /** * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; /** * Adds each object in the passed enumerable to the receiver. */ addObjects(objects: Enumerable): {}; /** * Removes each object in the passed enumerable from the receiver. */ removeObjects(objects: Enumerable): {}; /** * Retrieves the value of a property from the object. */ get(keyName: string): {}; /** * To get the values of multiple properties at once, call `getProperties` with a list of strings or an array: */ getProperties(...list: string[]): {}; /** * Sets the provided key or path to the value. */ set(keyName: string, value: {}): Observable; /** * Sets a list of properties at once. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. */ setProperties(hash: {}): Observable; /** * Begins a grouping of property changes. */ beginPropertyChanges(): Observable; /** * Ends a grouping of property changes. */ endPropertyChanges(): Observable; /** * Notify the observer system that a property is about to change. */ propertyWillChange(keyName: string): Observable; /** * Notify the observer system that a property has just changed. */ propertyDidChange(keyName: string): Observable; /** * Convenience method to call `propertyWillChange` and `propertyDidChange` in succession. */ notifyPropertyChange(keyName: string): Observable; /** * Adds an observer on a property. */ addObserver(key: string, target: {}, method: string|Function); /** * Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to `addObserver()` and your target will no longer receive notifications. */ removeObserver(key: string, target: {}, method: string|Function); /** * Returns `true` if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object. */ hasObserverFor(key: string): boolean; /** * Retrieves the value of a property, or a default value in the case that the property returns `undefined`. */ getWithDefault(keyName: string, defaultValue: {}): {}; /** * Set the value of a property to the current value plus some amount. */ incrementProperty(keyName: string, increment: number): number; /** * Set the value of a property to the current value minus some amount. */ decrementProperty(keyName: string, decrement: number): number; /** * Set the value of a boolean property to the opposite of it's current value. */ toggleProperty(keyName: string): {}; /** * Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily. */ cacheFor(keyName: string): {}; /** * Override to return a copy of the receiver. Default implementation raises an exception. */ copy(deep: boolean): {}; /** * If the object implements `Ember.Freezable`, then this will return a new copy if the object is not frozen and the receiver if the object is frozen. */ frozenCopy(): {}; } /** * `Ember.Object` is the main base class for all Ember objects. It is a subclass of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details, see the documentation for each of these. */ export class Object extends CoreObject implements Observable { /** * Retrieves the value of a property from the object. */ get(keyName: string): {}; /** * To get the values of multiple properties at once, call `getProperties` with a list of strings or an array: */ getProperties(...list: string[]): {}; /** * Sets the provided key or path to the value. */ set(keyName: string, value: {}): Observable; /** * Sets a list of properties at once. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. */ setProperties(hash: {}): Observable; /** * Begins a grouping of property changes. */ beginPropertyChanges(): Observable; /** * Ends a grouping of property changes. */ endPropertyChanges(): Observable; /** * Notify the observer system that a property is about to change. */ propertyWillChange(keyName: string): Observable; /** * Notify the observer system that a property has just changed. */ propertyDidChange(keyName: string): Observable; /** * Convenience method to call `propertyWillChange` and `propertyDidChange` in succession. */ notifyPropertyChange(keyName: string): Observable; /** * Adds an observer on a property. */ addObserver(key: string, target: {}, method: string|Function); /** * Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to `addObserver()` and your target will no longer receive notifications. */ removeObserver(key: string, target: {}, method: string|Function); /** * Returns `true` if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object. */ hasObserverFor(key: string): boolean; /** * Retrieves the value of a property, or a default value in the case that the property returns `undefined`. */ getWithDefault(keyName: string, defaultValue: {}): {}; /** * Set the value of a property to the current value plus some amount. */ incrementProperty(keyName: string, increment: number): number; /** * Set the value of a property to the current value minus some amount. */ decrementProperty(keyName: string, decrement: number): number; /** * Set the value of a boolean property to the opposite of it's current value. */ toggleProperty(keyName: string): {}; /** * Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily. */ cacheFor(keyName: string): {}; } /** * `Ember.ObjectProxy` forwards all properties not defined by the proxy itself to a proxied `content` object. */ export class ObjectProxy { } export class Service extends Object { } /** * DEPRECATED: * An unordered collection of objects. */ export class Set extends CoreObject implements MutableEnumerable, Copyable, Freezable { /** * DEPRECATED: * This property will change as the number of objects in the set changes. */ length: number; /** * DEPRECATED: * Clears the set. This is useful if you want to reuse an existing set without having to recreate it. */ clear(): Set; /** * DEPRECATED: * Returns true if the passed object is also an enumerable that contains the same objects as the receiver. */ isEqual(obj: Set): boolean; /** * DEPRECATED: * Adds an object to the set. Only non-`null` objects can be added to a set and those can only be added once. If the object is already in the set or the passed value is null this method will have no effect. */ add(obj: {}): Set; /** * DEPRECATED: * Removes the object from the set if it is found. If you pass a `null` value or an object that is already not in the set, this method will have no effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. */ remove(obj: {}): Set; /** * DEPRECATED: * Removes the last element from the set and returns it, or `null` if it's empty. */ pop(): {}; /** * DEPRECATED: * Inserts the given object on to the end of the set. It returns the set itself. */ push(): Set; /** * DEPRECATED: * Removes the last element from the set and returns it, or `null` if it's empty. */ shift(): {}; /** * DEPRECATED: * Inserts the given object on to the end of the set. It returns the set itself. */ unshift(): Set; /** * DEPRECATED: * Adds each object in the passed enumerable to the set. */ addEach(objects: Enumerable): Set; /** * DEPRECATED: * Removes each object in the passed enumerable to the set. */ removeEach(objects: Enumerable): Set; /** * DEPRECATED: * __Required.__ You must implement this method to apply this mixin. */ addObject(object: {}): {}; /** * DEPRECATED: * Adds each object in the passed enumerable to the receiver. */ addObjects(objects: Enumerable): {}; /** * DEPRECATED: * __Required.__ You must implement this method to apply this mixin. */ removeObject(object: {}): {}; /** * DEPRECATED: * Removes each object in the passed enumerable from the receiver. */ removeObjects(objects: Enumerable): {}; /** * DEPRECATED: * Implement this method to make your class enumerable. */ nextObject(index: number, previousObject: {}, context: {}): {}; /** * DEPRECATED: * Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. */ firstObject: any; /** * DEPRECATED: * Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. */ lastObject: any; /** * DEPRECATED: * Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. */ contains(obj: {}): boolean; /** * DEPRECATED: * Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. */ forEach(callback: Function, target: {}): {}; /** * DEPRECATED: * Alias for `mapBy` */ getEach(key: string): Ember.Array; /** * DEPRECATED: * Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. */ setEach(key: string, value: {}): {}; /** * DEPRECATED: * Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. */ map(callback: Function, target: {}): Ember.Array; /** * DEPRECATED: * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapBy(key: string): Ember.Array; /** * DEPRECATED: Use `mapBy` instead * Similar to map, this specialized function returns the value of the named property on all items in the enumeration. */ mapProperty(key: string): Ember.Array; /** * DEPRECATED: * Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. */ filter(callback: Function, target: {}): Ember.Array; /** * DEPRECATED: * Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). */ reject(callback: Function, target: {}): Ember.Array; /** * DEPRECATED: * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterBy(key: string, value: any): Ember.Array; /** * DEPRECATED: Use `filterBy` instead * Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ filterProperty(key: string, value: string): Ember.Array; /** * DEPRECATED: * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectBy(key: string, value: string): Ember.Array; /** * DEPRECATED: Use `rejectBy` instead * Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. */ rejectProperty(key: string, value: string): Ember.Array; /** * DEPRECATED: * Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. */ find(callback: Function, target: {}): {}; /** * DEPRECATED: * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findBy(key: string, value: string): {}; /** * DEPRECATED: Use `findBy` instead * Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. */ findProperty(key: string, value: string): {}; /** * DEPRECATED: * Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. */ every(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isEvery` instead */ everyProperty(key: string, value: string): boolean; /** * DEPRECATED: * Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. */ isEvery(key: string, value: string): boolean; /** * DEPRECATED: * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ any(callback: Function, target: {}): boolean; /** * DEPRECATED: Use `any` instead * Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. */ some(callback: Function, target: {}): boolean; /** * DEPRECATED: * Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. */ isAny(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ anyBy(key: string, value: string): boolean; /** * DEPRECATED: Use `isAny` instead */ someProperty(key: string, value: string): boolean; /** * DEPRECATED: * This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. */ reduce(callback: Function, initialValue: {}, reducerProperty: string): {}; /** * DEPRECATED: * Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. */ invoke(methodName: string, ...args: any[]): Ember.Array; /** * DEPRECATED: * Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. */ toArray(): Ember.Array; /** * DEPRECATED: * Returns a copy of the array with all `null` and `undefined` elements removed. */ compact(): Ember.Array; /** * DEPRECATED: * Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. */ without(value: {}): Enumerable; /** * DEPRECATED: * Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. */ uniq(): Enumerable; /** * DEPRECATED: * This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerables content. */ '[]': Ember.Array; /** * DEPRECATED: * Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. */ addEnumerableObserver(target: {}, opts: {}): void; /** * DEPRECATED: * Removes a registered enumerable observer. */ removeEnumerableObserver(target: {}, opts: {}): void; /** * DEPRECATED: * Becomes true whenever the array currently has observers watching changes on the array. */ hasEnumerableObservers: boolean; /** * DEPRECATED: * Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. */ enumerableContentWillChange(removing: Enumerable|number, adding: Enumerable|number); /** * DEPRECATED: * Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. */ enumerableContentDidChange(removing: Enumerable|number, adding: Enumerable|number); /** * DEPRECATED: * Converts the enumerable into an array and sorts by the keys specified in the argument. */ sortBy(property: string): Ember.Array; /** * DEPRECATED: * Override to return a copy of the receiver. Default implementation raises an exception. */ copy(deep: boolean): {}; /** * DEPRECATED: * If the object implements `Ember.Freezable`, then this will return a new copy if the object is not frozen and the receiver if the object is frozen. */ frozenCopy(): {}; /** * DEPRECATED: * Set to `true` when the object is frozen. Use this property to detect whether your object is frozen or not. */ isFrozen: boolean; /** * DEPRECATED: * Freezes the object. Once this method has been called the object should no longer allow any properties to be edited. */ freeze(): {}; } /** * An `Ember.SubArray` tracks an array in a way similar to, but more specialized than, `Ember.TrackedArray`. It is useful for keeping track of the indexes of items within a filtered array. */ export class SubArray { /** * Track that an item was added to the tracked array. */ addItem(index: number, match: boolean): number; /** * Track that an item was removed from the tracked array. */ removeItem(index: number): number; } /** * An `Ember.TrackedArray` tracks array operations. It's useful when you want to lazily compute the indexes of items in an array after they've been shifted by subsequent operations. */ export class TrackedArray { /** * Track that `newItems` were added to the tracked array at `index`. */ addItems(index: any, newItems: any); /** * Track that `count` items were removed at `index`. */ removeItems(index: any, count: any); /** * Apply all operations, reducing them to retain:n, for `n`, the number of items in the array. */ apply(callback: Function); } /** * Namespace for injection helper methods. */ export class inject { } /** * The ComponentTemplateDeprecation mixin is used to provide a useful deprecation warning when using either `template` or `templateName` with a component. The `template` and `templateName` properties specified at extend time are moved to `layout` and `layoutName` respectively. */ export class ComponentTemplateDeprecation { } /** * `Ember.ViewTargetActionSupport` is a mixin that can be included in a view class to add a `triggerAction` method with semantics similar to the Handlebars `{{action}}` helper. It provides intelligent defaults for the action's target: the view's controller; and the context that is sent with the action: the view's context. */ export class ViewTargetActionSupport extends TargetActionSupport { target: any; actionContext: any; } /** * `Ember.EventDispatcher` handles delegating browser events to their corresponding `Ember.Views.` For example, when you click on a view, `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets called. */ export class EventDispatcher extends Object { /** * The set of events names (and associated handler function names) to be setup and dispatched by the `EventDispatcher`. Custom events can added to this list at setup time, generally via the `Ember.Application.customEvents` hash. Only override this default set to prevent the EventDispatcher from listening on some events all together. */ events: {}; /** * It enables events to be dispatched to the view's `eventManager.` When present, this object takes precedence over handling of events on the view itself. */ canDispatchToEventManager: boolean; } /** * `Ember.CollectionView` is an `Ember.View` descendent responsible for managing a collection (an array or array-like object) by maintaining a child view object and associated DOM representation for each item in the array and ensuring that child views and their associated rendered HTML are updated when items in the array are added, removed, or replaced. */ export class CollectionView extends ContainerView { /** * `Ember.renderBuffer` gathers information regarding the view and generates the final representation. `Ember.renderBuffer` will generate HTML which can be pushed to the DOM. */ renderBuffer(tagName: string); /** * Array of class names which will be applied in the class attribute. */ classes: Ember.Array; /** * The id in of the element, to be applied in the id attribute. */ elementId: string; /** * A hash keyed on the name of the attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `data-view="Foo.bar"` property to an element, you would set the elementAttributes hash to `{'data-view':'Foo.bar'}`. */ elementAttributes: {}; /** * A hash keyed on the name of the properties and whose value will be applied to that property. For example, if you wanted to apply a `checked=true` property to an element, you would set the elementProperties hash to `{'checked':true}`. */ elementProperties: {}; /** * The tagname of the element an instance of `Ember.RenderBuffer` represents. */ elementTag: string; /** * A hash keyed on the name of the style attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `background-color:black;` style to an element, you would set the elementStyle hash to `{'background-color':'black'}`. */ elementStyle: {}; /** * Adds a string of HTML to the `RenderBuffer`. */ push(string: string); /** * Adds a class to the buffer, which will be rendered to the class attribute. */ addClass(className: string); /** * Sets the elementID to be used for the element. */ id(id: string); /** * Adds an attribute which will be rendered to the element. */ attr(name: string, value: string): RenderBuffer|string; /** * Remove an attribute from the list of attributes to render. */ removeAttr(name: string); /** * Adds a property which will be rendered to the element. */ prop(name: string, value: string): RenderBuffer|string; /** * Remove an property from the list of properties to render. */ removeProp(name: string); /** * Adds a style to the style attribute which will be rendered to the element. */ style(name: string, value: string); element(): DOMElement; /** * Generates the HTML content for this buffer. */ string(): string; /** * A list of items to be displayed by the `Ember.CollectionView`. */ content: Ember.Array; /** * An optional view to display if content is set to an empty array. */ emptyView: View; itemViewClass: View; /** * Setup a CollectionView */ init(); /** * Removes the content and content observers. */ destroy(); /** * Called when a mutation to the underlying content array will occur. */ arrayWillChange(content: Ember.Array, start: number, removed: number); /** * Called when a mutation to the underlying content array occurs. */ arrayDidChange(content: Ember.Array, start: number, removed: number, added: number); /** * Instantiates a view to be added to the childViews array during view initialization. You generally will not call this method directly unless you are overriding `createChildViews()`. Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent. */ createChildView(viewClass: any, attrs: {}): View; /** * A map of parent tags to their default child tags. You can add additional parent tags if you want collection views that use a particular parent tag to default to a child tag. */ static CONTAINER_MAP: {}; } /** * An `Ember.Component` is a view that is completely isolated. Property access in its templates go to the view object and actions are targeted at the view object. There is no access to the surrounding context or outer controller; all contextual information must be passed in. */ export class Component extends View { /** * DEPRECATED: * A components template property is set by passing a block during its invocation. It is executed within the parent context. */ template: any; /** * DEPRECATED: * Specifying a components `templateName` is deprecated without also providing the `layout` or `layoutName` properties. */ templateName: any; /** * If the component is currently inserted into the DOM of a parent view, this property will point to the controller of the parent view. */ targetObject: Controller; /** * Triggers a named action on the controller context where the component is used if this controller has registered for notifications of the action. */ sendAction(action: string, context: any); } /** * A `ContainerView` is an `Ember.View` subclass that implements `Ember.MutableArray` allowing programmatic management of its child views. */ export class ContainerView extends View { } /** * `Ember.CoreView` is an abstract class that exists to give view-like behavior to both Ember's main view class `Ember.View` and other classes like `Ember._SimpleMetamorphView` that don't need the fully functionaltiy of `Ember.View`. */ export class CoreView extends Object implements Evented, ActionHandler { /** * If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view. */ parentView: View; /** * Override the default event firing from `Ember.Evented` to also call methods with the given name. */ trigger(name: string); /** * Subscribes to a named event with given function. */ on(name: string, target: {}, method: Function): void; /** * Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place. */ one(name: string, target: {}, method: Function): void; /** * Cancels subscription for given name, target, and method. */ off(name: string, target: {}, method: Function): void; /** * Checks to see if object has any subscriptions for named event. */ has(name: string): boolean; /** * The collection of functions, keyed by name, available on this `ActionHandler` as action targets. */ actions: {}; /** * Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. */ send(actionName: string, context: any); } /** * `Ember.View` is the class in Ember responsible for encapsulating templates of HTML content, combining templates with data to render as sections of a page's DOM, and registering and responding to user-initiated events. */ export class View extends CoreView { static isView: boolean; /** * The name of the template to lookup if no template is provided. */ templateName: string; /** * The name of the layout to lookup if no layout is provided. */ layoutName: string; /** * Used to identify this view during debugging */ instrumentDisplay: string; /** * The template used to render the view. This should be a function that accepts an optional context parameter and returns a string of HTML that will be inserted into the DOM relative to its parent view. */ template: Function; /** * The controller managing this view. If this property is set, it will be made available for use by the template. */ controller: {}; /** * A view may contain a layout. A layout is a regular template but supersedes the `template` property during rendering. It is the responsibility of the layout template to retrieve the `template` property from the view (or alternatively, call `Handlebars.helpers.yield`, `{{yield}}`) to render it in the correct location. */ layout: Function; /** * The object from which templates should access properties. */ context: {}; /** * If `false`, the view will appear hidden in DOM. */ isVisible: boolean; /** * DEPRECATED: * Return the nearest ancestor that is an instance of the provided class. */ nearestInstanceOf(klass: any): void; /** * Return the nearest ancestor that is an instance of the provided class or mixin. */ nearestOfType(klass: Class,Mixin): void; /** * Return the nearest ancestor that has a given property. */ nearestWithProperty(property: string): void; /** * Return the nearest ancestor whose parent is an instance of `klass`. */ nearestChildOf(klass: any): void; /** * Called on your view when it should push strings of HTML into a `Ember.RenderBuffer`. Most users will want to override the `template` or `templateName` properties instead of this method. */ render(buffer: RenderBuffer); /** * Renders the view again. This will work regardless of whether the view is already in the DOM or not. If the view is in the DOM, the rendering process will be deferred to give bindings a chance to synchronize. */ rerender(); /** * Returns the current DOM element for the view. */ element: DOMElement; /** * Returns a jQuery object for this view's element. If you pass in a selector string, this method will return a jQuery object, using the current element as its buffer. */ $(selector: string): JQuery; /** * Appends the view's element to the specified parent element. */ appendTo(A: string|DOMElement|jQuery): View; /** * Replaces the content of the specified parent element with this view's element. If the view does not have an HTML representation yet, `createElement()` will be called automatically. */ replaceIn(target: string|DOMElement|jQuery): View; /** * Appends the view's element to the document body. If the view does not have an HTML representation yet, `createElement()` will be called automatically. */ append(): View; /** * Removes the view's element from the element to which it is attached. */ remove(): View; /** * Attempts to discover the element in the parent element. The default implementation looks for an element with an ID of `elementId` (or the view's guid if `elementId` is null). You can override this method to provide your own form of lookup. For example, if you want to discover your element using a CSS class name instead of an ID. */ findElementInParentElement(parentElement: DOMElement): DOMElement; /** * Creates a DOM representation of the view and all of its child views by recursively calling the `render()` method. */ createElement(): View; /** * Destroys any existing element along with the element for any child views as well. If the view does not currently have a element, then this method will do nothing. */ destroyElement(): View; /** * Tag name for the view's outer element. The tag name is only used when an element is first created. If you change the `tagName` for an element, you must destroy and recreate the view element. */ tagName: string; /** * The WAI-ARIA role of the control represented by this view. For example, a button may have a role of type 'button', or a pane may have a role of type 'alertdialog'. This property is used by assistive software to help visually challenged users navigate rich web applications. */ ariaRole: string; /** * Standard CSS class names to apply to the view's outer element. This property automatically inherits any class names defined by the view's superclasses as well. */ classNames: Ember.Array; /** * A list of properties of the view to apply as class names. If the property is a string value, the value of that string will be applied as a class name. */ classNameBindings: Ember.Array; /** * A list of properties of the view to apply as attributes. If the property is a string value, the value of that string will be applied as the attribute. */ attributeBindings: any; /** * Removes the child view from the parent view. */ removeChild(view: View): View; /** * Removes all children from the `parentView`. */ removeAllChildren(): View; /** * Removes the view from its `parentView`, if one is found. Otherwise does nothing. */ removeFromParent(): View; /** * You must call `destroy` on a view to destroy the view (and all of its child views). This will remove the view from any parent node, then make sure that the DOM element managed by the view can be released by the memory manager. */ destroy(); /** * Instantiates a view to be added to the childViews array during view initialization. You generally will not call this method directly unless you are overriding `createChildViews()`. Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent. */ createChildView(viewClass: any|string, attrs: {}): View; /** * Global views hash */ static views: {}; } } export namespace A Suite can be used to define a reusable set of unit tests that can be applied to any object { export namespace Suites are most useful for defining tests that work against a mixin or plugin API { export namespace Developers implementing objects that use the mixin or support the API can then run these tests against their own code to verify compliance { export namespace To define a suite, you need to define the tests themselves as well as a callback API implementors can use to tie your tests to thier specific class { export namespace ## Defining a Callback API To define the callback API, just extend this class and add your properties or methods that must be provided { export namespace Use Ember { export namespace required() placeholders for any properties that implementors must define themselves { export namespace ## Defining Unit Tests To add unit tests, use the suite { export namespace module() or suite { export namespace test() methods instead of a regular module() or test() method when defining your tests { export namespace This will add the tests to the suite { export namespace ## Using a Suite To use a Suite to test your own objects, extend the suite subclass and define any required methods { export namespace Then call run() on the new subclass { export namespace This will create an instance of your class and then defining the unit tests { export class extends Ember.Object { } } } } } } } } } } } } } } } export interface String { /** * Mark a string as being safe for unescaped output with Handlebars. */ htmlSafe(): Handlebars.SafeString; /** * See [Ember.String.fmt](/api/classes/Ember.String.html#method_fmt). */ fmt(); /** * See [Ember.String.w](/api/classes/Ember.String.html#method_w). */ w(); /** * See [Ember.String.loc](/api/classes/Ember.String.html#method_loc). */ loc(); /** * See [Ember.String.camelize](/api/classes/Ember.String.html#method_camelize). */ camelize(); /** * See [Ember.String.decamelize](/api/classes/Ember.String.html#method_decamelize). */ decamelize(); /** * See [Ember.String.dasherize](/api/classes/Ember.String.html#method_dasherize). */ dasherize(); /** * See [Ember.String.underscore](/api/classes/Ember.String.html#method_underscore). */ underscore(); /** * See [Ember.String.classify](/api/classes/Ember.String.html#method_classify). */ classify(); /** * See [Ember.String.capitalize](/api/classes/Ember.String.html#method_capitalize). */ capitalize(); } export interface Function { /** * The `property` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is `true`, which is the default. */ property(); /** * The `observes` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. */ observes(); /** * The `observesImmediately` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. */ observesImmediately(); /** * The `observesBefore` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. */ observesBefore(); /** * The `on` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. */ on(); } export default Ember }
the_stack
import { compact } from 'lodash'; import { AggregationOperator, Relation, RelationSide, RootEntityType } from '../../model'; import { AddEdgesQueryNode, AggregationQueryNode, BasicType, BinaryOperationQueryNode, BinaryOperator, BinaryOperatorWithAnalyzer, ConcatListsQueryNode, ConditionalQueryNode, ConfirmForBillingQueryNode, ConstBoolQueryNode, ConstIntQueryNode, CountQueryNode, CreateBillingEntityQueryNode, CreateEntityQueryNode, DeleteEntitiesQueryNode, DynamicPropertyAccessQueryNode, EntitiesIdentifierKind, EntitiesQueryNode, EntityFromIdQueryNode, FieldPathQueryNode, FieldQueryNode, FirstOfListQueryNode, FlexSearchStartsWithQueryNode, FollowEdgeQueryNode, ListItemQueryNode, ListQueryNode, LiteralQueryNode, MergeObjectsQueryNode, NullQueryNode, ObjectEntriesQueryNode, ObjectQueryNode, OperatorWithAnalyzerQueryNode, OrderClause, OrderDirection, OrderSpecification, PropertyAccessQueryNode, QueryNode, QueryResultValidator, RemoveEdgesQueryNode, RootEntityIDQueryNode, RUNTIME_ERROR_CODE_PROPERTY, RUNTIME_ERROR_TOKEN, RuntimeErrorQueryNode, SafeListQueryNode, SetEdgeQueryNode, TransformListQueryNode, TraversalQueryNode, TypeCheckQueryNode, UnaryOperationQueryNode, UnaryOperator, UpdateEntitiesQueryNode, VariableAssignmentQueryNode, VariableQueryNode, WithPreExecutionQueryNode } from '../../query-tree'; import { FlexSearchComplexOperatorQueryNode, FlexSearchFieldExistsQueryNode, FlexSearchQueryNode } from '../../query-tree/flex-search'; import { QuantifierFilterNode } from '../../query-tree/quantifiers'; import { createFieldPathNode } from '../../schema-generation/field-path-node'; import { not } from '../../schema-generation/utils/input-types'; import { Constructor, decapitalize } from '../../utils/utils'; import { IDENTITY_ANALYZER, NORM_CI_ANALYZER } from '../arangodb/schema-migration/arango-search-helpers'; import { likePatternToRegExp } from '../like-helpers'; import { getCollectionNameForRelation, getCollectionNameForRootEntity } from './inmemory-basics'; import { js, JSCompoundQuery, JSFragment, JSQueryResultVariable, JSVariable } from './js'; const ID_FIELD_NAME = 'id'; class QueryContext { private variableMap = new Map<VariableQueryNode, JSVariable>(); private preExecQueries: JSCompoundQuery[] = []; /** * Creates a new QueryContext with an independent variable map except that all query result variables of this * context are available. */ private newPreExecContext(): QueryContext { const newContext = new QueryContext(); this.variableMap.forEach((jsVar, varNode) => { if (jsVar instanceof JSQueryResultVariable) { newContext.variableMap.set(varNode, jsVar); } }); return newContext; } /** * Creates a new QueryContext that is identical to this one but has one additional variable binding * @param variableNode the variable token as it is referenced in the query tree * @param jsVariable the variable token as it will be available within the JS fragment */ private newNestedContextWithNewVariable(variableNode: VariableQueryNode, jsVariable: JSVariable): QueryContext { if (this.variableMap.has(variableNode)) { throw new Error(`Variable ${variableNode} is introduced twice`); } const newContext = new QueryContext(); newContext.variableMap = new Map(this.variableMap); newContext.variableMap.set(variableNode, jsVariable); newContext.preExecQueries = this.preExecQueries; return newContext; } /** * Creates a new QueryContext that is identical to this one but has one additional variable binding * * The JSFragment for the variable will be available via getVariable(). * * @param {VariableQueryNode} variableNode the variable as referenced in the query tree * @returns {QueryContext} the nested context */ introduceVariable(variableNode: VariableQueryNode): QueryContext { const variable = new JSVariable(variableNode.label); return this.newNestedContextWithNewVariable(variableNode, variable); } /** * Creates a new QueryContext that includes an additional transaction step and adds resultVariable to the scope * which will contain the result of the query * * The preExecQuery is evaluated in an independent context that has access to all previous preExecQuery result * variables. * * @param preExecQuery the query to execute as transaction step * @param resultVariable the variable to store the query result * @param resultValidator an optional validator for the query result */ addPreExecuteQuery( preExecQuery: QueryNode, resultVariable?: VariableQueryNode, resultValidator?: QueryResultValidator ): QueryContext { let resultVar: JSQueryResultVariable | undefined; let newContext: QueryContext; if (resultVariable) { resultVar = new JSQueryResultVariable(resultVariable.label); newContext = this.newNestedContextWithNewVariable(resultVariable, resultVar); } else { resultVar = undefined; newContext = this; } const jsQuery = createJSCompoundQuery(preExecQuery, resultVar, resultValidator, this.newPreExecContext()); this.preExecQueries.push(jsQuery); return newContext; } /** * Gets an JSFragment that evaluates to the value of a variable in the current scope */ getVariable(variableNode: VariableQueryNode): JSFragment { const variable = this.variableMap.get(variableNode); if (!variable) { throw new Error(`Variable ${variableNode.toString()} is used but not introduced`); } return js`${variable}`; } getPreExecuteQueries(): JSCompoundQuery[] { return this.preExecQueries; } } function createJSCompoundQuery( node: QueryNode, resultVariable: JSQueryResultVariable | undefined, resultValidator: QueryResultValidator | undefined, context: QueryContext ): JSCompoundQuery { const jsQuery = processNode(node, context); const preExecQueries = context.getPreExecuteQueries(); return new JSCompoundQuery(preExecQueries, jsQuery, resultVariable, resultValidator); } type NodeProcessor<T extends QueryNode> = (node: T, context: QueryContext) => JSFragment; namespace jsExt { export function safeJSONKey(key: string): JSFragment { if (js.isSafeIdentifier(key)) { return js`${js.string(key)}`; // if safe, use "name" approach } else { return js`${key}`; // fall back to bound values } } export function executingFunction(...content: JSFragment[]): JSFragment { return js.lines(js`(function() {`, js.indent(js.lines(...content)), js`})()`); } export function lambda(variable: JSVariable, expression: JSFragment) { return js`${variable} => (${expression})`; } export function evaluatingLambda(variable: JSVariable, expression: JSFragment, value: JSFragment) { return js`(${jsExt.lambda(variable, expression)})(${value})`; } } const processors = new Map<Constructor<QueryNode>, NodeProcessor<QueryNode>>(); function register<T extends QueryNode>(type: Constructor<T>, processor: NodeProcessor<T>) { processors.set(type, processor as NodeProcessor<QueryNode>); // probably some bivariancy issue } register(LiteralQueryNode, node => { return js.value(node.value); }); register(NullQueryNode, () => { return js`null`; }); register(RuntimeErrorQueryNode, node => { const runtimeErrorToken = js.code(RUNTIME_ERROR_TOKEN); if (node.code) { const codeProp = js.code(RUNTIME_ERROR_CODE_PROPERTY); return js`{ ${codeProp}: ${node.code}, ${runtimeErrorToken}: ${node.message} }`; } return js`{ ${runtimeErrorToken}: ${node.message} }`; }); register(ConstBoolQueryNode, node => { return node.value ? js`true` : js`false`; }); register(ConstIntQueryNode, node => { return js.integer(node.value); }); register(ObjectQueryNode, (node, context) => { if (!node.properties.length) { return js`{}`; } const properties = node.properties.map( p => js`${jsExt.safeJSONKey(p.propertyName)}: ${processNode(p.valueNode, context)}` ); return js.lines(js`{`, js.indent(js.join(properties, js`,\n`)), js`}`); }); register(ListQueryNode, (node, context) => { if (!node.itemNodes.length) { return js`[]`; } return js.lines( js`[`, js.indent( js.join( node.itemNodes.map(itemNode => processNode(itemNode, context)), js`,\n` ) ), js`]` ); }); register(ConcatListsQueryNode, (node, context) => { const listNodes = node.listNodes.map(node => js`...${processNode(node, context)}`); const listNodeStr = js.join(listNodes, js`, `); return js`[${listNodeStr}]`; }); register(VariableQueryNode, (node, context) => { return context.getVariable(node); }); register(VariableAssignmentQueryNode, (node, context) => { const newContext = context.introduceVariable(node.variableNode); const tmpVar = newContext.getVariable(node.variableNode); return jsExt.executingFunction( js`const ${tmpVar} = ${processNode(node.variableValueNode, newContext)};`, js`return ${processNode(node.resultNode, newContext)}` ); }); register(WithPreExecutionQueryNode, (node, context) => { let currentContext = context; for (const preExecParm of node.preExecQueries) { currentContext = currentContext.addPreExecuteQuery( preExecParm.query, preExecParm.resultVariable, preExecParm.resultValidator ); } return js`${processNode(node.resultNode, currentContext)}`; }); register(EntityFromIdQueryNode, (node, context) => { const itemVariable = new VariableQueryNode(decapitalize(node.rootEntityType.name)); return processNode( new FirstOfListQueryNode( new TransformListQueryNode({ listNode: new EntitiesQueryNode(node.rootEntityType), itemVariable, filterNode: new BinaryOperationQueryNode( new RootEntityIDQueryNode(itemVariable), BinaryOperator.EQUAL, node.idNode ) }) ), context ); }); register(FieldQueryNode, (node, context) => { const object = processNode(node.objectNode, context); return getPropertyAccessFrag(node.field.name, object); }); register(PropertyAccessQueryNode, (node, context) => { const object = processNode(node.objectNode, context); return getPropertyAccessFrag(node.propertyName, object); }); function getPropertyAccessFrag(propertyName: string, objectFrag: JSFragment) { const objectVar = js.variable('object'); const identifier = jsExt.safeJSONKey(propertyName); // always use [] access because we could collide with keywords // avoid undefined values because they cause trouble when being compared with === to null const raw = js`${identifier} in ${objectVar} ? ${objectVar}[${identifier}] : null`; // mimick arango behavior here which propagates null return jsExt.evaluatingLambda( objectVar, js`((typeof (${objectVar}) == 'object' && (${objectVar}) != null) ? (${raw}) : null)`, objectFrag ); } register(DynamicPropertyAccessQueryNode, (node, context) => { const objectFrag = processNode(node.objectNode, context); const objectVar = js.variable('object'); const keyFrag = processNode(node.propertyNode, context); // always use [] access because we could collide with keywords // avoid undefined values because they cause trouble when being compared with === to null const raw = js`${keyFrag} in ${objectVar} ? ${objectVar}[${keyFrag}] : null`; // mimick arango behavior here which propagates null return jsExt.evaluatingLambda( objectVar, js`((typeof (${objectVar}) == 'object' && (${objectVar}) != null) ? (${raw}) : null)`, objectFrag ); }); register(RootEntityIDQueryNode, (node, context) => { return getPropertyAccessFrag('id', processNode(node.objectNode, context)); }); register(TransformListQueryNode, (node, context) => { let itemContext = context.introduceVariable(node.itemVariable); const itemVar = itemContext.getVariable(node.itemVariable); function lambda(exprNode: QueryNode) { return jsExt.lambda(itemVar, processNode(exprNode, itemContext)); } const comparator = node.orderBy.isUnordered() ? undefined : getComparatorForOrderSpecification(node.orderBy, itemVar, itemContext); const isFiltered = !(node.filterNode instanceof ConstBoolQueryNode) || node.filterNode.value != true; const isMapped = node.innerNode != node.itemVariable; let sliceClause; if (node.maxCount != undefined) { sliceClause = js`.slice(${node.skip}, ${node.skip + node.maxCount})`; } else if (node.skip > 0) { sliceClause = js`.slice(${node.skip})`; } else { sliceClause = js``; } return js.lines( processNode(node.listNode, context), js.indent( js.lines( isFiltered ? js`.filter(${lambda(node.filterNode)})` : js``, comparator ? js`.slice().sort(${comparator})` : js``, // need slice() to not replace something in-place sliceClause, isMapped ? js`.map(${lambda(node.innerNode)})` : js`` ) ) ); }); register(CountQueryNode, (node, context) => { return js`${processNode(node.listNode, context)}.length`; }); register(AggregationQueryNode, (node, context) => { const itemVar = js.variable('item'); const indexVar = js.variable('index'); const accumulatorVar = js.variable('acc'); const listFrag = processNode(node.listNode, context); const listVar = js.variable('list'); const listWithoutNullsFrag = js`${listFrag}.filter(${itemVar} => ${itemVar} != null)`; switch (node.operator) { case AggregationOperator.SUM: return js`${listWithoutNullsFrag}.reduce((${itemVar}, ${accumulatorVar}) => ${accumulatorVar} + ${itemVar}, 0)`; case AggregationOperator.AVERAGE: return jsExt.evaluatingLambda( listVar, js`${listVar}.length ? (${listVar}.reduce((${itemVar}, ${accumulatorVar}) => ${accumulatorVar} + ${itemVar}) / ${listVar}.length) : null`, listWithoutNullsFrag ); case AggregationOperator.MIN: return js`support.min(${listWithoutNullsFrag})`; case AggregationOperator.MAX: return js`support.max(${listWithoutNullsFrag})`; case AggregationOperator.SOME_TRUE: return js`${listFrag}.some(${jsExt.lambda(itemVar, itemVar)})`; case AggregationOperator.SOME_NOT_TRUE: return js`${listFrag}.some(${jsExt.lambda(itemVar, js`!${itemVar}`)})`; case AggregationOperator.EVERY_TRUE: return js`${listFrag}.every(${jsExt.lambda(itemVar, itemVar)})`; case AggregationOperator.NONE_TRUE: return js`(!${listFrag}.some(${jsExt.lambda(itemVar, itemVar)}))`; case AggregationOperator.COUNT_TRUE: return js`${listFrag}.filter(${jsExt.lambda(itemVar, itemVar)}).length`; case AggregationOperator.COUNT_NOT_TRUE: return js`${listFrag}.filter(${jsExt.lambda(itemVar, js`!${itemVar}`)}).length`; case AggregationOperator.SOME_NULL: return js`${listFrag}.some(${jsExt.lambda(itemVar, js`${itemVar} == null`)})`; case AggregationOperator.SOME_NOT_NULL: return js`${listFrag}.some(${jsExt.lambda(itemVar, js`${itemVar} != null`)})`; case AggregationOperator.EVERY_NULL: return js`${listFrag}.every(${jsExt.lambda(itemVar, js`${itemVar} == null`)})`; case AggregationOperator.NONE_NULL: return js`${listFrag}.every(${jsExt.lambda(itemVar, js`${itemVar} != null`)})`; case AggregationOperator.COUNT_NULL: return js`${listFrag}.filter(${jsExt.lambda(itemVar, js`${itemVar} == null`)}).length`; case AggregationOperator.COUNT_NOT_NULL: return js`${listFrag}.filter(${jsExt.lambda(itemVar, js`${itemVar} != null`)}).length`; case AggregationOperator.COUNT: return js`${listFrag}.length`; case AggregationOperator.SOME: return js`(!!${listFrag}.length)`; case AggregationOperator.NONE: return js`(!${listFrag}.length)`; // these should also remove null values by definition case AggregationOperator.DISTINCT: const innerVar = js.variable(); const list = jsExt.evaluatingLambda( listVar, js`${listVar}.filter((${itemVar}, ${indexVar}) => (${itemVar} != null && ${listVar}.findIndex(${innerVar} => JSON.stringify(${itemVar}) === JSON.stringify(${innerVar})) === ${indexVar}))`, listWithoutNullsFrag ); if (node.sort) { return js`${list}.sort(support.compare)`; } return list; case AggregationOperator.COUNT_DISTINCT: return jsExt.evaluatingLambda( listVar, js`${listVar}.filter((${itemVar}, ${indexVar}) => (${itemVar} != null && ${listVar}.indexOf(${itemVar}) === ${indexVar})).length`, listWithoutNullsFrag ); default: throw new Error(`Unsupported aggregation operator: ${(node as any).operator}`); } }); register(MergeObjectsQueryNode, (node, context) => { const objectList = node.objectNodes.map(node => processNode(node, context)); const objectsFragment = js.join(objectList, js`, `); return js`Object.assign({}, ${objectsFragment})`; }); register(ObjectEntriesQueryNode, (node, context) => { const objVar = js.variable('object'); return jsExt.evaluatingLambda( objVar, js`(${objVar} && typeof ${objVar} === 'object') ? Object.entries(${objVar}) : []`, processNode(node.objectNode, context) ); }); register(FirstOfListQueryNode, (node, context) => { const listVar = js.variable('list'); return jsExt.evaluatingLambda( listVar, js`${listVar}.length ? ${listVar}[0] : null`, processNode(node.listNode, context) ); }); register(ListItemQueryNode, (node, context) => { const listVar = js.variable('list'); return jsExt.evaluatingLambda( listVar, js`${listVar}.length > ${node.index} ? ${listVar}[${node.index}] : null`, processNode(node.listNode, context) ); }); register(BinaryOperationQueryNode, (node, context) => { const lhs = processNode(node.lhs, context); const rhs = processNode(node.rhs, context); const lhsVar = js.variable('lhs'); const rhsVar = js.variable('rhs'); const lhsListOrString = jsExt.evaluatingLambda( lhsVar, js`(Array.isArray(${lhsVar}) ? ${lhsVar} : String(${lhsVar}))`, lhs ); const rhsListOrString = jsExt.evaluatingLambda( rhsVar, js`(Array.isArray(${rhsVar}) ? ${rhsVar} : String(${rhsVar}))`, rhs ); const op = getJSOperator(node.operator); if (op) { return js`(${lhs} ${op} ${rhs})`; } switch (node.operator) { case BinaryOperator.LESS_THAN: return compare(js`<`, lhs, rhs); case BinaryOperator.LESS_THAN_OR_EQUAL: return compare(js`<=`, lhs, rhs); case BinaryOperator.GREATER_THAN: return compare(js`>`, lhs, rhs); case BinaryOperator.GREATER_THAN_OR_EQUAL: return compare(js`>=`, lhs, rhs); case BinaryOperator.CONTAINS: return js`${lhsListOrString}.includes(${rhs})`; case BinaryOperator.IN: return js`${rhsListOrString}.includes(${lhs})`; case BinaryOperator.STARTS_WITH: return js`String(${lhs}).startsWith(${rhs})`; case BinaryOperator.ENDS_WITH: return js`String(${lhs}).endsWith(${rhs})`; case BinaryOperator.LIKE: if (node.rhs instanceof LiteralQueryNode && typeof node.rhs.value === 'string') { const regexp = likePatternToRegExp(node.rhs.value); return js`!!String(${lhs}).match(${js.value(regexp)})`; } return js`!!String(${lhs}).match(support.likePatternToRegExp(${rhs})`; case BinaryOperator.APPEND: // TODO would not work for lists, is this neccessary? return js`String(${lhs}) + String(${rhs})`; case BinaryOperator.PREPEND: return js`String(${rhs}) + String(${lhs})`; case BinaryOperator.SUBTRACT_LISTS: const itemVar = js.variable('item'); return js`(${lhs}).filter(${itemVar} => !${rhs}.includes(${itemVar}))`; default: throw new Error(`Unsupported binary operator: ${op}`); } }); register(UnaryOperationQueryNode, (node, context) => { switch (node.operator) { case UnaryOperator.NOT: return js`!(${processNode(node.valueNode, context)})`; case UnaryOperator.JSON_STRINGIFY: return js`JSON.stringify(${processNode(node.valueNode, context)})`; case UnaryOperator.ROUND: return js`Math.round(${processNode(node.valueNode, context)})`; default: throw new Error(`Unsupported unary operator: ${node.operator}`); } }); register(ConditionalQueryNode, (node, context) => { const cond = processNode(node.condition, context); const expr1 = processNode(node.expr1, context); const expr2 = processNode(node.expr2, context); return js`(${cond} ? ${expr1} : ${expr2})`; }); register(TypeCheckQueryNode, (node, context) => { const value = js`(${processNode(node.valueNode, context)})`; const valueVar = js.variable('value'); switch (node.type) { case BasicType.SCALAR: return jsExt.evaluatingLambda( valueVar, js`(typeof ${valueVar} == 'boolean' || typeof ${valueVar} == 'number || typeof ${valueVar} == 'string')`, value ); case BasicType.LIST: return js`Array.isArray(${value})`; case BasicType.OBJECT: return jsExt.evaluatingLambda( valueVar, js`typeof ${valueVar} == 'object' && ${valueVar} != null && !Array.isArray(${valueVar})`, value ); case BasicType.NULL: return js`${value} == null`; } }); register(SafeListQueryNode, (node, context) => { const reducedNode = new ConditionalQueryNode( new TypeCheckQueryNode(node.sourceNode, BasicType.LIST), node.sourceNode, ListQueryNode.EMPTY ); return processNode(reducedNode, context); }); register(QuantifierFilterNode, (node, context) => { let { quantifier, conditionNode, listNode, itemVariable } = node; // reduce 'every' to 'none' so that count-based evaluation is possible if (quantifier === 'every') { quantifier = 'none'; conditionNode = not(conditionNode); } const filteredListNode = new TransformListQueryNode({ listNode, filterNode: conditionNode, itemVariable }); const finalNode = new BinaryOperationQueryNode( new CountQueryNode(filteredListNode), quantifier === 'none' ? BinaryOperator.EQUAL : BinaryOperator.GREATER_THAN, new LiteralQueryNode(0) ); return processNode(finalNode, context); }); register(EntitiesQueryNode, (node, context) => { return getCollectionForType(node.rootEntityType, context); }); register(FollowEdgeQueryNode, (node, context) => { const sourceID = processNode(new RootEntityIDQueryNode(node.sourceEntityNode), context); return getFollowEdgeFragment(node.relationSide, sourceID, context); }); function getFollowEdgeFragment( relationSide: RelationSide, sourceIDFrag: JSFragment, context: QueryContext ): JSFragment { const targetType = relationSide.targetType; const targetColl = getCollectionForType(targetType, context); const edgeColl = getCollectionForRelation(relationSide.relation, context); const edgeVar = js.variable('edge'); const itemVar = js.variable(decapitalize(targetType.name)); const sourceIDOnEdge = relationSide.isFromSide ? js`${edgeVar}._from` : js`${edgeVar}._to`; const targetIDOnEdge = relationSide.isFromSide ? js`${edgeVar}._to` : js`${edgeVar}._from`; const idOnItem = js`${itemVar}.${js.identifier(ID_FIELD_NAME)}`; const idOnItemEqualsTargetIDOnEdge = js`${idOnItem} === ${targetIDOnEdge}`; return js.lines( js`${edgeColl}`, js.indent( js.lines( js`.filter(${jsExt.lambda(edgeVar, js`${sourceIDOnEdge} == ${sourceIDFrag}`)})`, js`.map(${jsExt.lambda( edgeVar, js`${targetColl}.find(${jsExt.lambda(itemVar, idOnItemEqualsTargetIDOnEdge)})` )})`, js`.filter(${jsExt.lambda(itemVar, itemVar)})` // filter out nulls ) ) ); } register(TraversalQueryNode, (node, context) => { let currentFrag: JSFragment = processNode(node.sourceEntityNode, context); let isList = node.sourceIsList; let isAlreadyID = node.entitiesIdentifierKind === EntitiesIdentifierKind.ID; if (!node.relationSegments.length && node.entitiesIdentifierKind !== EntitiesIdentifierKind.ENTITY) { throw new Error(`Only ENTITY identifiers supported without relationSegments`); } let segmentIndex = 0; for (const segment of node.relationSegments) { if (segment.vertexFilter) { throw new Error(`@collect with accessGroup restrictions is not supported by InMemoryAdapter`); } const nodeVar = js.variable('node'); const idFrag = isAlreadyID ? nodeVar : js`${nodeVar}.${js.identifier(ID_FIELD_NAME)}`; if (isList) { const accVar = js.variable('acc'); let edgeListFragment = js`${nodeVar} ? ${getFollowEdgeFragment( segment.relationSide, idFrag, context )} : null`; if ( !segment.isListSegment && (!node.alwaysProduceList || segmentIndex < node.relationSegments.length - 1) ) { // to-1 relations can be nullable and we need to keep the NULL values (and not just pretend the source didn't exist) const edgeListVar = js.variable('edges'); edgeListFragment = jsExt.evaluatingLambda( edgeListVar, js`${edgeListVar}.length ? ${edgeListVar} : [null]`, edgeListFragment ); } const reducer = js`(${accVar}, ${nodeVar}) => ${accVar}.concat(${edgeListFragment})`; currentFrag = js`${currentFrag}.reduce(${reducer}, [])`; } else { currentFrag = jsExt.evaluatingLambda( nodeVar, js`${nodeVar} ? ${getFollowEdgeFragment(segment.relationSide, idFrag, context)} : null`, currentFrag ); if (!segment.isListSegment) { // to-1 relations can be nullable and we need to keep the NULL values (and not just pretend the source didn't exist) currentFrag = js`(${currentFrag}[0] || null)`; } } if (segment.minDepth !== 1 || segment.maxDepth !== 1) { throw new Error(`Traversal with min/max depth is not supported by InMemoryAdapter`); } if (segment.isListSegment) { isList = true; } segmentIndex++; } // if we need to capture the root, do this (pseudo-code) // source.rel1.flatMap(o => o.rel2).flatMap(o2 => o2.rel3).flatMap(root => { root, obj: root.field1.flatMap(o => o.field2) }) // if the relations don't return a list, call the mapper directly const relationTraversalReturnsList = isList; let rootVar: JSVariable | undefined; let relationFrag: JSFragment | undefined; if (node.captureRootEntity) { relationFrag = currentFrag; rootVar = js.variable('root'); currentFrag = rootVar; isList = false; // we're going to be within the mapper, so not in a list } for (const segment of node.fieldSegments) { if (isList) { if (segment.isListSegment) { const nodeVar = js.variable('node'); const accVar = js.variable('acc'); const safeListVar = js.variable('list'); // || [] to not concat `null` to a list const reducer = js`(${accVar}, ${nodeVar}) => ${accVar}.concat(${getPropertyAccessFrag( segment.field.name, nodeVar )} || [])`; currentFrag = jsExt.evaluatingLambda( safeListVar, js`${safeListVar}.reduce(${reducer}, [])`, js`${currentFrag} || []` ); } else { const nodeVar = js.variable('node'); const mapper = jsExt.lambda(nodeVar, getPropertyAccessFrag(segment.field.name, nodeVar)); currentFrag = js`${currentFrag}.map(${mapper})`; } } else { currentFrag = getPropertyAccessFrag(segment.field.name, currentFrag); } if (segment.isListSegment) { isList = true; } } if (relationFrag && rootVar && node.captureRootEntity) { if (relationTraversalReturnsList) { if (node.fieldSegments.some(f => f.isListSegment)) { const accVar = js.variable('acc'); const objVar = js.variable('obj'); const mapper = js`${objVar} => ({ obj: ${objVar}, root: ${rootVar} })`; const reducer = js`(${accVar}, ${rootVar}) => ${accVar}.concat((${currentFrag}).map(${mapper}))`; currentFrag = js`${relationFrag}.reduce(${reducer}, [])`; } else { const mapper = js`${rootVar} => ({ obj: ${currentFrag}, root: ${rootVar} })`; currentFrag = js`${relationFrag}.map(${mapper})`; } } else { if (node.fieldSegments.some(f => f.isListSegment)) { const objVar = js.variable('obj'); const mapper = js`${objVar} => ({ obj: ${objVar}, root: ${rootVar} })`; currentFrag = jsExt.evaluatingLambda(rootVar, js`(${currentFrag}).map(${mapper})`, relationFrag); } else { currentFrag = jsExt.evaluatingLambda( rootVar, js`({ obj: ${currentFrag}, root: ${rootVar} })`, relationFrag ); } } } if (node.alwaysProduceList && !isList) { const resultVar = js.variable('result'); currentFrag = jsExt.evaluatingLambda( resultVar, js`${currentFrag} == null ? [] : [ ${currentFrag} ]`, currentFrag ); } return currentFrag; }); register(CreateEntityQueryNode, (node, context) => { const objVar = js.variable('obj'); const idVar = js.variable('id'); return jsExt.executingFunction( js`const ${objVar} = ${processNode(node.objectNode, context)};`, js`const ${idVar} = db.generateID();`, js`${objVar}.${js.identifier(ID_FIELD_NAME)} = ${idVar};`, js`${js.collection(getCollectionNameForRootEntity(node.rootEntityType))}.push(${objVar});`, js`return ${idVar};` ); }); register(UpdateEntitiesQueryNode, (node, context) => { const newContext = context.introduceVariable(node.currentEntityVariable); const entityVar = newContext.getVariable(node.currentEntityVariable); function lambda(inner: JSFragment) { return jsExt.lambda(entityVar, inner); } const updateFunction: JSFragment = jsExt.executingFunction( js`Object.assign(${entityVar}, ${processNode(new ObjectQueryNode(node.updates), newContext)});`, js`return ${entityVar}.${js.identifier(ID_FIELD_NAME)};` ); return js.lines( js`${processNode(node.listNode, context)}`, js.indent(js.lines(js`.map(${lambda(updateFunction)})`)) ); }); register(DeleteEntitiesQueryNode, (node, context) => { const itemVar = js.variable(decapitalize(node.rootEntityType.name)); const listVar = js.variable('objectsToDelete'); const coll = js.collection(getCollectionNameForRootEntity(node.rootEntityType)); const idsVar = js.variable('ids'); const oldsVar = js.variable('olds'); let idListFrag; let oldsFrag; switch (node.entitiesIdentifierKind) { case EntitiesIdentifierKind.ENTITY: idListFrag = js`${listVar}.map(${jsExt.lambda(itemVar, js`${itemVar}.${js.identifier(ID_FIELD_NAME)}`)})`; oldsFrag = listVar; break; case EntitiesIdentifierKind.ID: idListFrag = listVar; const itemVar2 = js.variable(decapitalize(node.rootEntityType.name)); // pretty inefficient, but it's only the js adapter, right oldsFrag = js`${idListFrag}.map(${jsExt.lambda( itemVar, js`${coll}.find(${jsExt.lambda( itemVar2, js`${itemVar2}.${js.identifier(ID_FIELD_NAME)} === ${itemVar}` )})` )})`; break; default: throw new Error(`Unexpected EntitiesIdentifierKind: ${node.entitiesIdentifierKind}`); } return jsExt.executingFunction( js`const ${listVar} = ${processNode(node.listNode, context)}`, js`const ${idsVar} = new Set(${idListFrag});`, js`const ${oldsVar} = ${oldsFrag};`, js`${coll} = ${coll}.filter(${jsExt.lambda( itemVar, js`!${idsVar}.has(${itemVar}.${js.identifier(ID_FIELD_NAME)})` )});`, js`return ${oldsVar};` ); }); register(AddEdgesQueryNode, (node, context) => { const coll = getCollectionForRelation(node.relation, context); const edgesJS = js.lines( js`[`, js.indent( js.join( node.edges.map( edge => js`{ _from: ${processNode(edge.fromIDNode, context)}, _to: ${processNode( edge.toIDNode, context )} }` ), js`,\n` ) ), js`]` ); function edgeExists(edge: JSFragment) { const edgeVar = js.variable('edge'); return js`${coll}.some(${jsExt.lambda( edgeVar, js`${edgeVar}._from == ${edge}._from && ${edgeVar}._to === ${edge}._to` )})`; } const toAdd = js.variable(`toAdd`); return js`${edgesJS}.forEach(${jsExt.lambda( toAdd, js`${edgeExists(toAdd)} ? undefined : ${coll}.push(${toAdd})` )})`; }); register(RemoveEdgesQueryNode, (node, context) => { const coll = getCollectionForRelation(node.relation, context); const edgeVar = js.variable('edge'); const fromIDs = node.edgeFilter.fromIDsNode ? processNode(node.edgeFilter.fromIDsNode, context) : undefined; const toIDs = node.edgeFilter.toIDsNode ? processNode(node.edgeFilter.toIDsNode, context) : undefined; const edgeRemovalCriteria = compact([ fromIDs ? js`${fromIDs}.includes(${edgeVar}._from)` : undefined, toIDs ? js`${toIDs}.includes(${edgeVar}._to)` : undefined ]); const edgeShouldStay = js`!(${js.join(edgeRemovalCriteria, js` && `)})`; return jsExt.executingFunction(js`${coll} = ${coll}.filter(${jsExt.lambda(edgeVar, edgeShouldStay)});`); }); register(OperatorWithAnalyzerQueryNode, (node, context) => { if (node.analyzer !== NORM_CI_ANALYZER && node.analyzer !== IDENTITY_ANALYZER && node.analyzer !== null) { throw new FlexSearchAnalyzerNotSupportedError(node.analyzer); } const isCaseInsensitive = node.analyzer === NORM_CI_ANALYZER; let lhs = processNode(node.lhs, context); let rhs = processNode(node.rhs, context); if (isCaseInsensitive) { lhs = js`${lhs}.toLowerCase()`; const rhsVar = js.variable('rhs'); rhs = jsExt.evaluatingLambda( rhsVar, js`(Array.isArray(${rhsVar}) ? ${rhsVar}.map(value => value.toLowerCase()) : ${rhsVar}.toLowerCase())`, rhs ); } switch (node.operator) { case BinaryOperatorWithAnalyzer.EQUAL: return js`(${lhs} === ${rhs})`; case BinaryOperatorWithAnalyzer.UNEQUAL: return js`(${lhs} !== ${rhs})`; case BinaryOperatorWithAnalyzer.FLEX_STRING_LESS_THAN: return compare(js`<`, lhs, rhs); case BinaryOperatorWithAnalyzer.FLEX_STRING_LESS_THAN_OR_EQUAL: return compare(js`<=`, lhs, rhs); case BinaryOperatorWithAnalyzer.FLEX_STRING_GREATER_THAN: return compare(js`>`, lhs, rhs); case BinaryOperatorWithAnalyzer.FLEX_STRING_GREATER_THAN_OR_EQUAL: return compare(js`>=`, lhs, rhs); case BinaryOperatorWithAnalyzer.IN: return js`${rhs}.includes(${lhs})`; case BinaryOperatorWithAnalyzer.FLEX_SEARCH_CONTAINS_ANY_WORD: case BinaryOperatorWithAnalyzer.FLEX_SEARCH_CONTAINS_PREFIX: case BinaryOperatorWithAnalyzer.FLEX_SEARCH_CONTAINS_PHRASE: default: throw new Error(`Unsupported binary operator with analyzer: ${node.operator}`); } }); register(FlexSearchQueryNode, (node, context) => { let itemContext = context.introduceVariable(node.itemVariable); const itemVar = itemContext.getVariable(node.itemVariable); function lambda(exprNode: QueryNode) { return jsExt.lambda(itemVar, processNode(exprNode, itemContext)); } const isFiltered = !(node.flexFilterNode instanceof ConstBoolQueryNode) || node.flexFilterNode.value != true; let orderFrag = js``; if (node.rootEntityType.flexSearchPrimarySort.length) { const order = new OrderSpecification( node.rootEntityType.flexSearchPrimarySort.map( c => new OrderClause(createFieldPathNode(c.field, node.itemVariable), c.direction) ) ); const comparator = getComparatorForOrderSpecification(order, itemVar, itemContext); orderFrag = js`.slice().sort(${comparator})`; } return js.lines( getCollectionForType(node.rootEntityType, context), js.indent(js.lines(isFiltered ? js`.filter(${lambda(node.flexFilterNode)})` : js``)), orderFrag ); }); register(FlexSearchFieldExistsQueryNode, (node, context) => { const sourceNodeResult = processNode(node.sourceNode, context); return js`(${sourceNodeResult} != null)`; }); register(FieldPathQueryNode, (node, context) => { const object = processNode(node.objectNode, context); for (const field of node.path) { if (field.isList) { throw new FlexSearchAggregationNotSupportedError(); } } let fragment = getPropertyAccessFrag(node.path[0].name, object); for (const field of node.path.slice(1, node.path.length)) { fragment = getPropertyAccessFrag(field.name, fragment); } return fragment; }); register(FlexSearchStartsWithQueryNode, (node, context) => { const lhs = processNode(node.lhs, context); const rhs = processNode(node.rhs, context); return js`(String(${lhs}).startsWith(${rhs}))`; }); register(FlexSearchComplexOperatorQueryNode, (node, context) => { throw new Error(`Internal Error: FlexSearchComplexOperatorQueryNode must be expanded before generating the query.`); }); register(CreateBillingEntityQueryNode, (node, context) => { const currentTimestamp = new Date().toISOString(); const billingEntities = js.collection('billingEntities'); return jsExt.executingFunction( js` const entry = ${billingEntities}.find(value => (value.key === ${node.key} && value.type === ${ node.rootEntityTypeName })); if(!entry){ ${billingEntities}.push({ key: ${node.key}, type: ${node.rootEntityTypeName}, category: ${processNode(node.categoryNode, context)}, quantity: ${processNode(node.quantityNode, context)}, isExported: false, isConfirmedForExport: false, createdAt: ${currentTimestamp}, updatedAt: ${currentTimestamp} }); }` ); }); register(ConfirmForBillingQueryNode, (node, context) => { const key = processNode(node.keyNode, context); const currentTimestamp = new Date().toISOString(); const billingEntities = js.collection('billingEntities'); return jsExt.executingFunction( js` const entry = ${billingEntities}.find(value => (value.key === ${key} && value.type === ${ node.rootEntityTypeName })); if(!entry){ ${billingEntities}.push({ key: ${key}, type: ${node.rootEntityTypeName}, isExported: false, category: ${processNode(node.categoryNode, context)}, quantity: ${processNode(node.quantityNode, context)}, isConfirmedForExport: true, confirmedForExportAt: ${currentTimestamp}, createdAt: ${currentTimestamp}, updatedAt: ${currentTimestamp} }); } else { entry.isConfirmedForExport = true; entry.confirmedForExportAt = ${currentTimestamp}; }` ); }); register(SetEdgeQueryNode, (node, context) => { const coll = getCollectionForRelation(node.relation, context); const edgeVar = js.variable('edge'); const edgeRemovalCriteria = compact([ node.existingEdge.fromIDNode ? js`${edgeVar}._from == ${processNode(node.existingEdge.fromIDNode, context)}` : undefined, node.existingEdge.toIDNode ? js`${edgeVar}._to == ${processNode(node.existingEdge.toIDNode, context)}` : undefined ]); const edgeShouldStay = js`!(${js.join(edgeRemovalCriteria, js` && `)})`; return jsExt.executingFunction( js`${coll} = ${coll}.filter(${jsExt.lambda(edgeVar, edgeShouldStay)});`, js`${coll}.push({ _from: ${processNode(node.newEdge.fromIDNode, context)}, _to: ${processNode( node.newEdge.toIDNode, context )} });` ); }); function getJSOperator(op: BinaryOperator): JSFragment | undefined { switch (op) { case BinaryOperator.AND: return js`&&`; case BinaryOperator.OR: return js`||`; case BinaryOperator.EQUAL: return js`===`; case BinaryOperator.UNEQUAL: return js`!==`; case BinaryOperator.ADD: return js`+`; case BinaryOperator.SUBTRACT: return js`-`; case BinaryOperator.MULTIPLY: return js`*`; case BinaryOperator.DIVIDE: return js`/`; case BinaryOperator.MODULO: return js`%`; default: return undefined; } } function getComparatorForOrderSpecification(orderBy: OrderSpecification, itemVar: JSFragment, context: QueryContext) { function getClauseFnAndInvert(clause: OrderClause): JSFragment { const valueLambda = jsExt.lambda(itemVar, processNode(clause.valueNode, context)); return js`[${valueLambda}, ${clause.direction == OrderDirection.DESCENDING ? js`true` : js`false`}]`; } const args = orderBy.clauses.map(clause => getClauseFnAndInvert(clause)); return js`support.getMultiComparator(${js.join(args, js`, `)})`; } function processNode(node: QueryNode, context: QueryContext): JSFragment { const processor = processors.get(node.constructor as Constructor<QueryNode>); if (!processor) { throw new Error(`Unsupported query type: ${node.constructor}`); } return processor(node, context); } // TODO I think JSCompoundQuery (JS transaction node) should not be the exported type // we should rather export JSExecutableQuery[] (as JS transaction) directly. export function getJSQuery(node: QueryNode): JSCompoundQuery { return createJSCompoundQuery(node, js.queryResultVariable('result'), undefined, new QueryContext()); } function getCollectionForType(type: RootEntityType, context: QueryContext) { const name = getCollectionNameForRootEntity(type); return js.collection(name); } function getCollectionForRelation(relation: Relation, context: QueryContext) { const name = getCollectionNameForRelation(relation); return js.collection(name); } function compare(comp: JSFragment, lhs: JSFragment, rhs: JSFragment) { return js.lines(js`support.compare(`, js.indent(js.lines(js`${lhs},`, js`${rhs}`)), js`) ${comp} 0`); } /** * Is thrown if a FlexSearch query containing fulltext-filters is performed for an in-memory database. */ export class FlexSearchAnalyzerNotSupportedError extends Error { constructor(analyzer: string) { super( `FlexSearch-query was not executed, because filters with analyzer "${analyzer}" are not supported for in-memory database.` ); this.name = this.constructor.name; } } /** * Is thrown if a FlexSearch query containing an aggregation filter is performed for an in-memory database. */ export class FlexSearchAggregationNotSupportedError extends Error { constructor() { super(`FlexSearch-query was not executed, because aggregations are not supported for in-memory database.`); this.name = this.constructor.name; } }
the_stack
import { IBulkEditService, ResourceEdit, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService'; import { IPosition, Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { EndOfLinePreference, IReadonlyTextBuffer } from 'vs/editor/common/model'; import { PLAINTEXT_LANGUAGE_ID } from 'vs/editor/common/languages/modesRegistry'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ResourceNotebookCellEdit } from 'vs/workbench/contrib/bulkEdit/browser/bulkCellEdits'; import { INotebookActionContext, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions'; import { CellEditState, CellFocusMode, expandCellRangesWithHiddenCells, IActiveNotebookEditor, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { CellViewModel, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModelImpl'; import { cloneNotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel'; import { CellEditType, CellKind, ICellEditOperation, ICellReplaceEdit, IOutputDto, ISelectionState, NotebookCellMetadata, SelectionStateType } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { cellRangeContains, cellRangesToIndexes, ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange'; export async function changeCellToKind(kind: CellKind, context: INotebookActionContext, language?: string, mime?: string): Promise<void> { const { notebookEditor } = context; if (!notebookEditor.hasModel()) { return; } if (notebookEditor.isReadOnly) { return; } if (context.ui && context.cell) { // action from UI const { cell } = context; if (cell.cellKind === kind) { return; } const text = cell.getText(); const idx = notebookEditor.getCellIndex(cell); if (language === undefined) { const availableLanguages = notebookEditor.activeKernel?.supportedLanguages ?? []; language = availableLanguages[0] ?? PLAINTEXT_LANGUAGE_ID; } notebookEditor.textModel.applyEdits([ { editType: CellEditType.Replace, index: idx, count: 1, cells: [{ cellKind: kind, source: text, language: language!, mime: mime ?? cell.mime, outputs: cell.model.outputs, metadata: cell.metadata, }] } ], true, { kind: SelectionStateType.Index, focus: notebookEditor.getFocus(), selections: notebookEditor.getSelections() }, () => { return { kind: SelectionStateType.Index, focus: notebookEditor.getFocus(), selections: notebookEditor.getSelections() }; }, undefined, true); const newCell = notebookEditor.cellAt(idx); await notebookEditor.focusNotebookCell(newCell, cell.getEditState() === CellEditState.Editing ? 'editor' : 'container'); } else if (context.selectedCells) { const selectedCells = context.selectedCells; const rawEdits: ICellEditOperation[] = []; selectedCells.forEach(cell => { if (cell.cellKind === kind) { return; } const text = cell.getText(); const idx = notebookEditor.getCellIndex(cell); if (language === undefined) { const availableLanguages = notebookEditor.activeKernel?.supportedLanguages ?? []; language = availableLanguages[0] ?? PLAINTEXT_LANGUAGE_ID; } rawEdits.push( { editType: CellEditType.Replace, index: idx, count: 1, cells: [{ cellKind: kind, source: text, language: language!, mime: mime ?? cell.mime, outputs: cell.model.outputs, metadata: cell.metadata, }] } ); }); notebookEditor.textModel.applyEdits(rawEdits, true, { kind: SelectionStateType.Index, focus: notebookEditor.getFocus(), selections: notebookEditor.getSelections() }, () => { return { kind: SelectionStateType.Index, focus: notebookEditor.getFocus(), selections: notebookEditor.getSelections() }; }, undefined, true); } } export function runDeleteAction(editor: IActiveNotebookEditor, cell: ICellViewModel) { const textModel = editor.textModel; const selections = editor.getSelections(); const targetCellIndex = editor.getCellIndex(cell); const containingSelection = selections.find(selection => selection.start <= targetCellIndex && targetCellIndex < selection.end); if (containingSelection) { const edits: ICellReplaceEdit[] = selections.reverse().map(selection => ({ editType: CellEditType.Replace, index: selection.start, count: selection.end - selection.start, cells: [] })); const nextCellAfterContainingSelection = containingSelection.end >= editor.getLength() ? undefined : editor.cellAt(containingSelection.end); textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => { if (nextCellAfterContainingSelection) { const cellIndex = textModel.cells.findIndex(cell => cell.handle === nextCellAfterContainingSelection.handle); return { kind: SelectionStateType.Index, focus: { start: cellIndex, end: cellIndex + 1 }, selections: [{ start: cellIndex, end: cellIndex + 1 }] }; } else { if (textModel.length) { const lastCellIndex = textModel.length - 1; return { kind: SelectionStateType.Index, focus: { start: lastCellIndex, end: lastCellIndex + 1 }, selections: [{ start: lastCellIndex, end: lastCellIndex + 1 }] }; } else { return { kind: SelectionStateType.Index, focus: { start: 0, end: 0 }, selections: [{ start: 0, end: 0 }] }; } } }, undefined, true); } else { const focus = editor.getFocus(); const edits: ICellReplaceEdit[] = [{ editType: CellEditType.Replace, index: targetCellIndex, count: 1, cells: [] }]; const finalSelections: ICellRange[] = []; for (let i = 0; i < selections.length; i++) { const selection = selections[i]; if (selection.end <= targetCellIndex) { finalSelections.push(selection); } else if (selection.start > targetCellIndex) { finalSelections.push({ start: selection.start - 1, end: selection.end - 1 }); } else { finalSelections.push({ start: targetCellIndex, end: targetCellIndex + 1 }); } } if (editor.cellAt(focus.start) === cell) { // focus is the target, focus is also not part of any selection const newFocus = focus.end === textModel.length ? { start: focus.start - 1, end: focus.end - 1 } : focus; textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: finalSelections }), undefined, true); } else { // users decide to delete a cell out of current focus/selection const newFocus = focus.start > targetCellIndex ? { start: focus.start - 1, end: focus.end - 1 } : focus; textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: finalSelections }), undefined, true); } } } export async function moveCellRange(context: INotebookCellActionContext, direction: 'up' | 'down'): Promise<void> { if (!context.notebookEditor.hasModel()) { return; } const editor = context.notebookEditor; const textModel = editor.textModel; if (editor.isReadOnly) { return; } const selections = editor.getSelections(); const modelRanges = expandCellRangesWithHiddenCells(editor, selections); const range = modelRanges[0]; if (!range || range.start === range.end) { return; } if (direction === 'up') { if (range.start === 0) { return; } const indexAbove = range.start - 1; const finalSelection = { start: range.start - 1, end: range.end - 1 }; const focus = context.notebookEditor.getFocus(); const newFocus = cellRangeContains(range, focus) ? { start: focus.start - 1, end: focus.end - 1 } : { start: range.start - 1, end: range.start }; textModel.applyEdits([ { editType: CellEditType.Move, index: indexAbove, length: 1, newIdx: range.end - 1 }], true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: [finalSelection] }), undefined, true ); const focusRange = editor.getSelections()[0] ?? editor.getFocus(); editor.revealCellRangeInView(focusRange); } else { if (range.end >= textModel.length) { return; } const indexBelow = range.end; const finalSelection = { start: range.start + 1, end: range.end + 1 }; const focus = editor.getFocus(); const newFocus = cellRangeContains(range, focus) ? { start: focus.start + 1, end: focus.end + 1 } : { start: range.start + 1, end: range.start + 2 }; textModel.applyEdits([ { editType: CellEditType.Move, index: indexBelow, length: 1, newIdx: range.start }], true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: [finalSelection] }), undefined, true ); const focusRange = editor.getSelections()[0] ?? editor.getFocus(); editor.revealCellRangeInView(focusRange); } } export async function copyCellRange(context: INotebookCellActionContext, direction: 'up' | 'down'): Promise<void> { const editor = context.notebookEditor; if (!editor.hasModel()) { return; } const textModel = editor.textModel; if (editor.isReadOnly) { return; } let range: ICellRange | undefined = undefined; if (context.ui) { const targetCell = context.cell; const targetCellIndex = editor.getCellIndex(targetCell); range = { start: targetCellIndex, end: targetCellIndex + 1 }; } else { const selections = editor.getSelections(); const modelRanges = expandCellRangesWithHiddenCells(editor, selections); range = modelRanges[0]; } if (!range || range.start === range.end) { return; } if (direction === 'up') { // insert up, without changing focus and selections const focus = editor.getFocus(); const selections = editor.getSelections(); textModel.applyEdits([ { editType: CellEditType.Replace, index: range.end, count: 0, cells: cellRangesToIndexes([range]).map(index => cloneNotebookCellTextModel(editor.cellAt(index)!.model)) }], true, { kind: SelectionStateType.Index, focus: focus, selections: selections }, () => ({ kind: SelectionStateType.Index, focus: focus, selections: selections }), undefined, true ); } else { // insert down, move selections const focus = editor.getFocus(); const selections = editor.getSelections(); const newCells = cellRangesToIndexes([range]).map(index => cloneNotebookCellTextModel(editor.cellAt(index)!.model)); const countDelta = newCells.length; const newFocus = context.ui ? focus : { start: focus.start + countDelta, end: focus.end + countDelta }; const newSelections = context.ui ? selections : [{ start: range.start + countDelta, end: range.end + countDelta }]; textModel.applyEdits([ { editType: CellEditType.Replace, index: range.end, count: 0, cells: cellRangesToIndexes([range]).map(index => cloneNotebookCellTextModel(editor.cellAt(index)!.model)) }], true, { kind: SelectionStateType.Index, focus: focus, selections: selections }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: newSelections }), undefined, true ); const focusRange = editor.getSelections()[0] ?? editor.getFocus(); editor.revealCellRangeInView(focusRange); } } export async function joinNotebookCells(editor: IActiveNotebookEditor, range: ICellRange, direction: 'above' | 'below', constraint?: CellKind): Promise<{ edits: ResourceEdit[]; cell: ICellViewModel; endFocus: ICellRange; endSelections: ICellRange[] } | null> { if (editor.isReadOnly) { return null; } const textModel = editor.textModel; const cells = editor.getCellsInRange(range); if (!cells.length) { return null; } if (range.start === 0 && direction === 'above') { return null; } if (range.end === textModel.length && direction === 'below') { return null; } for (let i = 0; i < cells.length; i++) { const cell = cells[i]; if (constraint && cell.cellKind !== constraint) { return null; } } if (direction === 'above') { const above = editor.cellAt(range.start - 1) as CellViewModel; if (constraint && above.cellKind !== constraint) { return null; } const insertContent = cells.map(cell => (cell.textBuffer.getEOL() ?? '') + cell.getText()).join(''); const aboveCellLineCount = above.textBuffer.getLineCount(); const aboveCellLastLineEndColumn = above.textBuffer.getLineLength(aboveCellLineCount); return { edits: [ new ResourceTextEdit(above.uri, { range: new Range(aboveCellLineCount, aboveCellLastLineEndColumn + 1, aboveCellLineCount, aboveCellLastLineEndColumn + 1), text: insertContent }), new ResourceNotebookCellEdit(textModel.uri, { editType: CellEditType.Replace, index: range.start, count: range.end - range.start, cells: [] } ) ], cell: above, endFocus: { start: range.start - 1, end: range.start }, endSelections: [{ start: range.start - 1, end: range.start }] }; } else { const below = editor.cellAt(range.end) as CellViewModel; if (constraint && below.cellKind !== constraint) { return null; } const cell = cells[0]; const restCells = [...cells.slice(1), below]; const insertContent = restCells.map(cl => (cl.textBuffer.getEOL() ?? '') + cl.getText()).join(''); const cellLineCount = cell.textBuffer.getLineCount(); const cellLastLineEndColumn = cell.textBuffer.getLineLength(cellLineCount); return { edits: [ new ResourceTextEdit(cell.uri, { range: new Range(cellLineCount, cellLastLineEndColumn + 1, cellLineCount, cellLastLineEndColumn + 1), text: insertContent }), new ResourceNotebookCellEdit(textModel.uri, { editType: CellEditType.Replace, index: range.start + 1, count: range.end - range.start, cells: [] } ) ], cell, endFocus: { start: range.start, end: range.start + 1 }, endSelections: [{ start: range.start, end: range.start + 1 }] }; } } export async function joinCellsWithSurrounds(bulkEditService: IBulkEditService, context: INotebookCellActionContext, direction: 'above' | 'below'): Promise<void> { const editor = context.notebookEditor; const textModel = editor.textModel; const viewModel = editor._getViewModel() as NotebookViewModel; let ret: { edits: ResourceEdit[]; cell: ICellViewModel; endFocus: ICellRange; endSelections: ICellRange[]; } | null = null; if (context.ui) { const focusMode = context.cell.focusMode; const cellIndex = editor.getCellIndex(context.cell); ret = await joinNotebookCells(editor, { start: cellIndex, end: cellIndex + 1 }, direction); if (!ret) { return; } await bulkEditService.apply( ret?.edits, { quotableLabel: 'Join Notebook Cells' } ); viewModel.updateSelectionsState({ kind: SelectionStateType.Index, focus: ret.endFocus, selections: ret.endSelections }); ret.cell.updateEditState(CellEditState.Editing, 'joinCellsWithSurrounds'); editor.revealCellRangeInView(editor.getFocus()); if (focusMode === CellFocusMode.Editor) { ret.cell.focusMode = CellFocusMode.Editor; } } else { const selections = editor.getSelections(); if (!selections.length) { return; } const focus = editor.getFocus(); const focusMode = editor.cellAt(focus.start)?.focusMode; const edits: ResourceEdit[] = []; let cell: ICellViewModel | null = null; const cells: ICellViewModel[] = []; for (let i = selections.length - 1; i >= 0; i--) { const selection = selections[i]; const containFocus = cellRangeContains(selection, focus); if ( selection.end >= textModel.length && direction === 'below' || selection.start === 0 && direction === 'above' ) { if (containFocus) { cell = editor.cellAt(focus.start)!; } cells.push(...editor.getCellsInRange(selection)); continue; } const singleRet = await joinNotebookCells(editor, selection, direction); if (!singleRet) { return; } edits.push(...singleRet.edits); cells.push(singleRet.cell); if (containFocus) { cell = singleRet.cell; } } if (!edits.length) { return; } if (!cell || !cells.length) { return; } await bulkEditService.apply( edits, { quotableLabel: 'Join Notebook Cells' } ); cells.forEach(cell => { cell.updateEditState(CellEditState.Editing, 'joinCellsWithSurrounds'); }); viewModel.updateSelectionsState({ kind: SelectionStateType.Handle, primary: cell.handle, selections: cells.map(cell => cell.handle) }); editor.revealCellRangeInView(editor.getFocus()); const newFocusedCell = editor.cellAt(editor.getFocus().start); if (focusMode === CellFocusMode.Editor && newFocusedCell) { newFocusedCell.focusMode = CellFocusMode.Editor; } } } function _splitPointsToBoundaries(splitPoints: IPosition[], textBuffer: IReadonlyTextBuffer): IPosition[] | null { const boundaries: IPosition[] = []; const lineCnt = textBuffer.getLineCount(); const getLineLen = (lineNumber: number) => { return textBuffer.getLineLength(lineNumber); }; // split points need to be sorted splitPoints = splitPoints.sort((l, r) => { const lineDiff = l.lineNumber - r.lineNumber; const columnDiff = l.column - r.column; return lineDiff !== 0 ? lineDiff : columnDiff; }); for (let sp of splitPoints) { if (getLineLen(sp.lineNumber) + 1 === sp.column && sp.column !== 1 /** empty line */ && sp.lineNumber < lineCnt) { sp = new Position(sp.lineNumber + 1, 1); } _pushIfAbsent(boundaries, sp); } if (boundaries.length === 0) { return null; } // boundaries already sorted and not empty const modelStart = new Position(1, 1); const modelEnd = new Position(lineCnt, getLineLen(lineCnt) + 1); return [modelStart, ...boundaries, modelEnd]; } function _pushIfAbsent(positions: IPosition[], p: IPosition) { const last = positions.length > 0 ? positions[positions.length - 1] : undefined; if (!last || last.lineNumber !== p.lineNumber || last.column !== p.column) { positions.push(p); } } export function computeCellLinesContents(cell: ICellViewModel, splitPoints: IPosition[]): string[] | null { const rangeBoundaries = _splitPointsToBoundaries(splitPoints, cell.textBuffer); if (!rangeBoundaries) { return null; } const newLineModels: string[] = []; for (let i = 1; i < rangeBoundaries.length; i++) { const start = rangeBoundaries[i - 1]; const end = rangeBoundaries[i]; newLineModels.push(cell.textBuffer.getValueInRange(new Range(start.lineNumber, start.column, end.lineNumber, end.column), EndOfLinePreference.TextDefined)); } return newLineModels; } export function insertCell( languageService: ILanguageService, editor: IActiveNotebookEditor, index: number, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = '', ui: boolean = false ) { const viewModel = editor._getViewModel() as NotebookViewModel; const activeKernel = editor.activeKernel; if (viewModel.options.isReadOnly) { return null; } const cell = editor.cellAt(index); const nextIndex = ui ? viewModel.getNextVisibleCellIndex(index) : index + 1; let language; if (type === CellKind.Code) { const supportedLanguages = activeKernel?.supportedLanguages ?? languageService.getRegisteredLanguageIds(); const defaultLanguage = supportedLanguages[0] || PLAINTEXT_LANGUAGE_ID; if (cell?.cellKind === CellKind.Code) { language = cell.language; } else if (cell?.cellKind === CellKind.Markup) { const nearestCodeCellIndex = viewModel.nearestCodeCellIndex(index); if (nearestCodeCellIndex > -1) { language = viewModel.cellAt(nearestCodeCellIndex)!.language; } else { language = defaultLanguage; } } else { if (cell === undefined && direction === 'above') { // insert cell at the very top language = viewModel.viewCells.find(cell => cell.cellKind === CellKind.Code)?.language || defaultLanguage; } else { language = defaultLanguage; } } if (!supportedLanguages.includes(language)) { // the language no longer exists language = defaultLanguage; } } else { language = 'markdown'; } const insertIndex = cell ? (direction === 'above' ? index : nextIndex) : index; return insertCellAtIndex(viewModel, insertIndex, initialText, language, type, undefined, [], true, true); } export function insertCellAtIndex(viewModel: NotebookViewModel, index: number, source: string, language: string, type: CellKind, metadata: NotebookCellMetadata | undefined, outputs: IOutputDto[], synchronous: boolean, pushUndoStop: boolean): CellViewModel { const endSelections: ISelectionState = { kind: SelectionStateType.Index, focus: { start: index, end: index + 1 }, selections: [{ start: index, end: index + 1 }] }; viewModel.notebookDocument.applyEdits([ { editType: CellEditType.Replace, index, count: 0, cells: [ { cellKind: type, language: language, mime: undefined, outputs: outputs, metadata: metadata, source: source } ] } ], synchronous, { kind: SelectionStateType.Index, focus: viewModel.getFocus(), selections: viewModel.getSelections() }, () => endSelections, undefined, pushUndoStop); return viewModel.cellAt(index)!; }
the_stack
import { BasePluginEvent, PLUGIN_SDK_EK_UI_ALIAS, PLUGIN_SDK_NS_UI_API, PLUGIN_SDK_EK_DRAG_AND_DROPPED, PLUGIN_SDK_EK_REQUEST_FETCH_NODE_MAIN_COMPONENT_LAYER_META, PLUGIN_SDK_EK_REQUEST_FETCH_NODE_MAIN_COMPONENT_META, PLUGIN_SDK_EK_REQUEST_FETCH_NODE_META, PLUGIN_SDK_EK_REQUEST_FETCH_ROOT_META, PLUGIN_SDK_EK_SIMPLE_NOTIFY, PLUGIN_SDK_NS_APP_REQUEST_CUSTOM_ALL, PLUGIN_SDK_NS_DRAG_AND_DROP, PLUGIN_SDK_NS_META_API, PLUGIN_SDK_NS_NOTIFY_API, PUGIN_SDK_EK_REQUEST_UPDATE_MAIN_COMPONENT_META, PUGIN_SDK_EK_REQUEST_UPDATE_NODE_META, PLUGIN_SDK_NS_STORAGE, PLUGIN_SDK_EK_STORAGE_ALIAS, TransportPluginEvent, reqid, BatchMetaFetchRequest, NodeMetaFetchRequest, NodeMetaUpdateRequest, StorageSetItemRequest, StorageGetItemRequest, StorageGetItemResponse, NotifyRequest, DragAndDropOnCanvasRequest, PLUGIN_SDK_NS_FOCUS_API, PLUGIN_SDK_EK_SIMPLE_FOCUS, FocusRequest, PLUGIN_SDK_NS_BROWSER_API, PLUGIN_SDK_EK_BROWSER_OPEN_URI, PLUGIN_SDK_NS_EXPORT_AS_IMAGE, PLUGIN_SDK_EK_REQUEST_EXPORT_AS_IMAGE, ImageExportRequest, ImageExportResponse, target_platform, TargetPlatform, UIControlRequest, } from "@plugin-sdk/core"; import type { ReflectSceneNode } from "@design-sdk/figma-node"; import { ASSISTANT_PLUGIN_NAMESPACE__NOCHANGE } from "@core/constant"; import { _SharedStorageCache } from "./_shared-storage-cache"; import { NodeApi } from "./node-api"; const __main_plugin_sdk_instance_storage_cache = new _SharedStorageCache( "co.grida.assistant" ); export class PluginSdk { private static _window: Window; static get window(): Window { return this._window; } static initializeWindow(window: Window) { this._window = window; } static resizeHost(size: { width: number; height: number }) { // figma.ui.resize() this.request({ namespace: PLUGIN_SDK_NS_UI_API, key: PLUGIN_SDK_EK_UI_ALIAS.resize, data: <UIControlRequest>{ type: "resize", size, }, }); } /** * this only sets TARGET_PLATFORM on ui thread. * @param platform */ static async initializeTargetPlatform(platform: TargetPlatform) { if (!!target_platform.get()) { throw "cannot overwrite target platform on runtime."; } target_platform.set(platform); if (platform == TargetPlatform.webdev) { return true; } // sync this to code side. await PluginSdk.request({ namespace: "__INTERNAL__", key: "sync-target-platform", data: platform, }); // console.info(`thread#ui: target platform set as ${platform}`); } // region general canvas api static get selectedNodeIds(): readonly string[] { throw "not implemented"; return []; } static get selectedNodes(): readonly ReflectSceneNode[] { throw "not implemented"; return []; } static get selectedNodeId(): string { // TODO throw "not implemented"; return undefined; } static get selectedNode(): ReflectSceneNode { // TODO throw "not implemented"; return undefined; } static async getNode(id: string) { return new NodeApi(id).get(); } static node(id: string): NodeApi { return new NodeApi(id); } static async getNodeImage( req: ImageExportRequest ): Promise<ImageExportResponse> { return await this.request<ImageExportResponse>({ namespace: PLUGIN_SDK_NS_EXPORT_AS_IMAGE, key: PLUGIN_SDK_EK_REQUEST_EXPORT_AS_IMAGE, data: req, }); } // enderegion general canvas api // region network api static get(params: any) { throw "not implmtd"; } static post(params: any) { throw "not implmtd"; } // endregion network api // // region storage api static setItem<T = string>(key: string, value: T) { __main_plugin_sdk_instance_storage_cache.setCache( key, value ); /* 1. set cache */ /* 2. send set request */ this.request({ namespace: PLUGIN_SDK_NS_STORAGE, key: PLUGIN_SDK_EK_STORAGE_ALIAS.set, data: <StorageSetItemRequest<T>>{ type: "set-item", key: key, value: value, }, }).finally(() => { __main_plugin_sdk_instance_storage_cache.removeCache( key ); /* 3. remove cache after saving complete */ }); } static async getItem<T = string>(key: string): Promise<T> { const _has_cached = __main_plugin_sdk_instance_storage_cache.hasCache(key); if (_has_cached) { return __main_plugin_sdk_instance_storage_cache.getCache<T>(key); } else { const _resp = await this.request<StorageGetItemResponse<T>>({ namespace: PLUGIN_SDK_NS_STORAGE, key: PLUGIN_SDK_EK_STORAGE_ALIAS.get, data: <StorageGetItemRequest<T>>{ type: "get-item", key: key, }, }); return _resp.value; } } // endregion storage api // // // region metadata static updateMetadata(request: NodeMetaUpdateRequest) { return this.request({ namespace: PLUGIN_SDK_NS_META_API, key: PUGIN_SDK_EK_REQUEST_UPDATE_NODE_META, data: request, }); } /** * fetches the metadata with grida default namespace provided. */ static async fetchMetadata_grida<T = any>( on: string, key: string ): Promise<T> { return this.fetchMetadata<T>({ type: "node-meta-fetch-request", id: on, key: key, namespace: ASSISTANT_PLUGIN_NAMESPACE__NOCHANGE, }); } static async fetchMetadata<T = any>( request: NodeMetaFetchRequest ): Promise<T> { return this.request<T>({ namespace: PLUGIN_SDK_NS_META_API, key: PLUGIN_SDK_EK_REQUEST_FETCH_NODE_META, data: request, }); } /** * fetches the master component metadata no matter the input id (node id) was id of master component or a instance. * when instance id was givven it will automatically locate master component to set the metadata * @param request * @returns * @deprecated - use plain meta update instead. */ static async fetchMainComponentMetadata(request: NodeMetaFetchRequest) { return this.request({ namespace: PLUGIN_SDK_NS_META_API, key: PLUGIN_SDK_EK_REQUEST_FETCH_NODE_MAIN_COMPONENT_META, data: request, }); } /** * fetches the master component's layer corresponding to givven id. works similar like "fetchMainComponentMetadata" * @deprecated - use plain meta update instead. */ static async fetchMainComponentLayerMetadata(request: NodeMetaFetchRequest) { throw "not implemented on handler side"; return this.request({ namespace: PLUGIN_SDK_NS_META_API, key: PLUGIN_SDK_EK_REQUEST_FETCH_NODE_MAIN_COMPONENT_LAYER_META, data: request, }); } /** * updates the main component's meta data. * (this also works for a variant compat component, * but it does't save on variant set's meta, * intead saves on master component of single variant. * - so you'll need to prevent using this on some case to prevent future confusion) * @param request * @returns * @deprecated - use plain meta update instead. */ static async updateMainComponentMetadata(request: NodeMetaUpdateRequest) { return this.request({ namespace: PLUGIN_SDK_NS_META_API, key: PUGIN_SDK_EK_REQUEST_UPDATE_MAIN_COMPONENT_META, data: request, }); } static fetchRootMetadata(key: string): Promise<any> { const data: BatchMetaFetchRequest = { type: "batch-meta-fetch-request", key: key, }; return this.request({ namespace: PLUGIN_SDK_NS_META_API, key: PLUGIN_SDK_EK_REQUEST_FETCH_ROOT_META, data: data, }); } // endregion metadata /** * inner iframe blocked js functions * this is designed to be used inside iframe that has no popup permission, so that calling open() in inner iframe won't work. * But we can simply allow popups for inner iframe, so we don't have to use this function. * this function does not check if this is being called inside a popup-blocked iframe. * * @deprecated use allow-popup & open instead. **/ static openUri(uri: string) { if (process.env.HOSTED ?? process.env.NEXT_PUBLIC_HOSTED) { this.request({ namespace: PLUGIN_SDK_NS_BROWSER_API, key: PLUGIN_SDK_EK_BROWSER_OPEN_URI, data: { uri: uri, }, }); } else { open(uri); } } // region user feedbacks static notify(message: string, duration?: number) { this.request({ namespace: PLUGIN_SDK_NS_NOTIFY_API, key: PLUGIN_SDK_EK_SIMPLE_NOTIFY, data: <NotifyRequest>{ message: message, duration: duration, }, }); } static notifyCopied() { this.notify("Copied to clipboard", 1); } static focus(target: string, zoom?: number) { this.request({ namespace: PLUGIN_SDK_NS_FOCUS_API, key: PLUGIN_SDK_EK_SIMPLE_FOCUS, data: <FocusRequest>{ target: target, zoom: zoom, }, }); } // endregion user feedbacks // region canvas static async dropOnCanvas(data: DragAndDropOnCanvasRequest) { return await this.request({ namespace: PLUGIN_SDK_NS_DRAG_AND_DROP, key: PLUGIN_SDK_EK_DRAG_AND_DROPPED, data: data, }); } // endregion canvas static postMessage(event: TransportPluginEvent) { // console.log("::plugin-sdk post message", event); PluginSdk.window.postMessage( { pluginMessage: event, }, "*" ); } static promises: Map<string, { resolve; reject }> = new Map(); static request<T = any>(event: BasePluginEvent): Promise<T> { // make id const requestId = this.makeRequetsId(event.key); return new Promise<T>((resolve, reject) => { // register to event / response que this.registerToEventQue(requestId, resolve, reject); // post message after registration is complete. this.postMessage({ type: "request", origin: "app", ...event, id: requestId, }); }); } private static makeRequetsId(key: string): string { return `${key}-${reqid()}`; } private static registerToEventQue(requestId: string, resolve, reject) { this.promises.set(requestId, { resolve: resolve, reject: reject, }); } private static removeFromEventQue(requestId: string) { this.promises.delete(requestId); } static handle(event: TransportPluginEvent) { if (event.type == "response") { this.handleResponse(event); } } private static handleResponse(event: TransportPluginEvent) { const promise = this.promises.get(event.id); if (!promise) { throw `no promise found to handle from event que with id ${ event.id } current promises are.. ${[...this.promises.keys()]}`; } if (event.error) { promise.reject(event.error); } else { promise.resolve(event.data); } // remove resolved promise from que this.removeFromEventQue(event.id); } /** * raises custom app event/request * see PluginSdkService#onAppRequest for more detail */ static appEvent(key: string, data: any) { this.request({ namespace: PLUGIN_SDK_NS_APP_REQUEST_CUSTOM_ALL, key: key, data: data, }); } }
the_stack
import InteropService from '../../services/interop/InteropService'; import { CustomExportContext, CustomImportContext, Module, ModuleType } from '../../services/interop/types'; import shim from '../../shim'; import { fileContentEqual, setupDatabaseAndSynchronizer, switchClient, checkThrowAsync, exportDir, supportDir } from '../../testing/test-utils'; import Folder from '../../models/Folder'; import Note from '../../models/Note'; import Tag from '../../models/Tag'; import Resource from '../../models/Resource'; import * as fs from 'fs-extra'; import { NoteEntity, ResourceEntity } from '../database/types'; import { ModelType } from '../../BaseModel'; const ArrayUtils = require('../../ArrayUtils'); async function recreateExportDir() { const dir = exportDir(); await fs.remove(dir); await fs.mkdirp(dir); } function fieldsEqual(model1: any, model2: any, fieldNames: string[]) { for (let i = 0; i < fieldNames.length; i++) { const f = fieldNames[i]; expect(model1[f]).toBe(model2[f]); } } function memoryExportModule() { interface Item { type: number; object: any; } interface Resource { filePath: string; object: ResourceEntity; } interface Result { destPath: string; items: Item[]; resources: Resource[]; } const result: Result = { destPath: '', items: [], resources: [], }; const module: Module = { type: ModuleType.Exporter, description: 'Memory Export Module', format: 'memory', fileExtensions: ['memory'], isCustom: true, onInit: async (context: CustomExportContext) => { result.destPath = context.destPath; }, onProcessItem: async (_context: CustomExportContext, itemType: number, item: any) => { result.items.push({ type: itemType, object: item, }); }, onProcessResource: async (_context: CustomExportContext, resource: any, filePath: string) => { result.resources.push({ filePath: filePath, object: resource, }); }, onClose: async (_context: CustomExportContext) => { // nothing }, }; return { result, module }; } describe('services_InteropService', function() { beforeEach(async (done) => { await setupDatabaseAndSynchronizer(1); await switchClient(1); await recreateExportDir(); done(); }); it('should export and import folders', (async () => { const service = InteropService.instance(); let folder1 = await Folder.save({ title: 'folder1' }); folder1 = await Folder.load(folder1.id); const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); await Folder.delete(folder1.id); await service.import({ path: filePath }); // Check that a new folder, with a new ID, has been created expect(await Folder.count()).toBe(1); const folder2 = (await Folder.all())[0]; expect(folder2.id).not.toBe(folder1.id); expect(folder2.title).toBe(folder1.title); await service.import({ path: filePath }); // As there was already a folder with the same title, check that the new one has been renamed await Folder.delete(folder2.id); const folder3 = (await Folder.all())[0]; expect(await Folder.count()).toBe(1); expect(folder3.title).not.toBe(folder2.title); let fieldNames = Folder.fieldNames(); fieldNames = ArrayUtils.removeElement(fieldNames, 'id'); fieldNames = ArrayUtils.removeElement(fieldNames, 'title'); fieldsEqual(folder3, folder1, fieldNames); })); it('should import folders and de-duplicate titles when needed', (async () => { const service = InteropService.instance(); const folder1 = await Folder.save({ title: 'folder' }); const folder2 = await Folder.save({ title: 'folder' }); const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); await Folder.delete(folder1.id); await Folder.delete(folder2.id); await service.import({ path: filePath }); const allFolders = await Folder.all(); expect(allFolders.map((f: any) => f.title).sort().join(' - ')).toBe('folder - folder (1)'); })); it('should import folders, and only de-duplicate titles when needed', (async () => { const service = InteropService.instance(); const folder1 = await Folder.save({ title: 'folder1' }); const folder2 = await Folder.save({ title: 'folder2' }); await Folder.save({ title: 'Sub', parent_id: folder1.id }); await Folder.save({ title: 'Sub', parent_id: folder2.id }); const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); await Folder.delete(folder1.id); await Folder.delete(folder2.id); await service.import({ path: filePath }); const importedFolder1 = await Folder.loadByTitle('folder1'); const importedFolder2 = await Folder.loadByTitle('folder2'); const importedSub1 = await Folder.load((await Folder.childrenIds(importedFolder1.id))[0]); const importedSub2 = await Folder.load((await Folder.childrenIds(importedFolder2.id))[0]); expect(importedSub1.title).toBe('Sub'); expect(importedSub2.title).toBe('Sub'); })); it('should export and import folders and notes', (async () => { const service = InteropService.instance(); const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); note1 = await Note.load(note1.id); const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); await Folder.delete(folder1.id); await Note.delete(note1.id); await service.import({ path: filePath }); expect(await Note.count()).toBe(1); let note2 = (await Note.all())[0]; const folder2 = (await Folder.all())[0]; expect(note1.parent_id).not.toBe(note2.parent_id); expect(note1.id).not.toBe(note2.id); expect(note2.parent_id).toBe(folder2.id); let fieldNames = Note.fieldNames(); fieldNames = ArrayUtils.removeElement(fieldNames, 'id'); fieldNames = ArrayUtils.removeElement(fieldNames, 'parent_id'); fieldsEqual(note1, note2, fieldNames); await service.import({ path: filePath }); note2 = (await Note.all())[0]; const note3 = (await Note.all())[1]; expect(note2.id).not.toBe(note3.id); expect(note2.parent_id).not.toBe(note3.parent_id); fieldsEqual(note2, note3, fieldNames); })); it('should export and import notes to specific folder', (async () => { const service = InteropService.instance(); const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); note1 = await Note.load(note1.id); const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); await Note.delete(note1.id); await service.import({ path: filePath, destinationFolderId: folder1.id }); expect(await Note.count()).toBe(1); expect(await Folder.count()).toBe(1); expect(await checkThrowAsync(async () => await service.import({ path: filePath, destinationFolderId: 'oops' }))).toBe(true); })); it('should export and import tags', (async () => { const service = InteropService.instance(); const filePath = `${exportDir()}/test.jex`; const folder1 = await Folder.save({ title: 'folder1' }); const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); let tag1 = await Tag.save({ title: 'mon tag' }); tag1 = await Tag.load(tag1.id); await Tag.addNote(tag1.id, note1.id); await service.export({ path: filePath }); await Folder.delete(folder1.id); await Note.delete(note1.id); await Tag.delete(tag1.id); await service.import({ path: filePath }); expect(await Tag.count()).toBe(1); const tag2 = (await Tag.all())[0]; const note2 = (await Note.all())[0]; expect(tag1.id).not.toBe(tag2.id); let fieldNames = Note.fieldNames(); fieldNames = ArrayUtils.removeElement(fieldNames, 'id'); fieldsEqual(tag1, tag2, fieldNames); let noteIds = await Tag.noteIds(tag2.id); expect(noteIds.length).toBe(1); expect(noteIds[0]).toBe(note2.id); await service.import({ path: filePath }); // If importing again, no new tag should be created as one with // the same name already existed. The newly imported note should // however go under that already existing tag. expect(await Tag.count()).toBe(1); noteIds = await Tag.noteIds(tag2.id); expect(noteIds.length).toBe(2); })); it('should export and import resources', (async () => { const service = InteropService.instance(); const filePath = `${exportDir()}/test.jex`; const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${supportDir}/photo.jpg`); note1 = await Note.load(note1.id); let resourceIds = await Note.linkedResourceIds(note1.body); const resource1 = await Resource.load(resourceIds[0]); await service.export({ path: filePath }); await Note.delete(note1.id); await service.import({ path: filePath }); expect(await Resource.count()).toBe(2); const note2 = (await Note.all())[0]; expect(note2.body).not.toBe(note1.body); resourceIds = await Note.linkedResourceIds(note2.body); expect(resourceIds.length).toBe(1); const resource2 = await Resource.load(resourceIds[0]); expect(resource2.id).not.toBe(resource1.id); let fieldNames = Note.fieldNames(); fieldNames = ArrayUtils.removeElement(fieldNames, 'id'); fieldsEqual(resource1, resource2, fieldNames); const resourcePath1 = Resource.fullPath(resource1); const resourcePath2 = Resource.fullPath(resource2); expect(resourcePath1).not.toBe(resourcePath2); expect(fileContentEqual(resourcePath1, resourcePath2)).toBe(true); })); it('should export and import single notes', (async () => { const service = InteropService.instance(); const filePath = `${exportDir()}/test.jex`; const folder1 = await Folder.save({ title: 'folder1' }); const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await service.export({ path: filePath, sourceNoteIds: [note1.id] }); await Note.delete(note1.id); await Folder.delete(folder1.id); await service.import({ path: filePath }); expect(await Note.count()).toBe(1); expect(await Folder.count()).toBe(1); const folder2 = (await Folder.all())[0]; expect(folder2.title).toBe('test'); })); it('should export and import single folders', (async () => { const service = InteropService.instance(); const filePath = `${exportDir()}/test.jex`; const folder1 = await Folder.save({ title: 'folder1' }); const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await service.export({ path: filePath, sourceFolderIds: [folder1.id] }); await Note.delete(note1.id); await Folder.delete(folder1.id); await service.import({ path: filePath }); expect(await Note.count()).toBe(1); expect(await Folder.count()).toBe(1); const folder2 = (await Folder.all())[0]; expect(folder2.title).toBe('folder1'); })); it('should export and import folder and its sub-folders', (async () => { const service = InteropService.instance(); const filePath = `${exportDir()}/test.jex`; const folder1 = await Folder.save({ title: 'folder1' }); const folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); const folder3 = await Folder.save({ title: 'folder3', parent_id: folder2.id }); const folder4 = await Folder.save({ title: 'folder4', parent_id: folder2.id }); const note1 = await Note.save({ title: 'ma note', parent_id: folder4.id }); await service.export({ path: filePath, sourceFolderIds: [folder1.id] }); await Note.delete(note1.id); await Folder.delete(folder1.id); await Folder.delete(folder2.id); await Folder.delete(folder3.id); await Folder.delete(folder4.id); await service.import({ path: filePath }); expect(await Note.count()).toBe(1); expect(await Folder.count()).toBe(4); const folder1_2 = await Folder.loadByTitle('folder1'); const folder2_2 = await Folder.loadByTitle('folder2'); const folder3_2 = await Folder.loadByTitle('folder3'); const folder4_2 = await Folder.loadByTitle('folder4'); const note1_2 = await Note.loadByTitle('ma note'); expect(folder2_2.parent_id).toBe(folder1_2.id); expect(folder3_2.parent_id).toBe(folder2_2.id); expect(folder4_2.parent_id).toBe(folder2_2.id); expect(note1_2.parent_id).toBe(folder4_2.id); })); it('should export and import links to notes', (async () => { const service = InteropService.instance(); const filePath = `${exportDir()}/test.jex`; const folder1 = await Folder.save({ title: 'folder1' }); const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); const note2 = await Note.save({ title: 'ma deuxième note', body: `Lien vers première note : ${Note.markdownTag(note1)}`, parent_id: folder1.id }); await service.export({ path: filePath, sourceFolderIds: [folder1.id] }); await Note.delete(note1.id); await Note.delete(note2.id); await Folder.delete(folder1.id); await service.import({ path: filePath }); expect(await Note.count()).toBe(2); expect(await Folder.count()).toBe(1); const note1_2 = await Note.loadByTitle('ma note'); const note2_2 = await Note.loadByTitle('ma deuxième note'); expect(note2_2.body.indexOf(note1_2.id) >= 0).toBe(true); })); it('should export selected notes in md format', (async () => { const service = InteropService.instance(); const folder1 = await Folder.save({ title: 'folder1' }); let note11 = await Note.save({ title: 'title note11', parent_id: folder1.id }); note11 = await Note.load(note11.id); const note12 = await Note.save({ title: 'title note12', parent_id: folder1.id }); await Note.load(note12.id); let folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); folder2 = await Folder.load(folder2.id); let note21 = await Note.save({ title: 'title note21', parent_id: folder2.id }); note21 = await Note.load(note21.id); await Folder.save({ title: 'folder3', parent_id: folder1.id }); await Folder.load(folder2.id); const outDir = exportDir(); await service.export({ path: outDir, format: 'md', sourceNoteIds: [note11.id, note21.id] }); // verify that the md files exist expect(await shim.fsDriver().exists(`${outDir}/folder1`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/title note11.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/title note12.md`)).toBe(false); expect(await shim.fsDriver().exists(`${outDir}/folder1/folder2`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/folder2/title note21.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder3`)).toBe(false); })); it('should export MD with unicode filenames', (async () => { const service = InteropService.instance(); const folder1 = await Folder.save({ title: 'folder1' }); const folder2 = await Folder.save({ title: 'ジョプリン' }); await Note.save({ title: '生活', parent_id: folder1.id }); await Note.save({ title: '生活', parent_id: folder1.id }); await Note.save({ title: '生活', parent_id: folder1.id }); await Note.save({ title: '', parent_id: folder1.id }); await Note.save({ title: '', parent_id: folder1.id }); await Note.save({ title: 'salut, ça roule ?', parent_id: folder1.id }); await Note.save({ title: 'ジョプリン', parent_id: folder2.id }); const outDir = exportDir(); await service.export({ path: outDir, format: 'md' }); expect(await shim.fsDriver().exists(`${outDir}/folder1/生活.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/生活-1.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/生活-2.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/Untitled.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/Untitled-1.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/folder1/salut, ça roule _.md`)).toBe(true); expect(await shim.fsDriver().exists(`${outDir}/ジョプリン/ジョプリン.md`)).toBe(true); })); it('should export a notebook as MD', (async () => { const folder1 = await Folder.save({ title: 'testexportfolder' }); await Note.save({ title: 'textexportnote1', parent_id: folder1.id }); await Note.save({ title: 'textexportnote2', parent_id: folder1.id }); const service = InteropService.instance(); await service.export({ path: exportDir(), format: 'md', sourceFolderIds: [folder1.id], }); expect(await shim.fsDriver().exists(`${exportDir()}/testexportfolder/textexportnote1.md`)).toBe(true); expect(await shim.fsDriver().exists(`${exportDir()}/testexportfolder/textexportnote2.md`)).toBe(true); })); it('should export conflict notes', (async () => { const folder1 = await Folder.save({ title: 'testexportfolder' }); await Note.save({ title: 'textexportnote1', parent_id: folder1.id, is_conflict: 1 }); await Note.save({ title: 'textexportnote2', parent_id: folder1.id }); const service = InteropService.instance(); await service.export({ path: exportDir(), format: 'md', sourceFolderIds: [folder1.id], includeConflicts: false, }); expect(await shim.fsDriver().exists(`${exportDir()}/testexportfolder/textexportnote1.md`)).toBe(false); expect(await shim.fsDriver().exists(`${exportDir()}/testexportfolder/textexportnote2.md`)).toBe(true); await recreateExportDir(); await service.export({ path: exportDir(), format: 'md', sourceFolderIds: [folder1.id], includeConflicts: true, }); expect(await shim.fsDriver().exists(`${exportDir()}/testexportfolder/textexportnote1.md`)).toBe(true); expect(await shim.fsDriver().exists(`${exportDir()}/testexportfolder/textexportnote2.md`)).toBe(true); })); it('should not try to export folders with a non-existing parent', (async () => { // Handles and edge case where user has a folder but this folder with a parent // that doesn't exist. Can happen for example in this case: // // - folder1/folder2 // - Client 1 sync folder2, but not folder1 // - Client 2 sync and get folder2 only // - Client 2 export data // => Crash if we don't handle this case await Folder.save({ title: 'orphan', parent_id: '0c5bbd8a1b5a48189484a412a7e534cc' }); const service = InteropService.instance(); const result = await service.export({ path: exportDir(), format: 'md', }); expect(result.warnings.length).toBe(0); })); it('should not export certain note properties', (async () => { const folder = await Folder.save({ title: 'folder' }); await Note.save({ title: 'note', is_shared: 1, share_id: 'someid', parent_id: folder.id }); const service = InteropService.instance(); const { result, module } = memoryExportModule(); service.registerModule(module); await service.export({ format: 'memory', }); const exportedNote = (result.items.find(i => i.type === ModelType.Note)).object as NoteEntity; expect(exportedNote.share_id).toBe(''); expect(exportedNote.is_shared).toBe(0); })); it('should allow registering new import modules', (async () => { const testImportFilePath = `${exportDir()}/testImport${Math.random()}.test`; await shim.fsDriver().writeFile(testImportFilePath, 'test', 'utf8'); const result = { hasBeenExecuted: false, sourcePath: '', }; const module: Module = { type: ModuleType.Importer, description: 'Test Import Module', format: 'testing', fileExtensions: ['test'], isCustom: true, onExec: async (context: CustomImportContext) => { result.hasBeenExecuted = true; result.sourcePath = context.sourcePath; }, }; const service = InteropService.instance(); service.registerModule(module); await service.import({ format: 'testing', path: testImportFilePath, }); expect(result.hasBeenExecuted).toBe(true); expect(result.sourcePath).toBe(testImportFilePath); })); it('should allow registering new export modules', (async () => { const folder1 = await Folder.save({ title: 'folder1' }); const note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); await Note.save({ title: 'note2', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${supportDir}/photo.jpg`); const filePath = `${exportDir()}/example.test`; const result: any = { destPath: '', itemTypes: [], items: [], resources: [], filePaths: [], closeCalled: false, }; const module: Module = { type: ModuleType.Exporter, description: 'Test Export Module', format: 'testing', fileExtensions: ['test'], isCustom: true, onInit: async (context: CustomExportContext) => { result.destPath = context.destPath; }, onProcessItem: async (_context: CustomExportContext, itemType: number, item: any) => { result.itemTypes.push(itemType); result.items.push(item); }, onProcessResource: async (_context: CustomExportContext, resource: any, filePath: string) => { result.resources.push(resource); result.filePaths.push(filePath); }, onClose: async (_context: CustomExportContext) => { result.closeCalled = true; }, }; const service = InteropService.instance(); service.registerModule(module); await service.export({ format: 'testing', path: filePath, }); expect(result.destPath).toBe(filePath); expect(result.itemTypes.sort().join('_')).toBe('1_1_2_4'); expect(result.items.length).toBe(4); expect(result.items.map((o: any) => o.title).sort().join('_')).toBe('folder1_note1_note2_photo.jpg'); expect(result.resources.length).toBe(1); expect(result.resources[0].title).toBe('photo.jpg'); expect(result.filePaths.length).toBe(1); expect(!!result.filePaths[0]).toBe(true); expect(result.closeCalled).toBe(true); })); });
the_stack
import * as crypto from 'crypto'; import { AccountRootPrincipal, Grant, IGrantable } from '@aws-cdk/aws-iam'; import { IKey, ViaServicePrincipal } from '@aws-cdk/aws-kms'; import { IResource, Resource, Size, SizeRoundingBehavior, Stack, Token, Tags, Names, RemovalPolicy } from '@aws-cdk/core'; import { Construct } from 'constructs'; import { CfnVolume } from './ec2.generated'; import { IInstance } from './instance'; // v2 - keep this import as a separate section to reduce merge conflict when forward merging with the v2 branch. // eslint-disable-next-line import { Construct as CoreConstruct } from '@aws-cdk/core'; /** * Block device */ export interface BlockDevice { /** * The device name exposed to the EC2 instance * * For example, a value like `/dev/sdh`, `xvdh`. * * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html */ readonly deviceName: string; /** * Defines the block device volume, to be either an Amazon EBS volume or an ephemeral instance store volume * * For example, a value like `BlockDeviceVolume.ebs(15)`, `BlockDeviceVolume.ephemeral(0)`. */ readonly volume: BlockDeviceVolume; /** * If false, the device mapping will be suppressed. * If set to false for the root device, the instance might fail the Amazon EC2 health check. * Amazon EC2 Auto Scaling launches a replacement instance if the instance fails the health check. * * @default true - device mapping is left untouched */ readonly mappingEnabled?: boolean; } /** * Base block device options for an EBS volume */ export interface EbsDeviceOptionsBase { /** * Indicates whether to delete the volume when the instance is terminated. * * @default - true for Amazon EC2 Auto Scaling, false otherwise (e.g. EBS) */ readonly deleteOnTermination?: boolean; /** * The number of I/O operations per second (IOPS) to provision for the volume. * * Must only be set for {@link volumeType}: {@link EbsDeviceVolumeType.IO1} * * The maximum ratio of IOPS to volume size (in GiB) is 50:1, so for 5,000 provisioned IOPS, * you need at least 100 GiB storage on the volume. * * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html * * @default - none, required for {@link EbsDeviceVolumeType.IO1} */ readonly iops?: number; /** * The EBS volume type * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html * * @default {@link EbsDeviceVolumeType.GP2} */ readonly volumeType?: EbsDeviceVolumeType; } /** * Block device options for an EBS volume */ export interface EbsDeviceOptions extends EbsDeviceOptionsBase { /** * Specifies whether the EBS volume is encrypted. * Encrypted EBS volumes can only be attached to instances that support Amazon EBS encryption * * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances * * @default false */ readonly encrypted?: boolean; } /** * Block device options for an EBS volume created from a snapshot */ export interface EbsDeviceSnapshotOptions extends EbsDeviceOptionsBase { /** * The volume size, in Gibibytes (GiB) * * If you specify volumeSize, it must be equal or greater than the size of the snapshot. * * @default - The snapshot size */ readonly volumeSize?: number; } /** * Properties of an EBS block device */ export interface EbsDeviceProps extends EbsDeviceSnapshotOptions { /** * The snapshot ID of the volume to use * * @default - No snapshot will be used */ readonly snapshotId?: string; } /** * Describes a block device mapping for an EC2 instance or Auto Scaling group. */ export class BlockDeviceVolume { /** * Creates a new Elastic Block Storage device * * @param volumeSize The volume size, in Gibibytes (GiB) * @param options additional device options */ public static ebs(volumeSize: number, options: EbsDeviceOptions = {}): BlockDeviceVolume { return new this({ ...options, volumeSize }); } /** * Creates a new Elastic Block Storage device from an existing snapshot * * @param snapshotId The snapshot ID of the volume to use * @param options additional device options */ public static ebsFromSnapshot(snapshotId: string, options: EbsDeviceSnapshotOptions = {}): BlockDeviceVolume { return new this({ ...options, snapshotId }); } /** * Creates a virtual, ephemeral device. * The name will be in the form ephemeral{volumeIndex}. * * @param volumeIndex the volume index. Must be equal or greater than 0 */ public static ephemeral(volumeIndex: number) { if (volumeIndex < 0) { throw new Error(`volumeIndex must be a number starting from 0, got "${volumeIndex}"`); } return new this(undefined, `ephemeral${volumeIndex}`); } /** * @param ebsDevice EBS device info * @param virtualName Virtual device name */ protected constructor(public readonly ebsDevice?: EbsDeviceProps, public readonly virtualName?: string) { } } /** * Supported EBS volume types for blockDevices */ export enum EbsDeviceVolumeType { /** * Magnetic */ STANDARD = 'standard', /** * Provisioned IOPS SSD - IO1 */ IO1 = 'io1', /** * Provisioned IOPS SSD - IO2 */ IO2 = 'io2', /** * General Purpose SSD - GP2 */ GP2 = 'gp2', /** * General Purpose SSD - GP3 */ GP3 = 'gp3', /** * Throughput Optimized HDD */ ST1 = 'st1', /** * Cold HDD */ SC1 = 'sc1', /** * General purpose SSD volume (GP2) that balances price and performance for a wide variety of workloads. */ GENERAL_PURPOSE_SSD = GP2, /** * General purpose SSD volume (GP3) that balances price and performance for a wide variety of workloads. */ GENERAL_PURPOSE_SSD_GP3 = GP3, /** * Highest-performance SSD volume (IO1) for mission-critical low-latency or high-throughput workloads. */ PROVISIONED_IOPS_SSD = IO1, /** * Highest-performance SSD volume (IO2) for mission-critical low-latency or high-throughput workloads. */ PROVISIONED_IOPS_SSD_IO2 = IO2, /** * Low-cost HDD volume designed for frequently accessed, throughput-intensive workloads. */ THROUGHPUT_OPTIMIZED_HDD = ST1, /** * Lowest cost HDD volume designed for less frequently accessed workloads. */ COLD_HDD = SC1, /** * Magnetic volumes are backed by magnetic drives and are suited for workloads where data is accessed infrequently, and scenarios where low-cost * storage for small volume sizes is important. */ MAGNETIC = STANDARD, } /** * An EBS Volume in AWS EC2. */ export interface IVolume extends IResource { /** * The EBS Volume's ID * * @attribute */ readonly volumeId: string; /** * The availability zone that the EBS Volume is contained within (ex: us-west-2a) */ readonly availabilityZone: string; /** * The customer-managed encryption key that is used to encrypt the Volume. * * @attribute */ readonly encryptionKey?: IKey; /** * Grants permission to attach this Volume to an instance. * CAUTION: Granting an instance permission to attach to itself using this method will lead to * an unresolvable circular reference between the instance role and the instance. * Use {@link IVolume.grantAttachVolumeToSelf} to grant an instance permission to attach this * volume to itself. * * @param grantee the principal being granted permission. * @param instances the instances to which permission is being granted to attach this * volume to. If not specified, then permission is granted to attach * to all instances in this account. */ grantAttachVolume(grantee: IGrantable, instances?: IInstance[]): Grant; /** * Grants permission to attach the Volume by a ResourceTag condition. If you are looking to * grant an Instance, AutoScalingGroup, EC2-Fleet, SpotFleet, ECS host, etc the ability to attach * this volume to **itself** then this is the method you want to use. * * This is implemented by adding a Tag with key `VolumeGrantAttach-<suffix>` to the given * constructs and this Volume, and then conditioning the Grant such that the grantee is only * given the ability to AttachVolume if both the Volume and the destination Instance have that * tag applied to them. * * @param grantee the principal being granted permission. * @param constructs The list of constructs that will have the generated resource tag applied to them. * @param tagKeySuffix A suffix to use on the generated Tag key in place of the generated hash value. * Defaults to a hash calculated from this volume and list of constructs. (DEPRECATED) */ grantAttachVolumeByResourceTag(grantee: IGrantable, constructs: Construct[], tagKeySuffix?: string): Grant; /** * Grants permission to detach this Volume from an instance * CAUTION: Granting an instance permission to detach from itself using this method will lead to * an unresolvable circular reference between the instance role and the instance. * Use {@link IVolume.grantDetachVolumeFromSelf} to grant an instance permission to detach this * volume from itself. * * @param grantee the principal being granted permission. * @param instances the instances to which permission is being granted to detach this * volume from. If not specified, then permission is granted to detach * from all instances in this account. */ grantDetachVolume(grantee: IGrantable, instances?: IInstance[]): Grant; /** * Grants permission to detach the Volume by a ResourceTag condition. * * This is implemented via the same mechanism as {@link IVolume.grantAttachVolumeByResourceTag}, * and is subject to the same conditions. * * @param grantee the principal being granted permission. * @param constructs The list of constructs that will have the generated resource tag applied to them. * @param tagKeySuffix A suffix to use on the generated Tag key in place of the generated hash value. * Defaults to a hash calculated from this volume and list of constructs. (DEPRECATED) */ grantDetachVolumeByResourceTag(grantee: IGrantable, constructs: Construct[], tagKeySuffix?: string): Grant; } /** * Properties of an EBS Volume */ export interface VolumeProps { /** * The value of the physicalName property of this resource. * * @default The physical name will be allocated by CloudFormation at deployment time */ readonly volumeName?: string; /** * The Availability Zone in which to create the volume. */ readonly availabilityZone: string; /** * The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. * See {@link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html} * for details on the allowable size for each type of volume. * * @default If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size. */ readonly size?: Size; /** * The snapshot from which to create the volume. You must specify either a snapshot ID or a volume size. * * @default The EBS volume is not created from a snapshot. */ readonly snapshotId?: string; /** * Indicates whether Amazon EBS Multi-Attach is enabled. * See {@link https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html#considerations|Considerations and limitations} * for the constraints of multi-attach. * * @default false */ readonly enableMultiAttach?: boolean; /** * Specifies whether the volume should be encrypted. The effect of setting the encryption state to true depends on the volume origin * (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, * see {@link https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default|Encryption by Default} * in the Amazon Elastic Compute Cloud User Guide. * * Encrypted Amazon EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see * {@link https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances|Supported Instance Types.} * * @default false */ readonly encrypted?: boolean; /** * The customer-managed encryption key that is used to encrypt the Volume. The encrypted property must * be true if this is provided. * * Note: If using an {@link aws-kms.IKey} created from a {@link aws-kms.Key.fromKeyArn()} here, * then the KMS key **must** have the following in its Key policy; otherwise, the Volume * will fail to create. * * { * "Effect": "Allow", * "Principal": { "AWS": "<arn for your account-user> ex: arn:aws:iam::00000000000:root" }, * "Resource": "*", * "Action": [ * "kms:DescribeKey", * "kms:GenerateDataKeyWithoutPlainText", * ], * "Condition": { * "StringEquals": { * "kms:ViaService": "ec2.<Region>.amazonaws.com", (eg: ec2.us-east-1.amazonaws.com) * "kms:CallerAccount": "0000000000" (your account ID) * } * } * } * * @default The default KMS key for the account, region, and EC2 service is used. */ readonly encryptionKey?: IKey; /** * Indicates whether the volume is auto-enabled for I/O operations. By default, Amazon EBS disables I/O to the volume from attached EC2 * instances when it determines that a volume's data is potentially inconsistent. If the consistency of the volume is not a concern, and * you prefer that the volume be made available immediately if it's impaired, you can configure the volume to automatically enable I/O. * * @default false */ readonly autoEnableIo?: boolean; /** * The type of the volume; what type of storage to use to form the EBS Volume. * * @default {@link EbsDeviceVolumeType.GENERAL_PURPOSE_SSD} */ readonly volumeType?: EbsDeviceVolumeType; /** * The number of I/O operations per second (IOPS) to provision for the volume. The maximum ratio is 50 IOPS/GiB for PROVISIONED_IOPS_SSD, * and 500 IOPS/GiB for both PROVISIONED_IOPS_SSD_IO2 and GENERAL_PURPOSE_SSD_GP3. * See {@link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html} * for more information. * * This parameter is valid only for PROVISIONED_IOPS_SSD, PROVISIONED_IOPS_SSD_IO2 and GENERAL_PURPOSE_SSD_GP3 volumes. * * @default None -- Required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS if omitted. */ readonly iops?: number; /** * Policy to apply when the volume is removed from the stack * * @default RemovalPolicy.RETAIN */ readonly removalPolicy?: RemovalPolicy; } /** * Attributes required to import an existing EBS Volume into the Stack. */ export interface VolumeAttributes { /** * The EBS Volume's ID */ readonly volumeId: string; /** * The availability zone that the EBS Volume is contained within (ex: us-west-2a) */ readonly availabilityZone: string; /** * The customer-managed encryption key that is used to encrypt the Volume. * * @default None -- The EBS Volume is not using a customer-managed KMS key for encryption. */ readonly encryptionKey?: IKey; } /** * Common behavior of Volumes. Users should not use this class directly, and instead use ``Volume``. */ abstract class VolumeBase extends Resource implements IVolume { public abstract readonly volumeId: string; public abstract readonly availabilityZone: string; public abstract readonly encryptionKey?: IKey; public grantAttachVolume(grantee: IGrantable, instances?: IInstance[]): Grant { const result = Grant.addToPrincipal({ grantee, actions: ['ec2:AttachVolume'], resourceArns: this.collectGrantResourceArns(instances), }); if (this.encryptionKey) { // When attaching a volume, the EC2 Service will need to grant to itself permission // to be able to decrypt the encryption key. We restrict the CreateGrant for principle // of least privilege, in accordance with best practices. // See: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#ebs-encryption-permissions const kmsGrant: Grant = this.encryptionKey.grant(grantee, 'kms:CreateGrant'); kmsGrant.principalStatement!.addConditions( { Bool: { 'kms:GrantIsForAWSResource': true }, StringEquals: { 'kms:ViaService': `ec2.${Stack.of(this).region}.amazonaws.com`, 'kms:GrantConstraintType': 'EncryptionContextSubset', }, }, ); } return result; } public grantAttachVolumeByResourceTag(grantee: IGrantable, constructs: Construct[], tagKeySuffix?: string): Grant { const tagValue = this.calculateResourceTagValue([this, ...constructs]); const tagKey = `VolumeGrantAttach-${tagKeySuffix ?? tagValue.slice(0, 10).toUpperCase()}`; const grantCondition: { [key: string]: string } = {}; grantCondition[`ec2:ResourceTag/${tagKey}`] = tagValue; const result = this.grantAttachVolume(grantee); result.principalStatement!.addCondition( 'ForAnyValue:StringEquals', grantCondition, ); // The ResourceTag condition requires that all resources involved in the operation have // the given tag, so we tag this and all constructs given. Tags.of(this).add(tagKey, tagValue); constructs.forEach(construct => Tags.of(construct as CoreConstruct).add(tagKey, tagValue)); return result; } public grantDetachVolume(grantee: IGrantable, instances?: IInstance[]): Grant { const result = Grant.addToPrincipal({ grantee, actions: ['ec2:DetachVolume'], resourceArns: this.collectGrantResourceArns(instances), }); // Note: No encryption key permissions are required to detach an encrypted volume. return result; } public grantDetachVolumeByResourceTag(grantee: IGrantable, constructs: Construct[], tagKeySuffix?: string): Grant { const tagValue = this.calculateResourceTagValue([this, ...constructs]); const tagKey = `VolumeGrantDetach-${tagKeySuffix ?? tagValue.slice(0, 10).toUpperCase()}`; const grantCondition: { [key: string]: string } = {}; grantCondition[`ec2:ResourceTag/${tagKey}`] = tagValue; const result = this.grantDetachVolume(grantee); result.principalStatement!.addCondition( 'ForAnyValue:StringEquals', grantCondition, ); // The ResourceTag condition requires that all resources involved in the operation have // the given tag, so we tag this and all constructs given. Tags.of(this).add(tagKey, tagValue); constructs.forEach(construct => Tags.of(construct as CoreConstruct).add(tagKey, tagValue)); return result; } private collectGrantResourceArns(instances?: IInstance[]): string[] { const stack = Stack.of(this); const resourceArns: string[] = [ `arn:${stack.partition}:ec2:${stack.region}:${stack.account}:volume/${this.volumeId}`, ]; const instanceArnPrefix = `arn:${stack.partition}:ec2:${stack.region}:${stack.account}:instance`; if (instances) { instances.forEach(instance => resourceArns.push(`${instanceArnPrefix}/${instance?.instanceId}`)); } else { resourceArns.push(`${instanceArnPrefix}/*`); } return resourceArns; } private calculateResourceTagValue(constructs: Construct[]): string { const md5 = crypto.createHash('md5'); constructs.forEach(construct => md5.update(Names.uniqueId(construct))); return md5.digest('hex'); } } /** * Creates a new EBS Volume in AWS EC2. */ export class Volume extends VolumeBase { /** * Import an existing EBS Volume into the Stack. * * @param scope the scope of the import. * @param id the ID of the imported Volume in the construct tree. * @param attrs the attributes of the imported Volume */ public static fromVolumeAttributes(scope: Construct, id: string, attrs: VolumeAttributes): IVolume { class Import extends VolumeBase { public readonly volumeId = attrs.volumeId; public readonly availabilityZone = attrs.availabilityZone; public readonly encryptionKey = attrs.encryptionKey; } // Check that the provided volumeId looks like it could be valid. if (!Token.isUnresolved(attrs.volumeId) && !/^vol-[0-9a-fA-F]+$/.test(attrs.volumeId)) { throw new Error('`volumeId` does not match expected pattern. Expected `vol-<hexadecmial value>` (ex: `vol-05abe246af`) or a Token'); } return new Import(scope, id); } public readonly volumeId: string; public readonly availabilityZone: string; public readonly encryptionKey?: IKey; constructor(scope: Construct, id: string, props: VolumeProps) { super(scope, id, { physicalName: props.volumeName, }); this.validateProps(props); const resource = new CfnVolume(this, 'Resource', { availabilityZone: props.availabilityZone, autoEnableIo: props.autoEnableIo, encrypted: props.encrypted, kmsKeyId: props.encryptionKey?.keyArn, iops: props.iops, multiAttachEnabled: props.enableMultiAttach ?? false, size: props.size?.toGibibytes({ rounding: SizeRoundingBehavior.FAIL }), snapshotId: props.snapshotId, volumeType: props.volumeType ?? EbsDeviceVolumeType.GENERAL_PURPOSE_SSD, }); resource.applyRemovalPolicy(props.removalPolicy); if (props.volumeName) Tags.of(resource).add('Name', props.volumeName); this.volumeId = resource.ref; this.availabilityZone = props.availabilityZone; this.encryptionKey = props.encryptionKey; if (this.encryptionKey) { // Per: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#ebs-encryption-requirements const principal = new ViaServicePrincipal(`ec2.${Stack.of(this).region}.amazonaws.com`, new AccountRootPrincipal()).withConditions({ StringEquals: { 'kms:CallerAccount': Stack.of(this).account, }, }); const grant = this.encryptionKey.grant(principal, // Describe & Generate are required to be able to create the CMK-encrypted Volume. 'kms:DescribeKey', 'kms:GenerateDataKeyWithoutPlainText', ); if (props.snapshotId) { // ReEncrypt is required for when re-encrypting from an encrypted snapshot. grant.principalStatement?.addActions('kms:ReEncrypt*'); } } } protected validateProps(props: VolumeProps) { if (!(props.size || props.snapshotId)) { throw new Error('Must provide at least one of `size` or `snapshotId`'); } if (props.snapshotId && !Token.isUnresolved(props.snapshotId) && !/^snap-[0-9a-fA-F]+$/.test(props.snapshotId)) { throw new Error('`snapshotId` does match expected pattern. Expected `snap-<hexadecmial value>` (ex: `snap-05abe246af`) or Token'); } if (props.encryptionKey && !props.encrypted) { throw new Error('`encrypted` must be true when providing an `encryptionKey`.'); } if ( props.volumeType && [ EbsDeviceVolumeType.PROVISIONED_IOPS_SSD, EbsDeviceVolumeType.PROVISIONED_IOPS_SSD_IO2, ].includes(props.volumeType) && !props.iops ) { throw new Error( '`iops` must be specified if the `volumeType` is `PROVISIONED_IOPS_SSD` or `PROVISIONED_IOPS_SSD_IO2`.', ); } if (props.iops) { const volumeType = props.volumeType ?? EbsDeviceVolumeType.GENERAL_PURPOSE_SSD; if ( ![ EbsDeviceVolumeType.PROVISIONED_IOPS_SSD, EbsDeviceVolumeType.PROVISIONED_IOPS_SSD_IO2, EbsDeviceVolumeType.GENERAL_PURPOSE_SSD_GP3, ].includes(volumeType) ) { throw new Error( '`iops` may only be specified if the `volumeType` is `PROVISIONED_IOPS_SSD`, `PROVISIONED_IOPS_SSD_IO2` or `GENERAL_PURPOSE_SSD_GP3`.', ); } // Enforce minimum & maximum IOPS: // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html const iopsRanges: { [key: string]: { Min: number, Max: number } } = {}; iopsRanges[EbsDeviceVolumeType.GENERAL_PURPOSE_SSD_GP3] = { Min: 3000, Max: 16000 }; iopsRanges[EbsDeviceVolumeType.PROVISIONED_IOPS_SSD] = { Min: 100, Max: 64000 }; iopsRanges[EbsDeviceVolumeType.PROVISIONED_IOPS_SSD_IO2] = { Min: 100, Max: 64000 }; const { Min, Max } = iopsRanges[volumeType]; if (props.iops < Min || props.iops > Max) { throw new Error(`\`${volumeType}\` volumes iops must be between ${Min} and ${Max}.`); } // Enforce maximum ratio of IOPS/GiB: // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html const maximumRatios: { [key: string]: number } = {}; maximumRatios[EbsDeviceVolumeType.GENERAL_PURPOSE_SSD_GP3] = 500; maximumRatios[EbsDeviceVolumeType.PROVISIONED_IOPS_SSD] = 50; maximumRatios[EbsDeviceVolumeType.PROVISIONED_IOPS_SSD_IO2] = 500; const maximumRatio = maximumRatios[volumeType]; if (props.size && (props.iops > maximumRatio * props.size.toGibibytes({ rounding: SizeRoundingBehavior.FAIL }))) { throw new Error(`\`${volumeType}\` volumes iops has a maximum ratio of ${maximumRatio} IOPS/GiB.`); } } if (props.enableMultiAttach) { const volumeType = props.volumeType ?? EbsDeviceVolumeType.GENERAL_PURPOSE_SSD; if ( ![ EbsDeviceVolumeType.PROVISIONED_IOPS_SSD, EbsDeviceVolumeType.PROVISIONED_IOPS_SSD_IO2, ].includes(volumeType) ) { throw new Error('multi-attach is supported exclusively on `PROVISIONED_IOPS_SSD` and `PROVISIONED_IOPS_SSD_IO2` volumes.'); } } if (props.size) { const size = props.size.toGibibytes({ rounding: SizeRoundingBehavior.FAIL }); // Enforce minimum & maximum volume size: // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html const sizeRanges: { [key: string]: { Min: number, Max: number } } = {}; sizeRanges[EbsDeviceVolumeType.GENERAL_PURPOSE_SSD] = { Min: 1, Max: 16384 }; sizeRanges[EbsDeviceVolumeType.GENERAL_PURPOSE_SSD_GP3] = { Min: 1, Max: 16384 }; sizeRanges[EbsDeviceVolumeType.PROVISIONED_IOPS_SSD] = { Min: 4, Max: 16384 }; sizeRanges[EbsDeviceVolumeType.PROVISIONED_IOPS_SSD_IO2] = { Min: 4, Max: 16384 }; sizeRanges[EbsDeviceVolumeType.THROUGHPUT_OPTIMIZED_HDD] = { Min: 125, Max: 16384 }; sizeRanges[EbsDeviceVolumeType.COLD_HDD] = { Min: 125, Max: 16384 }; sizeRanges[EbsDeviceVolumeType.MAGNETIC] = { Min: 1, Max: 1024 }; const volumeType = props.volumeType ?? EbsDeviceVolumeType.GENERAL_PURPOSE_SSD; const { Min, Max } = sizeRanges[volumeType]; if (size < Min || size > Max) { throw new Error(`\`${volumeType}\` volumes must be between ${Min} GiB and ${Max} GiB in size.`); } } } }
the_stack
export interface RegExpOptions { sensitive?: boolean; strict?: boolean; end?: boolean; delimiter?: string; delimiters?: string | string[]; endsWith?: string | string[]; } export interface ParseOptions { delimiter?: string; delimiters?: string | string[]; } export interface Key { name: string | number; prefix: string | null; delimiter: string | null; optional: boolean; repeat: boolean; pattern: string | null; partial: boolean; } export interface PathFunctionOptions { encode?: (value: string) => string; } export type Token = string | Key; export type Path = string | RegExp | Array<string | RegExp>; export type PathFunction = ( data?: { [key: string]: any }, options?: PathFunctionOptions ) => string; /** * Default configs. */ const DEFAULT_DELIMITER = '/'; const DEFAULT_DELIMITERS = './'; /** * The main path matching regexp utility. */ const PATH_REGEXP = new RegExp( [ // Match escaped characters that would otherwise appear in future matches. // This allows the user to escape special characters that won't transform. '(\\\\.)', // Match Express-style parameters and un-named parameters with a prefix // and optional suffixes. Matches appear as: // // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"] // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined] '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?', ].join('|'), 'g' ); /** * Parse a string for the raw tokens. */ export const parse = (str: string, options?: ParseOptions): Token[] => { var tokens = []; var key = 0; var index = 0; var path = ''; var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER; var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS; var pathEscaped = false; var res; while ((res = PATH_REGEXP.exec(str)) !== null) { var m = res[0]; var escaped = res[1]; var offset = res.index; path += str.slice(index, offset); index = offset + m.length; // Ignore already escaped sequences. if (escaped) { path += escaped[1]; pathEscaped = true; continue; } var prev = ''; var next = str[index]; var name = res[2]; var capture = res[3]; var group = res[4]; var modifier = res[5]; if (!pathEscaped && path.length) { var k = path.length - 1; if (delimiters.indexOf(path[k]) > -1) { prev = path[k]; path = path.slice(0, k); } } // Push the current path onto the tokens. if (path) { tokens.push(path); path = ''; pathEscaped = false; } var partial = prev !== '' && next !== undefined && next !== prev; var repeat = modifier === '+' || modifier === '*'; var optional = modifier === '?' || modifier === '*'; var delimiter = prev || defaultDelimiter; var pattern = capture || group; tokens.push({ name: name || key++, prefix: prev, delimiter: delimiter, optional: optional, repeat: repeat, partial: partial, pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?', }); } // Push any remaining characters. if (path || index < str.length) { tokens.push(path + str.substr(index)); } return tokens; }; /** * Compile a string to a template function for the path. */ export const compile = (str: string, options?: ParseOptions) => { return tokensToFunction(parse(str, options)); }; /** * Expose a method for transforming tokens into the path function. */ export const tokensToFunction = (tokens: Token[]): PathFunction => { // Compile all the tokens into regexps. var matches = new Array(tokens.length); // Compile all the patterns before compilation. for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'object') { matches[i] = new RegExp('^(?:' + token.pattern + ')$'); } } return ( data?: { [key: string]: any }, options?: PathFunctionOptions ): string => { var path = ''; var encode = (options && options.encode) || encodeURIComponent; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { path += token; continue; } var value = data ? data[token.name] : undefined; var segment; if (Array.isArray(value)) { if (!token.repeat) { throw new TypeError( 'Expected "' + token.name + '" to not repeat, but got array' ); } if (value.length === 0) { if (token.optional) continue; throw new TypeError('Expected "' + token.name + '" to not be empty'); } for (var j = 0; j < value.length; j++) { segment = encode(value[j]); if (!matches[i].test(segment)) { throw new TypeError( 'Expected all "' + token.name + '" to match "' + token.pattern + '"' ); } path += (j === 0 ? token.prefix : token.delimiter) + segment; } continue; } if ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) { segment = encode(String(value)); if (!matches[i].test(segment)) { throw new TypeError( 'Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"' ); } path += token.prefix + segment; continue; } if (token.optional) { // Prepend partial segment prefixes. if (token.partial) path += token.prefix; continue; } throw new TypeError( 'Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string') ); } return path; }; }; /** * Escape a regular expression string. */ const escapeString = (str: string) => { return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1'); }; /** * Escape the capturing group by escaping special characters and meaning. */ const escapeGroup = (group: string) => { return group.replace(/([=!:$/()])/g, '\\$1'); }; /** * Get the flags for a regexp from the options. */ const flags = (options: RegExpOptions): string => { return options && options.sensitive ? '' : 'i'; }; /** * Pull out keys from a regexp. */ const regexpToRegexp = (path: RegExp, keys: Key[]): RegExp => { if (!keys) return path; // Use a negative lookahead to match only capturing groups. var groups = path.source.match(/\((?!\?)/g); if (groups) { for (var i = 0; i < groups.length; i++) { keys.push({ name: i, prefix: null, delimiter: null, optional: false, repeat: false, partial: false, pattern: null, }); } } return path; }; /** * Transform an array into a regexp. */ const arrayToRegexp = ( path: Array<string | RegExp>, keys: Key[], options: RegExpOptions ): RegExp => { var parts = []; for (var i = 0; i < path.length; i++) { parts.push(pathToRegexp(path[i], keys, options).source); } return new RegExp('(?:' + parts.join('|') + ')', flags(options)); }; /** * Create a path regexp from string input. */ const stringToRegexp = ( path: string, keys: Key[], options: RegExpOptions ): RegExp => { return tokensToRegExp(parse(path, options), keys, options); }; /** * Expose a function for taking tokens and returning a RegExp. */ export const tokensToRegExp = ( tokens: Token[], keys?: Key[], options?: RegExpOptions ): RegExp => { options = options || {}; var strict = options.strict; var end = options.end !== false; var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER); var delimiters = options.delimiters || DEFAULT_DELIMITERS; var endsWith = (<Array<string>>[]) .concat(options.endsWith || []) .map(escapeString) .concat('$') .join('|'); var route = ''; var isEndDelimited = false; // Iterate over the tokens and create our regexp string. for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { route += escapeString(token); isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1; } else { var prefix = escapeString(token.prefix || ''); var capture = token.repeat ? '(?:' + token.pattern + ')(?:' + prefix + '(?:' + token.pattern + '))*' : token.pattern; if (keys) keys.push(token); if (token.optional) { if (token.partial) { route += prefix + '(' + capture + ')?'; } else { route += '(?:' + prefix + '(' + capture + '))?'; } } else { route += prefix + '(' + capture + ')'; } } } if (end) { if (!strict) route += '(?:' + delimiter + ')?'; route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'; } else { if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'; if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'; } return new RegExp('^' + route, flags(options)); }; /** * Normalize the given path string, returning a regular expression. * * An empty array can be passed in for the keys, which will hold the * placeholder key descriptions. For example, using `/user/:id`, `keys` will * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. */ export const pathToRegexp = ( path: Path, keys: Key[], options: RegExpOptions ): RegExp => { if (path instanceof RegExp) { return regexpToRegexp(path, keys); } if (Array.isArray(path)) { return arrayToRegexp(path, keys, options); } return stringToRegexp(path, keys, options); };
the_stack
import { SpanStatusCode, Exception, ROOT_CONTEXT, SpanContext, SpanKind, TraceFlags, } from '@opentelemetry/api'; import { hrTime, hrTimeDuration, hrTimeToMilliseconds, hrTimeToNanoseconds, } from '@opentelemetry/core'; import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; import * as assert from 'assert'; import { BasicTracerProvider, Span, SpanProcessor } from '../../src'; const performanceTimeOrigin = hrTime(); describe('Span', () => { const tracer = new BasicTracerProvider({ spanLimits: { attributeValueLengthLimit: 100, attributeCountLimit: 100, eventCountLimit: 100, }, }).getTracer('default'); const name = 'span1'; const spanContext: SpanContext = { traceId: 'd4cda95b652f4a1592b449d5929fda1b', spanId: '6e0c63257de34c92', traceFlags: TraceFlags.SAMPLED, }; const linkContext: SpanContext = { traceId: 'e4cda95b652f4a1592b449d5929fda1b', spanId: '7e0c63257de34c92', traceFlags: TraceFlags.SAMPLED }; it('should create a Span instance', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); assert.ok(span instanceof Span); span.end(); }); it('should have valid startTime', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); assert.ok( hrTimeToMilliseconds(span.startTime) > hrTimeToMilliseconds(performanceTimeOrigin) ); }); it('should have valid endTime', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); span.end(); assert.ok( hrTimeToNanoseconds(span.endTime) >= hrTimeToNanoseconds(span.startTime), 'end time must be bigger or equal start time' ); assert.ok( hrTimeToMilliseconds(span.endTime) > hrTimeToMilliseconds(performanceTimeOrigin), 'end time must be bigger than time origin' ); }); it('should have a duration', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); span.end(); assert.ok(hrTimeToNanoseconds(span.duration) >= 0); }); it('should have valid event.time', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); span.addEvent('my-event'); assert.ok( hrTimeToMilliseconds(span.events[0].time) > hrTimeToMilliseconds(performanceTimeOrigin) ); }); it('should have an entered time for event', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER, undefined, [], 0 ); const timeMS = 123; const spanStartTime = hrTimeToMilliseconds(span.startTime); const eventTime = spanStartTime + timeMS; span.addEvent('my-event', undefined, eventTime); const diff = hrTimeDuration(span.startTime, span.events[0].time); assert.strictEqual(hrTimeToMilliseconds(diff), 123); }); describe('when 2nd param is "TimeInput" type', () => { it('should have an entered time for event - ', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER, undefined, [], 0 ); const timeMS = 123; const spanStartTime = hrTimeToMilliseconds(span.startTime); const eventTime = spanStartTime + timeMS; span.addEvent('my-event', eventTime); const diff = hrTimeDuration(span.startTime, span.events[0].time); assert.strictEqual(hrTimeToMilliseconds(diff), 123); }); }); it('should get the span context of span', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); const context = span.spanContext(); assert.strictEqual(context.traceId, spanContext.traceId); assert.strictEqual(context.traceFlags, TraceFlags.SAMPLED); assert.strictEqual(context.traceState, undefined); assert.ok(context.spanId.match(/[a-f0-9]{16}/)); assert.ok(span.isRecording()); span.end(); }); describe('isRecording', () => { it('should return true when span is not ended', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); assert.ok(span.isRecording()); span.end(); }); it('should return false when span is ended', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); span.end(); assert.ok(span.isRecording() === false); }); }); describe('setAttribute', () => { describe('when default options set', () => { it('should set an attribute', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); span.setAttribute('string', 'string'); span.setAttribute('number', 0); span.setAttribute('bool', true); span.setAttribute('array<string>', ['str1', 'str2']); span.setAttribute('array<number>', [1, 2]); span.setAttribute('array<bool>', [true, false]); //@ts-expect-error invalid attribute type object span.setAttribute('object', { foo: 'bar' }); //@ts-expect-error invalid attribute inhomogenous array span.setAttribute('non-homogeneous-array', [0, '']); // This empty length attribute should not be set span.setAttribute('', 'empty-key'); assert.deepStrictEqual(span.attributes, { string: 'string', number: 0, bool: true, 'array<string>': ['str1', 'str2'], 'array<number>': [1, 2], 'array<bool>': [true, false], }); }); it('should be able to overwrite attributes', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); span.setAttribute('overwrite', 'initial value'); span.setAttribute('overwrite', 'overwritten value'); assert.deepStrictEqual(span.attributes, { overwrite: 'overwritten value', }); }); }); describe('when generalLimits options set', () => { describe('when "attributeCountLimit" option defined', () => { const tracer = new BasicTracerProvider({ generalLimits: { // Setting count limit attributeCountLimit: 100, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); for (let i = 0; i < 150; i++) { span.setAttribute('foo' + i, 'bar' + i); } span.end(); it('should remove / drop all remaining values after the number of values exceeds this limit', () => { assert.strictEqual(Object.keys(span.attributes).length, 100); assert.strictEqual(span.attributes['foo0'], 'bar0'); assert.strictEqual(span.attributes['foo99'], 'bar99'); assert.strictEqual(span.attributes['foo149'], undefined); }); }); describe('when "attributeValueLengthLimit" option defined', () => { const tracer = new BasicTracerProvider({ generalLimits: { // Setting attribute value length limit attributeValueLengthLimit: 5, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); it('should truncate value which length exceeds this limit', () => { span.setAttribute('attr-with-more-length', 'abcdefgh'); assert.strictEqual(span.attributes['attr-with-more-length'], 'abcde'); }); it('should truncate value of arrays which exceeds this limit', () => { span.setAttribute('attr-array-of-strings', ['abcdefgh', 'abc', 'abcde', '']); span.setAttribute('attr-array-of-bool', [true, false]); assert.deepStrictEqual(span.attributes['attr-array-of-strings'], ['abcde', 'abc', 'abcde', '']); assert.deepStrictEqual(span.attributes['attr-array-of-bool'], [true, false]); }); it('should not truncate value which length not exceeds this limit', () => { span.setAttribute('attr-with-less-length', 'abc'); assert.strictEqual(span.attributes['attr-with-less-length'], 'abc'); }); it('should return same value for non-string values', () => { span.setAttribute('attr-non-string', true); assert.strictEqual(span.attributes['attr-non-string'], true); }); }); describe('when "attributeValueLengthLimit" option is invalid', () => { const tracer = new BasicTracerProvider({ generalLimits: { // Setting invalid attribute value length limit attributeValueLengthLimit: -5, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); it('should not truncate any value', () => { span.setAttribute('attr-not-truncate', 'abcdefgh'); span.setAttribute('attr-array-of-strings', ['abcdefgh', 'abc', 'abcde']); assert.deepStrictEqual(span.attributes['attr-not-truncate'], 'abcdefgh'); assert.deepStrictEqual(span.attributes['attr-array-of-strings'], ['abcdefgh', 'abc', 'abcde']); }); }); }); describe('when spanLimits options set', () => { describe('when "attributeCountLimit" option defined', () => { const tracer = new BasicTracerProvider({ spanLimits: { // Setting count limit attributeCountLimit: 100, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); for (let i = 0; i < 150; i++) { span.setAttribute('foo' + i, 'bar' + i); } span.end(); it('should remove / drop all remaining values after the number of values exceeds this limit', () => { assert.strictEqual(Object.keys(span.attributes).length, 100); assert.strictEqual(span.attributes['foo0'], 'bar0'); assert.strictEqual(span.attributes['foo99'], 'bar99'); assert.strictEqual(span.attributes['foo149'], undefined); }); }); describe('when "attributeValueLengthLimit" option defined', () => { const tracer = new BasicTracerProvider({ spanLimits: { // Setting attribute value length limit attributeValueLengthLimit: 5, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); it('should truncate value which length exceeds this limit', () => { span.setAttribute('attr-with-more-length', 'abcdefgh'); assert.strictEqual(span.attributes['attr-with-more-length'], 'abcde'); }); it('should truncate value of arrays which exceeds this limit', () => { span.setAttribute('attr-array-of-strings', ['abcdefgh', 'abc', 'abcde', '']); span.setAttribute('attr-array-of-bool', [true, false]); assert.deepStrictEqual(span.attributes['attr-array-of-strings'], ['abcde', 'abc', 'abcde', '']); assert.deepStrictEqual(span.attributes['attr-array-of-bool'], [true, false]); }); it('should not truncate value which length not exceeds this limit', () => { span.setAttribute('attr-with-less-length', 'abc'); assert.strictEqual(span.attributes['attr-with-less-length'], 'abc'); }); it('should return same value for non-string values', () => { span.setAttribute('attr-non-string', true); assert.strictEqual(span.attributes['attr-non-string'], true); }); }); describe('when "attributeValueLengthLimit" option is invalid', () => { const tracer = new BasicTracerProvider({ spanLimits: { // Setting invalid attribute value length limit attributeValueLengthLimit: -5, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); it('should not truncate any value', () => { span.setAttribute('attr-not-truncate', 'abcdefgh'); span.setAttribute('attr-array-of-strings', ['abcdefgh', 'abc', 'abcde']); assert.deepStrictEqual(span.attributes['attr-not-truncate'], 'abcdefgh'); assert.deepStrictEqual(span.attributes['attr-array-of-strings'], ['abcdefgh', 'abc', 'abcde']); }); }); }); describe('when both generalLimits and spanLimits options set', () => { describe('when "attributeCountLimit" option defined', () => { const tracer = new BasicTracerProvider({ generalLimits: { // Setting count limit attributeCountLimit: 10, }, spanLimits: { attributeCountLimit: 5, } }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); for (let i = 0; i < 150; i++) { span.setAttribute('foo' + i, 'bar' + i); } span.end(); it('should remove / drop all remaining values after the number of values exceeds span limit', () => { assert.strictEqual(Object.keys(span.attributes).length, 5); assert.strictEqual(span.attributes['foo0'], 'bar0'); assert.strictEqual(span.attributes['foo4'], 'bar4'); assert.strictEqual(span.attributes['foo5'], undefined); assert.strictEqual(span.attributes['foo10'], undefined); }); }); describe('when "attributeValueLengthLimit" option defined', () => { const tracer = new BasicTracerProvider({ generalLimits: { // Setting attribute value length limit attributeValueLengthLimit: 10, }, spanLimits: { // Setting attribute value length limit attributeValueLengthLimit: 5, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); it('should truncate value which length exceeds span limit', () => { span.setAttribute('attr-with-more-length', 'abcdefgh'); assert.strictEqual(span.attributes['attr-with-more-length'], 'abcde'); }); it('should truncate value of arrays which exceeds span limit', () => { span.setAttribute('attr-array-of-strings', ['abcdefgh', 'abc', 'abcde', '']); span.setAttribute('attr-array-of-bool', [true, false]); assert.deepStrictEqual(span.attributes['attr-array-of-strings'], ['abcde', 'abc', 'abcde', '']); assert.deepStrictEqual(span.attributes['attr-array-of-bool'], [true, false]); }); it('should not truncate value which length not exceeds span limit', () => { span.setAttribute('attr-with-less-length', 'abc'); assert.strictEqual(span.attributes['attr-with-less-length'], 'abc'); }); it('should return same value for non-string values', () => { span.setAttribute('attr-non-string', true); assert.strictEqual(span.attributes['attr-non-string'], true); }); }); }); }); describe('setAttributes', () => { it('should be able to set multiple attributes', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); span.setAttributes({ string: 'string', number: 0, bool: true, 'array<string>': ['str1', 'str2'], 'array<number>': [1, 2], 'array<bool>': [true, false], //@ts-expect-error invalid attribute type object object: { foo: 'bar' }, //@ts-expect-error invalid attribute inhomogenous array 'non-homogeneous-array': [0, ''], // This empty length attribute should not be set '': 'empty-key', }); assert.deepStrictEqual(span.attributes, { string: 'string', number: 0, bool: true, 'array<string>': ['str1', 'str2'], 'array<number>': [1, 2], 'array<bool>': [true, false], }); }); }); it('should set an event', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); span.addEvent('sent'); span.addEvent('rev', { attr1: 'value', attr2: 123, attr3: true }); span.end(); }); it('should set a link', () => { const spanContext: SpanContext = { traceId: 'a3cda95b652f4a1592b449d5929fda1b', spanId: '5e0c63257de34c92', traceFlags: TraceFlags.SAMPLED, }; const linkContext: SpanContext = { traceId: 'b3cda95b652f4a1592b449d5929fda1b', spanId: '6e0c63257de34c92', traceFlags: TraceFlags.SAMPLED }; const attributes = { attr1: 'value', attr2: 123, attr3: true }; const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT, '12345', [{ context: linkContext }, { context: linkContext, attributes }] ); span.end(); }); it('should drop extra events', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); for (let i = 0; i < 150; i++) { span.addEvent('sent' + i); } span.end(); assert.strictEqual(span.events.length, 100); assert.strictEqual(span.events[span.events.length - 1].name, 'sent149'); }); it('should add no event', () => { const tracer = new BasicTracerProvider({ spanLimits: { eventCountLimit: 0, }, }).getTracer('default'); const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); for (let i = 0; i < 10; i++) { span.addEvent('sent' + i); } span.end(); assert.strictEqual(span.events.length, 0); }); it('should set an error status', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); span.setStatus({ code: SpanStatusCode.ERROR, message: 'This is an error', }); span.end(); }); it('should return ReadableSpan', () => { const parentId = '5c1c63257de34c67'; const span = new Span( tracer, ROOT_CONTEXT, 'my-span', spanContext, SpanKind.INTERNAL, parentId ); assert.strictEqual(span.name, 'my-span'); assert.strictEqual(span.kind, SpanKind.INTERNAL); assert.strictEqual(span.parentSpanId, parentId); assert.strictEqual(span.spanContext().traceId, spanContext.traceId); assert.deepStrictEqual(span.status, { code: SpanStatusCode.UNSET, }); assert.deepStrictEqual(span.attributes, {}); assert.deepStrictEqual(span.links, []); assert.deepStrictEqual(span.events, []); assert.ok(span.instrumentationLibrary); const { name, version } = span.instrumentationLibrary; assert.strictEqual(name, 'default'); assert.strictEqual(version, undefined); }); it('should return ReadableSpan with attributes', () => { const span = new Span( tracer, ROOT_CONTEXT, 'my-span', spanContext, SpanKind.CLIENT ); span.setAttribute('attr1', 'value1'); assert.deepStrictEqual(span.attributes, { attr1: 'value1' }); span.setAttributes({ attr2: 123, attr1: false }); assert.deepStrictEqual(span.attributes, { attr1: false, attr2: 123, }); span.end(); // shouldn't add new attribute span.setAttribute('attr3', 'value3'); assert.deepStrictEqual(span.attributes, { attr1: false, attr2: 123, }); }); it('should return ReadableSpan with links', () => { const span = new Span( tracer, ROOT_CONTEXT, 'my-span', spanContext, SpanKind.CLIENT, undefined, [ { context: linkContext }, { context: linkContext, attributes: { attr1: 'value', attr2: 123, attr3: true }, }, ] ); assert.strictEqual(span.links.length, 2); assert.deepStrictEqual(span.links, [ { context: linkContext, }, { attributes: { attr1: 'value', attr2: 123, attr3: true }, context: linkContext, }, ]); span.end(); }); it('should return ReadableSpan with events', () => { const span = new Span( tracer, ROOT_CONTEXT, 'my-span', spanContext, SpanKind.CLIENT ); span.addEvent('sent'); assert.strictEqual(span.events.length, 1); const [event] = span.events; assert.deepStrictEqual(event.name, 'sent'); assert.ok(!event.attributes); assert.ok(event.time[0] > 0); span.addEvent('rev', { attr1: 'value', attr2: 123, attr3: true }); assert.strictEqual(span.events.length, 2); const [event1, event2] = span.events; assert.deepStrictEqual(event1.name, 'sent'); assert.ok(!event1.attributes); assert.ok(event1.time[0] > 0); assert.deepStrictEqual(event2.name, 'rev'); assert.deepStrictEqual(event2.attributes, { attr1: 'value', attr2: 123, attr3: true, }); assert.ok(event2.time[0] > 0); span.end(); // shouldn't add new event span.addEvent('sent'); assert.strictEqual(span.events.length, 2); }); it('should return ReadableSpan with new status', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); span.setStatus({ code: SpanStatusCode.ERROR, message: 'This is an error', }); assert.strictEqual(span.status.code, SpanStatusCode.ERROR); assert.strictEqual(span.status.message, 'This is an error'); span.end(); // shouldn't update status span.setStatus({ code: SpanStatusCode.OK, message: 'OK', }); assert.strictEqual(span.status.code, SpanStatusCode.ERROR); }); it('should only end a span once', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); const endTime = Date.now(); span.end(endTime); span.end(endTime + 10); assert.deepStrictEqual(span.endTime[0], Math.trunc(endTime / 1000)); }); it('should update name', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); span.updateName('foo-span'); span.end(); // shouldn't update name span.updateName('bar-span'); assert.strictEqual(span.name, 'foo-span'); }); it('should have ended', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.SERVER ); assert.strictEqual(span.ended, false); span.end(); assert.strictEqual(span.ended, true); }); describe('span processor', () => { it('should call onStart synchronously when span is started', () => { let started = false; const processor: SpanProcessor = { onStart: () => { started = true; }, forceFlush: () => Promise.resolve(), onEnd() {}, shutdown: () => Promise.resolve(), }; const provider = new BasicTracerProvider(); provider.addSpanProcessor(processor); provider.getTracer('default').startSpan('test'); assert.ok(started); }); it('should call onEnd synchronously when span is ended', () => { let ended = false; const processor: SpanProcessor = { onStart: () => {}, forceFlush: () => Promise.resolve(), onEnd() { ended = true; }, shutdown: () => Promise.resolve(), }; const provider = new BasicTracerProvider(); provider.addSpanProcessor(processor); provider.getTracer('default').startSpan('test').end(); assert.ok(ended); }); it('should call onStart with a writeable span', () => { const processor: SpanProcessor = { onStart: span => { span.setAttribute('attr', true); }, forceFlush: () => Promise.resolve(), onEnd() {}, shutdown: () => Promise.resolve(), }; const provider = new BasicTracerProvider(); provider.addSpanProcessor(processor); const s = provider.getTracer('default').startSpan('test') as Span; assert.ok(s.attributes.attr); }); }); describe('recordException', () => { const invalidExceptions: any[] = [ 1, null, undefined, { foo: 'bar' }, { stack: 'bar' }, ['a', 'b', 'c'], ]; invalidExceptions.forEach(key => { describe(`when exception is (${JSON.stringify(key)})`, () => { it('should NOT record an exception', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); assert.strictEqual(span.events.length, 0); span.recordException(key); assert.strictEqual(span.events.length, 0); }); }); }); describe('when exception type is "string"', () => { let error: Exception; beforeEach(() => { error = 'boom'; }); it('should record an exception', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); assert.strictEqual(span.events.length, 0); span.recordException(error); const event = span.events[0]; assert.strictEqual(event.name, 'exception'); assert.deepStrictEqual(event.attributes, { 'exception.message': 'boom', }); assert.ok(event.time[0] > 0); }); }); const errorsObj = [ { description: 'code', obj: { code: 'Error', message: 'boom', stack: 'bar' }, }, { description: 'name', obj: { name: 'Error', message: 'boom', stack: 'bar' }, }, ]; errorsObj.forEach(errorObj => { describe(`when exception type is an object with ${errorObj.description}`, () => { const error: Exception = errorObj.obj; it('should record an exception', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); assert.strictEqual(span.events.length, 0); span.recordException(error); const event = span.events[0]; assert.ok(event.time[0] > 0); assert.strictEqual(event.name, 'exception'); assert.ok(event.attributes); const type = event.attributes[SemanticAttributes.EXCEPTION_TYPE]; const message = event.attributes[SemanticAttributes.EXCEPTION_MESSAGE]; const stacktrace = String( event.attributes[SemanticAttributes.EXCEPTION_STACKTRACE] ); assert.strictEqual(type, 'Error'); assert.strictEqual(message, 'boom'); assert.strictEqual(stacktrace, 'bar'); }); }); }); describe('when time is provided', () => { it('should record an exception with provided time', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); assert.strictEqual(span.events.length, 0); span.recordException('boom', [0, 123]); const event = span.events[0]; assert.deepStrictEqual(event.time, [0, 123]); }); }); describe('when exception code is numeric', () => { it('should record an exception with string value', () => { const span = new Span( tracer, ROOT_CONTEXT, name, spanContext, SpanKind.CLIENT ); assert.strictEqual(span.events.length, 0); span.recordException({ code: 12 }); const event = span.events[0]; assert.deepStrictEqual(event.attributes, { [SemanticAttributes.EXCEPTION_TYPE]: '12', }); }); }); }); });
the_stack
import uuid from "uuid/v4"; import { TokenProvider, EventHubRuntimeInformation, EventHubPartitionRuntimeInformation, AadTokenProvider, EventHubClient } from "@azure/event-hubs"; import { ApplicationTokenCredentials, UserTokenCredentials, DeviceTokenCredentials, MSITokenCredentials } from "ms-rest-azure"; import * as log from "./log"; import { LeaseManager } from "./leaseManager"; import { HostContext } from "./hostContext"; import { CheckpointManager } from "./checkpointManager"; import { validateType } from "./util/utils"; import { FromConnectionStringOptions, EventProcessorHostOptions, FromTokenProviderOptions, OnReceivedMessage, OnReceivedError, FromIotHubConnectionStringOptions } from "./modelTypes"; /** * Describes the Event Processor Host to process events from an EventHub. * @class EventProcessorHost */ export class EventProcessorHost { /** * @property {ProcessorContextWithLeaseManager} _context The processor context. * @private */ private _context: HostContext; /** * Creates a new host to process events from an Event Hub. * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} storageConnectionString Connection string to Azure Storage account used for * leases and checkpointing. Example DefaultEndpointsProtocol=https;AccountName=<account-name>; * AccountKey=<account-key>;EndpointSuffix=core.windows.net * @param {EventHubClient} eventHubClient The EventHub client * @param {EventProcessorOptions} [options] Optional parameters for creating an * EventProcessorHost. */ constructor(hostName: string, options?: EventProcessorHostOptions) { if (!options) options = {}; this._context = HostContext.create(hostName, options); } /** * Provides the host name for the Event processor host. */ get hostName(): string { return this._context.hostName; } /** * Provides the consumer group name for the Event processor host. */ get consumerGroup(): string { return this._context.consumerGroup; } /** * Provides the eventhub runtime information. * @returns {Promise<EventHubRuntimeInformation>} */ getHubRuntimeInformation(): Promise<EventHubRuntimeInformation> { return this._context.getHubRuntimeInformation(); } /** * Provides information about the specified partition. * @param {(string|number)} partitionId Partition ID for which partition information is required. * * @returns {EventHubPartitionRuntimeInformation} EventHubPartitionRuntimeInformation */ getPartitionInformation(partitionId: string | number): Promise<EventHubPartitionRuntimeInformation> { return this._context.getPartitionInformation(partitionId); } /** * Provides an array of partitionIds. * @returns {Promise<string[]>} */ getPartitionIds(): Promise<string[]> { return this._context.getPartitionIds(); } /** * Provides a list of partitions the EPH is currently receiving messages from. * * The EPH will try to grab leases for more partitions during each scan that happens once every * (configured) lease renew seconds. The number of EPH instances that are being run * simultaneously to receive messages from the same consumer group within an event hub also * influences the number of partitions that this instance of EPH is actively receiving messages * from. * * @returns {Array<string>} Array<string> List of partitions that this EPH instance is currently * receiving messages from. */ get receivingFromPartitions(): string[] { return Array.from(this._context.pumps.keys()); } /** * Starts the event processor host, fetching the list of partitions, and attempting to grab leases * For each successful lease, it will get the details from the blob and start a receiver at the * point where it left off previously. * * @return {Promise<void>} */ async start(onMessage: OnReceivedMessage, onError: OnReceivedError): Promise<void> { try { await this._context.partitionManager.start(onMessage, onError); } catch (err) { log.error(this._context.withHost("An error occurred while starting the EPH: %O"), err); this._context.onEphError(err); throw err; } } /** * Stops the EventProcessorHost from processing messages. * @return {Promise<void>} */ async stop(): Promise<void> { try { await this._context.partitionManager.stop(); } catch (err) { log.error(this._context.withHost("An error occurred while stopping the EPH: %O"), err); this._context.onEphError(err); throw err; } } /** * Convenience method for generating unique host name. * * @param {string} [prefix] String to use as the beginning of the name. Default value: "js-host". * @return {string} A unique host name */ static createHostName(prefix?: string): string { if (!prefix) prefix = "js-host"; return `${prefix}-${uuid()}`; } /** * Creates an EventProcessorHost instance from the EventHub connection string. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} storageConnectionString Connection string to Azure Storage account used for * leases and checkpointing. Example DefaultEndpointsProtocol=https;AccountName=<account-name>; * AccountKey=<account-key>;EndpointSuffix=core.windows.net * @param {string} storageContainerName Azure Storage container name for use by built-in lease * and checkpoint manager. * @param {string} eventHubConnectionString Connection string for the Event Hub to receive from. * Example: 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/; * SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' * @param {FromConnectionStringOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static createFromConnectionString( hostName: string, storageConnectionString: string, storageContainerName: string, eventHubConnectionString: string, options?: FromConnectionStringOptions): EventProcessorHost { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("storageConnectionString", storageConnectionString, true, "string"); validateType("storageContainerName", storageContainerName, true, "string"); validateType("eventHubConnectionString", eventHubConnectionString, true, "string"); validateType("options", options, false, "object"); const ephOptions: EventProcessorHostOptions = { ...options, storageConnectionString: storageConnectionString, storageContainerName: storageContainerName, eventHubConnectionString: eventHubConnectionString }; return new EventProcessorHost(hostName, ephOptions); } /** * Creates an EventProcessorHost instance from the EventHub connection string with the provided * checkpoint manager and lease manager. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} eventHubConnectionString Connection string for the Event Hub to receive from. * Example: 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/; * SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' * @param {CheckpointManager} checkpointManager A manager to manage checkpoints. * @param {LeaseManager} leaseManager A manager to manage leases. * @param {FromConnectionStringOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static createFromConnectionStringWithCustomCheckpointAndLeaseManager( hostName: string, eventHubConnectionString: string, checkpointManager: CheckpointManager, leaseManager: LeaseManager, options?: FromConnectionStringOptions): EventProcessorHost { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("eventHubConnectionString", eventHubConnectionString, true, "string"); validateType("checkpointManager", checkpointManager, true, "object"); validateType("leaseManager", leaseManager, true, "object"); validateType("options", options, false, "object"); const ephOptions: EventProcessorHostOptions = { ...options, eventHubConnectionString: eventHubConnectionString, checkpointManager: checkpointManager, leaseManager: leaseManager }; return new EventProcessorHost(hostName, ephOptions); } /** * Creates an EventProcessorHost instance from a TokenProvider. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} storageConnectionString Connection string to Azure Storage account used for * leases and checkpointing. Example DefaultEndpointsProtocol=https;AccountName=<account-name>; * AccountKey=<account-key>;EndpointSuffix=core.windows.net * @param {string} storageContainerName Azure Storage container name for use by built-in lease * and checkpoint manager. * @param {string} namespace Fully qualified domain name for Event Hubs. * Example: "{your-sb-namespace}.servicebus.windows.net" * @param {string} eventHubPath The name of the EventHub. * @param {TokenProvider} tokenProvider - Your token provider that implements the TokenProvider interface. * @param {FromTokenProviderOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static createFromTokenProvider( hostName: string, storageConnectionString: string, storageContainerName: string, namespace: string, eventHubPath: string, tokenProvider: TokenProvider, options?: FromTokenProviderOptions): EventProcessorHost { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("storageConnectionString", storageConnectionString, true, "string"); validateType("storageContainerName", storageContainerName, true, "string"); validateType("namespace", namespace, true, "string"); validateType("eventHubPath", eventHubPath, true, "string"); validateType("tokenProvider", tokenProvider, true, "object"); validateType("options", options, false, "object"); if (!namespace.endsWith("/")) namespace += "/"; const connectionString = `Endpoint=sb://${namespace};SharedAccessKeyName=defaultKeyName;` + `SharedAccessKey=defaultKeyValue;EntityPath=${eventHubPath}`; const ephOptions: EventProcessorHostOptions = { ...options, tokenProvider: tokenProvider, storageConnectionString: storageConnectionString, storageContainerName: storageContainerName, eventHubPath: eventHubPath, eventHubConnectionString: connectionString }; return new EventProcessorHost(hostName, ephOptions); } /** * Creates an EventProcessorHost instance from a TokenProvider with the provided checkpoint manager * and lease manager. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} namespace Fully qualified domain name for Event Hubs. * Example: "{your-sb-namespace}.servicebus.windows.net" * @param {string} eventHubPath The name of the EventHub. * @param {TokenProvider} tokenProvider - Your token provider that implements the TokenProvider interface. * @param {CheckpointManager} checkpointManager A manager to manage checkpoints. * @param {LeaseManager} leaseManager A manager to manage leases. * @param {FromTokenProviderOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static createFromTokenProviderWithCustomCheckpointAndLeaseManager( hostName: string, namespace: string, eventHubPath: string, tokenProvider: TokenProvider, checkpointManager: CheckpointManager, leaseManager: LeaseManager, options?: FromTokenProviderOptions): EventProcessorHost { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("namespace", namespace, true, "string"); validateType("eventHubPath", eventHubPath, true, "string"); validateType("tokenProvider", tokenProvider, true, "object"); validateType("checkpointManager", checkpointManager, true, "object"); validateType("leaseManager", leaseManager, true, "object"); validateType("options", options, false, "object"); if (!namespace.endsWith("/")) namespace += "/"; const connectionString = `Endpoint=sb://${namespace};SharedAccessKeyName=defaultKeyName;` + `SharedAccessKey=defaultKeyValue;EntityPath=${eventHubPath}`; const ephOptions: EventProcessorHostOptions = { ...options, tokenProvider: tokenProvider, eventHubPath: eventHubPath, eventHubConnectionString: connectionString, checkpointManager: checkpointManager, leaseManager: leaseManager }; return new EventProcessorHost(hostName, ephOptions); } /** * Creates an EventProcessorHost instance from AAD token credentials. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} storageConnectionString Connection string to Azure Storage account used for * leases and checkpointing. Example DefaultEndpointsProtocol=https;AccountName=<account-name>; * AccountKey=<account-key>;EndpointSuffix=core.windows.net * @param {string} storageContainerName Azure Storage container name for use by built-in lease * and checkpoint manager. * @param {string} namespace Fully qualified domain name for Event Hubs. * Example: "{your-sb-namespace}.servicebus.windows.net" * @param {string} eventHubPath The name of the EventHub. * @param {TokenCredentials} credentials - The AAD Token credentials. It can be one of the * following: ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials * | MSITokenCredentials. * @param {FromTokenProviderOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static createFromAadTokenCredentials( hostName: string, storageConnectionString: string, storageContainerName: string, namespace: string, eventHubPath: string, credentials: ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials | MSITokenCredentials, options?: FromTokenProviderOptions): EventProcessorHost { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("storageConnectionString", storageConnectionString, true, "string"); validateType("storageContainerName", storageContainerName, true, "string"); validateType("namespace", namespace, true, "string"); validateType("eventHubPath", eventHubPath, true, "string"); validateType("credentials", credentials, true, "object"); validateType("options", options, false, "object"); if (!namespace.endsWith("/")) namespace += "/"; const connectionString = `Endpoint=sb://${namespace};SharedAccessKeyName=defaultKeyName;` + `SharedAccessKey=defaultKeyValue;EntityPath=${eventHubPath}`; const ephOptions: EventProcessorHostOptions = { ...options, tokenProvider: new AadTokenProvider(credentials), storageConnectionString: storageConnectionString, storageContainerName: storageContainerName, eventHubPath: eventHubPath, eventHubConnectionString: connectionString }; return new EventProcessorHost(hostName, ephOptions); } /** * Creates an EventProcessorHost instance from AAD token credentials with the given checkpoint manager * and lease manager. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} namespace Fully qualified domain name for Event Hubs. * Example: "{your-sb-namespace}.servicebus.windows.net" * @param {string} eventHubPath The name of the EventHub. * @param {TokenCredentials} credentials - The AAD Token credentials. It can be one of the * following: ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials * | MSITokenCredentials. * @param {CheckpointManager} checkpointManager A manager to manage checkpoints. * @param {LeaseManager} leaseManager A manager to manage leases. * @param {FromTokenProviderOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static createFromAadTokenCredentialsWithCustomCheckpointAndLeaseManager( hostName: string, namespace: string, eventHubPath: string, credentials: ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials | MSITokenCredentials, checkpointManager: CheckpointManager, leaseManager: LeaseManager, options?: FromTokenProviderOptions): EventProcessorHost { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("namespace", namespace, true, "string"); validateType("eventHubPath", eventHubPath, true, "string"); validateType("credentials", credentials, true, "object"); validateType("checkpointManager", checkpointManager, true, "object"); validateType("leaseManager", leaseManager, true, "object"); validateType("options", options, false, "object"); if (!namespace.endsWith("/")) namespace += "/"; const connectionString = `Endpoint=sb://${namespace};SharedAccessKeyName=defaultKeyName;` + `SharedAccessKey=defaultKeyValue;EntityPath=${eventHubPath}`; const ephOptions: EventProcessorHostOptions = { ...options, tokenProvider: new AadTokenProvider(credentials), eventHubPath: eventHubPath, eventHubConnectionString: connectionString, checkpointManager: checkpointManager, leaseManager: leaseManager }; return new EventProcessorHost(hostName, ephOptions); } /** * Creates an EventProcessorHost instance from the IotHub connection string. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} storageConnectionString Connection string to Azure Storage account used for * leases and checkpointing. Example DefaultEndpointsProtocol=https;AccountName=<account-name>; * AccountKey=<account-key>;EndpointSuffix=core.windows.net * @param {string} storageContainerName Azure Storage container name for use by built-in lease * and checkpoint manager. * @param {string} iotHubConnectionString Connection string for the IotHub. * Example: 'Endpoint=iot-host-name;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' * @param {FromIotHubConnectionStringOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static async createFromIotHubConnectionString( hostName: string, storageConnectionString: string, storageContainerName: string, iotHubConnectionString: string, options?: FromIotHubConnectionStringOptions): Promise<EventProcessorHost> { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("storageConnectionString", storageConnectionString, true, "string"); validateType("storageContainerName", storageContainerName, true, "string"); validateType("iotHubConnectionString", iotHubConnectionString, true, "string"); validateType("options", options, false, "object"); const client = await EventHubClient.createFromIotHubConnectionString(iotHubConnectionString); /* tslint:disable:no-string-literal */ const eventHubConnectionString = client["_context"].config.connectionString; const ephOptions: EventProcessorHostOptions = { ...options, storageConnectionString: storageConnectionString, storageContainerName: storageContainerName, eventHubConnectionString: eventHubConnectionString, eventHubPath: client.eventhubName }; return new EventProcessorHost(hostName, ephOptions); } /** * Creates an EventProcessorHost instance from the IotHub connection string with the given * checkpoint manager and lease manager. * * @param {string} hostName Name of the processor host. MUST BE UNIQUE. * Strongly recommend including a Guid or a prefix with a guid to ensure uniqueness. You can use * `EventProcessorHost.createHostName("your-prefix")`; Default: `js-host-${uuid()}`. * @param {string} iotHubConnectionString Connection string for the IotHub. * Example: 'Endpoint=iot-host-name;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' * @param {CheckpointManager} checkpointManager A manager to manage checkpoints. * @param {LeaseManager} leaseManager A manager to manage leases. * @param {FromIotHubConnectionStringOptions} [options] Optional parameters for creating an * EventProcessorHost. * * @returns {EventProcessorHost} EventProcessorHost */ static async createFromIotHubConnectionStringWithCustomCheckpointAndLeaseManager( hostName: string, iotHubConnectionString: string, checkpointManager: CheckpointManager, leaseManager: LeaseManager, options?: FromIotHubConnectionStringOptions): Promise<EventProcessorHost> { if (!options) options = {}; validateType("hostName", hostName, true, "string"); validateType("iotHubConnectionString", iotHubConnectionString, true, "string"); validateType("checkpointManager", checkpointManager, true, "object"); validateType("leaseManager", leaseManager, true, "object"); validateType("options", options, false, "object"); const client = await EventHubClient.createFromIotHubConnectionString(iotHubConnectionString); /* tslint:disable:no-string-literal */ const eventHubConnectionString = client["_context"].config.connectionString; const ephOptions: EventProcessorHostOptions = { ...options, eventHubConnectionString: eventHubConnectionString, checkpointManager: checkpointManager, leaseManager: leaseManager, eventHubPath: client.eventhubName }; return new EventProcessorHost(hostName, ephOptions); } }
the_stack
* @author Richard <richardo2016@gmail.com> * */ /// <reference path="Buffer.d.ts" /> /// <reference path="BufferedStream.d.ts" /> /// <reference path="Chain.d.ts" /> /// <reference path="Cipher.d.ts" /> /// <reference path="Condition.d.ts" /> /// <reference path="DbConnection.d.ts" /> /// <reference path="DgramSocket.d.ts" /> /// <reference path="Digest.d.ts" /> /// <reference path="Event.d.ts" /> /// <reference path="EventEmitter.d.ts" /> /// <reference path="EventInfo.d.ts" /> /// <reference path="Fiber.d.ts" /> /// <reference path="File.d.ts" /> /// <reference path="Handler.d.ts" /> /// <reference path="HandlerEx.d.ts" /> /// <reference path="HeapGraphEdge.d.ts" /> /// <reference path="HeapGraphNode.d.ts" /> /// <reference path="HeapSnapshot.d.ts" /> /// <reference path="HttpClient.d.ts" /> /// <reference path="HttpCollection.d.ts" /> /// <reference path="HttpCookie.d.ts" /> /// <reference path="HttpHandler.d.ts" /> /// <reference path="HttpMessage.d.ts" /> /// <reference path="HttpRequest.d.ts" /> /// <reference path="HttpResponse.d.ts" /> /// <reference path="HttpServer.d.ts" /> /// <reference path="HttpUploadData.d.ts" /> /// <reference path="HttpsServer.d.ts" /> /// <reference path="Image.d.ts" /> /// <reference path="Int64.d.ts" /> /// <reference path="LevelDB.d.ts" /> /// <reference path="Lock.d.ts" /> /// <reference path="LruCache.d.ts" /> /// <reference path="MSSQL.d.ts" /> /// <reference path="MemoryStream.d.ts" /> /// <reference path="Message.d.ts" /> /// <reference path="MongoCollection.d.ts" /> /// <reference path="MongoCursor.d.ts" /> /// <reference path="MongoDB.d.ts" /> /// <reference path="MongoID.d.ts" /> /// <reference path="MySQL.d.ts" /> /// <reference path="PKey.d.ts" /> /// <reference path="Redis.d.ts" /> /// <reference path="RedisHash.d.ts" /> /// <reference path="RedisList.d.ts" /> /// <reference path="RedisSet.d.ts" /> /// <reference path="RedisSortedSet.d.ts" /> /// <reference path="Routing.d.ts" /> /// <reference path="SQLite.d.ts" /> /// <reference path="SandBox.d.ts" /> /// <reference path="SeekableStream.d.ts" /> /// <reference path="Semaphore.d.ts" /> /// <reference path="Service.d.ts" /> /// <reference path="Smtp.d.ts" /> /// <reference path="Socket.d.ts" /> /// <reference path="SslHandler.d.ts" /> /// <reference path="SslServer.d.ts" /> /// <reference path="SslSocket.d.ts" /> /// <reference path="Stat.d.ts" /> /// <reference path="Stats.d.ts" /> /// <reference path="Stream.d.ts" /> /// <reference path="StringDecoder.d.ts" /> /// <reference path="SubProcess.d.ts" /> /// <reference path="TcpServer.d.ts" /> /// <reference path="Timer.d.ts" /> /// <reference path="UrlObject.d.ts" /> /// <reference path="WebSocket.d.ts" /> /// <reference path="WebSocketMessage.d.ts" /> /// <reference path="WebView.d.ts" /> /// <reference path="Worker.d.ts" /> /// <reference path="X509Cert.d.ts" /> /// <reference path="X509Crl.d.ts" /> /// <reference path="X509Req.d.ts" /> /// <reference path="XmlAttr.d.ts" /> /// <reference path="XmlCDATASection.d.ts" /> /// <reference path="XmlCharacterData.d.ts" /> /// <reference path="XmlComment.d.ts" /> /// <reference path="XmlDocument.d.ts" /> /// <reference path="XmlDocumentType.d.ts" /> /// <reference path="XmlElement.d.ts" /> /// <reference path="XmlNamedNodeMap.d.ts" /> /// <reference path="XmlNode.d.ts" /> /// <reference path="XmlNodeList.d.ts" /> /// <reference path="XmlProcessingInstruction.d.ts" /> /// <reference path="XmlText.d.ts" /> /// <reference path="ZipFile.d.ts" /> /// <reference path="ZmqSocket.d.ts" /> /// <reference path="object.d.ts" /> /** module Or Internal Object */ /** * @brief 加密算法模块 * @detail 使用方法:,```JavaScript,var crypto = require('crypto');,``` */ declare module "crypto" { module crypto { /** * * @brief 指定对称加密算法 AES,支持 128, 192, 256 位 key,分组密码工作模式支持 ECB, CBC, CFB128, CTR, GCM * * */ export const AES = 1; /** * * @brief 指定对称加密算法 CAMELLIA,支持 128, 192, 256 位 key,分组密码工作模式支持 ECB, CBC, CFB128, CTR, GCM * * */ export const CAMELLIA = 2; /** * * @brief 指定对称加密算法 DES,支持 64 位 key,分组密码工作模式支持 ECB, CBC * * */ export const DES = 3; /** * * @brief 指定对称加密算法 DES-EDE,支持 128 位 key,分组密码工作模式支持 ECB, CBC * * */ export const DES_EDE = 4; /** * * @brief 指定对称加密算法 DES-EDE3,支持 192 位 key,分组密码工作模式支持 ECB, CBC * * */ export const DES_EDE3 = 5; /** * * @brief 指定对称加密算法 BLOWFISH,支持 192 位 key,分组密码工作模式支持 ECB, CBC, CFB64, CTR * * */ export const BLOWFISH = 6; /** * * @brief 指定对称加密算法 ARC4,支持 40, 56, 64, 128 位 key * * */ export const ARC4 = 7; /** * * @brief 指定分组密码工作模式支持 ECB * * */ export const ECB = 1; /** * * @brief 指定分组密码工作模式支持 CBC * * */ export const CBC = 2; /** * * @brief 指定分组密码工作模式支持 CFB64 * * */ export const CFB64 = 3; /** * * @brief 指定分组密码工作模式支持 CFB128 * * */ export const CFB128 = 4; /** * * @brief 指定分组密码工作模式支持 OFB * * */ export const OFB = 5; /** * * @brief 指定分组密码工作模式支持 CTR * * */ export const CTR = 6; /** * * @brief 指定分组密码工作模式支持 GCM * * */ export const GCM = 7; /** * * @brief 指定流密码模式 * * */ export const STREAM = 8; /** * * @brief 指定分组密码工作模式支持 CCM * * */ export const CCM = 9; /** * * @brief 指定填充模式为 PKCS7 * * */ export const PKCS7 = 0; /** * * @brief 指定填充模式为 ONE_AND_ZEROS * * */ export const ONE_AND_ZEROS = 1; /** * * @brief 指定填充模式为 ZEROS_AND_LEN * * */ export const ZEROS_AND_LEN = 2; /** * * @brief 指定填充模式为 ZEROS * * */ export const ZEROS = 3; /** * * @brief 指定填充模式为 NOPADDING * * */ export const NOPADDING = 4; /** * * @brief Cipher 构造函数,参见 Cipher * * */ export class Cipher extends Class_Cipher {} /** * * @brief PKey 构造函数,参见 PKey * * */ export class PKey extends Class_PKey {} /** * * @brief X509Cert 构造函数,参见 X509Cert * * */ export class X509Cert extends Class_X509Cert {} /** * * @brief X509Crl 构造函数,参见 X509Crl * * */ export class X509Crl extends Class_X509Crl {} /** * * @brief X509Req 构造函数,参见 X509Req * * */ export class X509Req extends Class_X509Req {} /** * * @brief 根据给定的算法名称创建一个信息摘要对象 * @param algo 指定信息摘要对象的算法 * @return 返回信息摘要对象 * * * */ export function createHash(algo: string): Class_Digest; /** * * @brief 根据给定的算法名称创建一个 hmac 信息摘要对象 * @param algo 指定信息摘要对象的算法 * @param key 二进制签名密钥 * @return 返回信息摘要对象 * * * */ export function createHmac(algo: string, key: Class_Buffer): Class_Digest; /** * * @brief 加载一个 PEM/DER 格式的密钥文件 * @param filename 密钥文件名 * @param password 解密密码 * @return 返回包含密钥的对象 * * * */ export function loadPKey(filename: string, password?: string/** = ""*/): Class_PKey; /** * * @brief 加载一个 CRT/PEM/DER/TXT 格式的证书,可多次调用 * * loadFile 加载 mozilla 的 certdata,txt, 可于 http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt 下载使用 * @param filename 证书文件名 * @return 返回包含证书的对象 * * * */ export function loadCert(filename: string): Class_X509Cert; /** * * @brief 加载一个 PEM/DER 格式的撤销证书,可多次调用 * @param filename 撤销证书文件名 * @return 返回包含撤销证书的对象 * * * */ export function loadCrl(filename: string): Class_X509Crl; /** * * @brief 加载一个 PEM/DER 格式的证书请求,可多次调用 * @param filename 证书请求文件名 * @return 返回包含请求证书的对象 * * * */ export function loadReq(filename: string): Class_X509Req; /** * * @brief 生成指定尺寸的随机数,使用 havege 生成器 * @param size 指定生成的随机数尺寸 * @return 返回生成的随机数 * * * @async */ export function randomBytes(size: number): Class_Buffer; /** * * @brief 生成指定尺寸的低强度随机数,使用快速的算法 * @param size 指定生成的随机数尺寸 * @return 返回生成的随机数 * * * @async */ export function simpleRandomBytes(size: number): Class_Buffer; /** * * @brief 生成指定尺寸的伪随机数,使用 entropy 生成器 * @param size 指定生成的随机数尺寸 * @return 返回生成的随机数 * * * @async */ export function pseudoRandomBytes(size: number): Class_Buffer; /** * * @brief 生成给定数据的可视化字符图像 * @param data 指定要展示的数据 * @param title 指定字符图像的标题,多字节字符会导致宽度错误 * @param size 字符图像尺寸 * @return 返回生成的可视化字符串图像 * * * */ export function randomArt(data: Class_Buffer, title: string, size?: number/** = 8*/): string; /** * * @brief 依据 pbkdf1 根据明文 password 生成要求的二进制钥匙 * @param password 指定使用的密码 * @param salt 指定 hmac 使用的 salt * @param iterations 指定迭代次数 * @param size 指定钥匙尺寸 * @param algo 指定要使用的 hash 算法,详见 hash 模块 * @return 返回生成的二进制钥匙 * * * @async */ export function pbkdf1(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algo: number): Class_Buffer; /** * * @brief 依据 pbkdf1 根据明文 password 生成要求的二进制钥匙 * @param password 指定使用的密码 * @param salt 指定 hmac 使用的 salt * @param iterations 指定迭代次数 * @param size 指定钥匙尺寸 * @param algoName 指定要使用的 hash 算法,详见 hash 模块 * @return 返回生成的二进制钥匙 * * * @async */ export function pbkdf1(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algoName: string): Class_Buffer; /** * * @brief 依据 rfc2898 根据明文 password 生成要求的二进制钥匙 * @param password 指定使用的密码 * @param salt 指定 hmac 使用的 salt * @param iterations 指定迭代次数 * @param size 指定钥匙尺寸 * @param algo 指定要使用的 hash 算法,详见 hash 模块 * @return 返回生成的二进制钥匙 * * * @async */ export function pbkdf2(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algo: number): Class_Buffer; /** * * @brief 依据 rfc2898 根据明文 password 生成要求的二进制钥匙 * @param password 指定使用的密码 * @param salt 指定 hmac 使用的 salt * @param iterations 指定迭代次数 * @param size 指定钥匙尺寸 * @param algoName 指定要使用的 hash 算法,详见 hash 模块 * @return 返回生成的二进制钥匙 * * * @async */ export function pbkdf2(password: Class_Buffer, salt: Class_Buffer, iterations: number, size: number, algoName: string): Class_Buffer; } /** end of `module crypto` */ export = crypto } /** endof `module Or Internal Object` */
the_stack
import Long from "long"; import _m0 from "protobufjs/minimal"; import { Any } from "../../google/protobuf/any"; export const protobufPackage = "gravity.v1"; /** * EthereumEventVoteRecord is an event that is pending of confirmation by 2/3 of * the signer set. The event is then attested and executed in the state machine * once the required threshold is met. */ export interface EthereumEventVoteRecord { event?: Any; votes: string[]; accepted: boolean; } /** * LatestEthereumBlockHeight defines the latest observed ethereum block height * and the corresponding timestamp value in nanoseconds. */ export interface LatestEthereumBlockHeight { ethereumHeight: Long; cosmosHeight: Long; } /** * EthereumSigner represents a cosmos validator with its corresponding bridge * operator ethereum address and its staking consensus power. */ export interface EthereumSigner { power: Long; ethereumAddress: string; } /** * SignerSetTx is the Ethereum Bridge multisig set that relays * transactions the two chains. The staking validators keep ethereum keys which * are used to check signatures on Ethereum in order to get significant gas * savings. */ export interface SignerSetTx { nonce: Long; height: Long; signers: EthereumSigner[]; } /** * BatchTx represents a batch of transactions going from Cosmos to Ethereum. * Batch txs are are identified by a unique hash and the token contract that is * shared by all the SendToEthereum */ export interface BatchTx { batchNonce: Long; timeout: Long; transactions: SendToEthereum[]; tokenContract: string; height: Long; } /** * SendToEthereum represents an individual SendToEthereum from Cosmos to * Ethereum */ export interface SendToEthereum { id: Long; sender: string; ethereumRecipient: string; erc20Token?: ERC20Token; erc20Fee?: ERC20Token; } /** * ContractCallTx represents an individual arbitratry logic call transaction * from Cosmos to Ethereum. */ export interface ContractCallTx { invalidationNonce: Long; invalidationScope: Uint8Array; address: string; payload: Uint8Array; timeout: Long; tokens: ERC20Token[]; fees: ERC20Token[]; height: Long; } export interface ERC20Token { contract: string; amount: string; } export interface IDSet { ids: Long[]; } const baseEthereumEventVoteRecord: object = { votes: "", accepted: false }; export const EthereumEventVoteRecord = { encode( message: EthereumEventVoteRecord, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.event !== undefined) { Any.encode(message.event, writer.uint32(10).fork()).ldelim(); } for (const v of message.votes) { writer.uint32(18).string(v!); } if (message.accepted === true) { writer.uint32(24).bool(message.accepted); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): EthereumEventVoteRecord { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseEthereumEventVoteRecord, } as EthereumEventVoteRecord; message.votes = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.event = Any.decode(reader, reader.uint32()); break; case 2: message.votes.push(reader.string()); break; case 3: message.accepted = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): EthereumEventVoteRecord { const message = { ...baseEthereumEventVoteRecord, } as EthereumEventVoteRecord; message.votes = []; if (object.event !== undefined && object.event !== null) { message.event = Any.fromJSON(object.event); } else { message.event = undefined; } if (object.votes !== undefined && object.votes !== null) { for (const e of object.votes) { message.votes.push(String(e)); } } if (object.accepted !== undefined && object.accepted !== null) { message.accepted = Boolean(object.accepted); } else { message.accepted = false; } return message; }, toJSON(message: EthereumEventVoteRecord): unknown { const obj: any = {}; message.event !== undefined && (obj.event = message.event ? Any.toJSON(message.event) : undefined); if (message.votes) { obj.votes = message.votes.map((e) => e); } else { obj.votes = []; } message.accepted !== undefined && (obj.accepted = message.accepted); return obj; }, fromPartial( object: DeepPartial<EthereumEventVoteRecord> ): EthereumEventVoteRecord { const message = { ...baseEthereumEventVoteRecord, } as EthereumEventVoteRecord; message.votes = []; if (object.event !== undefined && object.event !== null) { message.event = Any.fromPartial(object.event); } else { message.event = undefined; } if (object.votes !== undefined && object.votes !== null) { for (const e of object.votes) { message.votes.push(e); } } if (object.accepted !== undefined && object.accepted !== null) { message.accepted = object.accepted; } else { message.accepted = false; } return message; }, }; const baseLatestEthereumBlockHeight: object = { ethereumHeight: Long.UZERO, cosmosHeight: Long.UZERO, }; export const LatestEthereumBlockHeight = { encode( message: LatestEthereumBlockHeight, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.ethereumHeight.isZero()) { writer.uint32(8).uint64(message.ethereumHeight); } if (!message.cosmosHeight.isZero()) { writer.uint32(16).uint64(message.cosmosHeight); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): LatestEthereumBlockHeight { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseLatestEthereumBlockHeight, } as LatestEthereumBlockHeight; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ethereumHeight = reader.uint64() as Long; break; case 2: message.cosmosHeight = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): LatestEthereumBlockHeight { const message = { ...baseLatestEthereumBlockHeight, } as LatestEthereumBlockHeight; if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = Long.fromString(object.ethereumHeight); } else { message.ethereumHeight = Long.UZERO; } if (object.cosmosHeight !== undefined && object.cosmosHeight !== null) { message.cosmosHeight = Long.fromString(object.cosmosHeight); } else { message.cosmosHeight = Long.UZERO; } return message; }, toJSON(message: LatestEthereumBlockHeight): unknown { const obj: any = {}; message.ethereumHeight !== undefined && (obj.ethereumHeight = (message.ethereumHeight || Long.UZERO).toString()); message.cosmosHeight !== undefined && (obj.cosmosHeight = (message.cosmosHeight || Long.UZERO).toString()); return obj; }, fromPartial( object: DeepPartial<LatestEthereumBlockHeight> ): LatestEthereumBlockHeight { const message = { ...baseLatestEthereumBlockHeight, } as LatestEthereumBlockHeight; if (object.ethereumHeight !== undefined && object.ethereumHeight !== null) { message.ethereumHeight = object.ethereumHeight as Long; } else { message.ethereumHeight = Long.UZERO; } if (object.cosmosHeight !== undefined && object.cosmosHeight !== null) { message.cosmosHeight = object.cosmosHeight as Long; } else { message.cosmosHeight = Long.UZERO; } return message; }, }; const baseEthereumSigner: object = { power: Long.UZERO, ethereumAddress: "" }; export const EthereumSigner = { encode( message: EthereumSigner, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.power.isZero()) { writer.uint32(8).uint64(message.power); } if (message.ethereumAddress !== "") { writer.uint32(18).string(message.ethereumAddress); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): EthereumSigner { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseEthereumSigner } as EthereumSigner; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.power = reader.uint64() as Long; break; case 2: message.ethereumAddress = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): EthereumSigner { const message = { ...baseEthereumSigner } as EthereumSigner; if (object.power !== undefined && object.power !== null) { message.power = Long.fromString(object.power); } else { message.power = Long.UZERO; } if ( object.ethereumAddress !== undefined && object.ethereumAddress !== null ) { message.ethereumAddress = String(object.ethereumAddress); } else { message.ethereumAddress = ""; } return message; }, toJSON(message: EthereumSigner): unknown { const obj: any = {}; message.power !== undefined && (obj.power = (message.power || Long.UZERO).toString()); message.ethereumAddress !== undefined && (obj.ethereumAddress = message.ethereumAddress); return obj; }, fromPartial(object: DeepPartial<EthereumSigner>): EthereumSigner { const message = { ...baseEthereumSigner } as EthereumSigner; if (object.power !== undefined && object.power !== null) { message.power = object.power as Long; } else { message.power = Long.UZERO; } if ( object.ethereumAddress !== undefined && object.ethereumAddress !== null ) { message.ethereumAddress = object.ethereumAddress; } else { message.ethereumAddress = ""; } return message; }, }; const baseSignerSetTx: object = { nonce: Long.UZERO, height: Long.UZERO }; export const SignerSetTx = { encode( message: SignerSetTx, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.nonce.isZero()) { writer.uint32(8).uint64(message.nonce); } if (!message.height.isZero()) { writer.uint32(16).uint64(message.height); } for (const v of message.signers) { EthereumSigner.encode(v!, writer.uint32(26).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): SignerSetTx { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSignerSetTx } as SignerSetTx; message.signers = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.nonce = reader.uint64() as Long; break; case 2: message.height = reader.uint64() as Long; break; case 3: message.signers.push(EthereumSigner.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SignerSetTx { const message = { ...baseSignerSetTx } as SignerSetTx; message.signers = []; if (object.nonce !== undefined && object.nonce !== null) { message.nonce = Long.fromString(object.nonce); } else { message.nonce = Long.UZERO; } if (object.height !== undefined && object.height !== null) { message.height = Long.fromString(object.height); } else { message.height = Long.UZERO; } if (object.signers !== undefined && object.signers !== null) { for (const e of object.signers) { message.signers.push(EthereumSigner.fromJSON(e)); } } return message; }, toJSON(message: SignerSetTx): unknown { const obj: any = {}; message.nonce !== undefined && (obj.nonce = (message.nonce || Long.UZERO).toString()); message.height !== undefined && (obj.height = (message.height || Long.UZERO).toString()); if (message.signers) { obj.signers = message.signers.map((e) => e ? EthereumSigner.toJSON(e) : undefined ); } else { obj.signers = []; } return obj; }, fromPartial(object: DeepPartial<SignerSetTx>): SignerSetTx { const message = { ...baseSignerSetTx } as SignerSetTx; message.signers = []; if (object.nonce !== undefined && object.nonce !== null) { message.nonce = object.nonce as Long; } else { message.nonce = Long.UZERO; } if (object.height !== undefined && object.height !== null) { message.height = object.height as Long; } else { message.height = Long.UZERO; } if (object.signers !== undefined && object.signers !== null) { for (const e of object.signers) { message.signers.push(EthereumSigner.fromPartial(e)); } } return message; }, }; const baseBatchTx: object = { batchNonce: Long.UZERO, timeout: Long.UZERO, tokenContract: "", height: Long.UZERO, }; export const BatchTx = { encode( message: BatchTx, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.batchNonce.isZero()) { writer.uint32(8).uint64(message.batchNonce); } if (!message.timeout.isZero()) { writer.uint32(16).uint64(message.timeout); } for (const v of message.transactions) { SendToEthereum.encode(v!, writer.uint32(26).fork()).ldelim(); } if (message.tokenContract !== "") { writer.uint32(34).string(message.tokenContract); } if (!message.height.isZero()) { writer.uint32(40).uint64(message.height); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): BatchTx { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseBatchTx } as BatchTx; message.transactions = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.batchNonce = reader.uint64() as Long; break; case 2: message.timeout = reader.uint64() as Long; break; case 3: message.transactions.push( SendToEthereum.decode(reader, reader.uint32()) ); break; case 4: message.tokenContract = reader.string(); break; case 5: message.height = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): BatchTx { const message = { ...baseBatchTx } as BatchTx; message.transactions = []; if (object.batchNonce !== undefined && object.batchNonce !== null) { message.batchNonce = Long.fromString(object.batchNonce); } else { message.batchNonce = Long.UZERO; } if (object.timeout !== undefined && object.timeout !== null) { message.timeout = Long.fromString(object.timeout); } else { message.timeout = Long.UZERO; } if (object.transactions !== undefined && object.transactions !== null) { for (const e of object.transactions) { message.transactions.push(SendToEthereum.fromJSON(e)); } } if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = String(object.tokenContract); } else { message.tokenContract = ""; } if (object.height !== undefined && object.height !== null) { message.height = Long.fromString(object.height); } else { message.height = Long.UZERO; } return message; }, toJSON(message: BatchTx): unknown { const obj: any = {}; message.batchNonce !== undefined && (obj.batchNonce = (message.batchNonce || Long.UZERO).toString()); message.timeout !== undefined && (obj.timeout = (message.timeout || Long.UZERO).toString()); if (message.transactions) { obj.transactions = message.transactions.map((e) => e ? SendToEthereum.toJSON(e) : undefined ); } else { obj.transactions = []; } message.tokenContract !== undefined && (obj.tokenContract = message.tokenContract); message.height !== undefined && (obj.height = (message.height || Long.UZERO).toString()); return obj; }, fromPartial(object: DeepPartial<BatchTx>): BatchTx { const message = { ...baseBatchTx } as BatchTx; message.transactions = []; if (object.batchNonce !== undefined && object.batchNonce !== null) { message.batchNonce = object.batchNonce as Long; } else { message.batchNonce = Long.UZERO; } if (object.timeout !== undefined && object.timeout !== null) { message.timeout = object.timeout as Long; } else { message.timeout = Long.UZERO; } if (object.transactions !== undefined && object.transactions !== null) { for (const e of object.transactions) { message.transactions.push(SendToEthereum.fromPartial(e)); } } if (object.tokenContract !== undefined && object.tokenContract !== null) { message.tokenContract = object.tokenContract; } else { message.tokenContract = ""; } if (object.height !== undefined && object.height !== null) { message.height = object.height as Long; } else { message.height = Long.UZERO; } return message; }, }; const baseSendToEthereum: object = { id: Long.UZERO, sender: "", ethereumRecipient: "", }; export const SendToEthereum = { encode( message: SendToEthereum, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.id.isZero()) { writer.uint32(8).uint64(message.id); } if (message.sender !== "") { writer.uint32(18).string(message.sender); } if (message.ethereumRecipient !== "") { writer.uint32(26).string(message.ethereumRecipient); } if (message.erc20Token !== undefined) { ERC20Token.encode(message.erc20Token, writer.uint32(34).fork()).ldelim(); } if (message.erc20Fee !== undefined) { ERC20Token.encode(message.erc20Fee, writer.uint32(42).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): SendToEthereum { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSendToEthereum } as SendToEthereum; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.uint64() as Long; break; case 2: message.sender = reader.string(); break; case 3: message.ethereumRecipient = reader.string(); break; case 4: message.erc20Token = ERC20Token.decode(reader, reader.uint32()); break; case 5: message.erc20Fee = ERC20Token.decode(reader, reader.uint32()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SendToEthereum { const message = { ...baseSendToEthereum } as SendToEthereum; if (object.id !== undefined && object.id !== null) { message.id = Long.fromString(object.id); } else { message.id = Long.UZERO; } if (object.sender !== undefined && object.sender !== null) { message.sender = String(object.sender); } else { message.sender = ""; } if ( object.ethereumRecipient !== undefined && object.ethereumRecipient !== null ) { message.ethereumRecipient = String(object.ethereumRecipient); } else { message.ethereumRecipient = ""; } if (object.erc20Token !== undefined && object.erc20Token !== null) { message.erc20Token = ERC20Token.fromJSON(object.erc20Token); } else { message.erc20Token = undefined; } if (object.erc20Fee !== undefined && object.erc20Fee !== null) { message.erc20Fee = ERC20Token.fromJSON(object.erc20Fee); } else { message.erc20Fee = undefined; } return message; }, toJSON(message: SendToEthereum): unknown { const obj: any = {}; message.id !== undefined && (obj.id = (message.id || Long.UZERO).toString()); message.sender !== undefined && (obj.sender = message.sender); message.ethereumRecipient !== undefined && (obj.ethereumRecipient = message.ethereumRecipient); message.erc20Token !== undefined && (obj.erc20Token = message.erc20Token ? ERC20Token.toJSON(message.erc20Token) : undefined); message.erc20Fee !== undefined && (obj.erc20Fee = message.erc20Fee ? ERC20Token.toJSON(message.erc20Fee) : undefined); return obj; }, fromPartial(object: DeepPartial<SendToEthereum>): SendToEthereum { const message = { ...baseSendToEthereum } as SendToEthereum; if (object.id !== undefined && object.id !== null) { message.id = object.id as Long; } else { message.id = Long.UZERO; } if (object.sender !== undefined && object.sender !== null) { message.sender = object.sender; } else { message.sender = ""; } if ( object.ethereumRecipient !== undefined && object.ethereumRecipient !== null ) { message.ethereumRecipient = object.ethereumRecipient; } else { message.ethereumRecipient = ""; } if (object.erc20Token !== undefined && object.erc20Token !== null) { message.erc20Token = ERC20Token.fromPartial(object.erc20Token); } else { message.erc20Token = undefined; } if (object.erc20Fee !== undefined && object.erc20Fee !== null) { message.erc20Fee = ERC20Token.fromPartial(object.erc20Fee); } else { message.erc20Fee = undefined; } return message; }, }; const baseContractCallTx: object = { invalidationNonce: Long.UZERO, address: "", timeout: Long.UZERO, height: Long.UZERO, }; export const ContractCallTx = { encode( message: ContractCallTx, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (!message.invalidationNonce.isZero()) { writer.uint32(8).uint64(message.invalidationNonce); } if (message.invalidationScope.length !== 0) { writer.uint32(18).bytes(message.invalidationScope); } if (message.address !== "") { writer.uint32(26).string(message.address); } if (message.payload.length !== 0) { writer.uint32(34).bytes(message.payload); } if (!message.timeout.isZero()) { writer.uint32(40).uint64(message.timeout); } for (const v of message.tokens) { ERC20Token.encode(v!, writer.uint32(50).fork()).ldelim(); } for (const v of message.fees) { ERC20Token.encode(v!, writer.uint32(58).fork()).ldelim(); } if (!message.height.isZero()) { writer.uint32(64).uint64(message.height); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ContractCallTx { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseContractCallTx } as ContractCallTx; message.tokens = []; message.fees = []; message.invalidationScope = new Uint8Array(); message.payload = new Uint8Array(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.invalidationNonce = reader.uint64() as Long; break; case 2: message.invalidationScope = reader.bytes(); break; case 3: message.address = reader.string(); break; case 4: message.payload = reader.bytes(); break; case 5: message.timeout = reader.uint64() as Long; break; case 6: message.tokens.push(ERC20Token.decode(reader, reader.uint32())); break; case 7: message.fees.push(ERC20Token.decode(reader, reader.uint32())); break; case 8: message.height = reader.uint64() as Long; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ContractCallTx { const message = { ...baseContractCallTx } as ContractCallTx; message.tokens = []; message.fees = []; message.invalidationScope = new Uint8Array(); message.payload = new Uint8Array(); if ( object.invalidationNonce !== undefined && object.invalidationNonce !== null ) { message.invalidationNonce = Long.fromString(object.invalidationNonce); } else { message.invalidationNonce = Long.UZERO; } if ( object.invalidationScope !== undefined && object.invalidationScope !== null ) { message.invalidationScope = bytesFromBase64(object.invalidationScope); } if (object.address !== undefined && object.address !== null) { message.address = String(object.address); } else { message.address = ""; } if (object.payload !== undefined && object.payload !== null) { message.payload = bytesFromBase64(object.payload); } if (object.timeout !== undefined && object.timeout !== null) { message.timeout = Long.fromString(object.timeout); } else { message.timeout = Long.UZERO; } if (object.tokens !== undefined && object.tokens !== null) { for (const e of object.tokens) { message.tokens.push(ERC20Token.fromJSON(e)); } } if (object.fees !== undefined && object.fees !== null) { for (const e of object.fees) { message.fees.push(ERC20Token.fromJSON(e)); } } if (object.height !== undefined && object.height !== null) { message.height = Long.fromString(object.height); } else { message.height = Long.UZERO; } return message; }, toJSON(message: ContractCallTx): unknown { const obj: any = {}; message.invalidationNonce !== undefined && (obj.invalidationNonce = ( message.invalidationNonce || Long.UZERO ).toString()); message.invalidationScope !== undefined && (obj.invalidationScope = base64FromBytes( message.invalidationScope !== undefined ? message.invalidationScope : new Uint8Array() )); message.address !== undefined && (obj.address = message.address); message.payload !== undefined && (obj.payload = base64FromBytes( message.payload !== undefined ? message.payload : new Uint8Array() )); message.timeout !== undefined && (obj.timeout = (message.timeout || Long.UZERO).toString()); if (message.tokens) { obj.tokens = message.tokens.map((e) => e ? ERC20Token.toJSON(e) : undefined ); } else { obj.tokens = []; } if (message.fees) { obj.fees = message.fees.map((e) => e ? ERC20Token.toJSON(e) : undefined ); } else { obj.fees = []; } message.height !== undefined && (obj.height = (message.height || Long.UZERO).toString()); return obj; }, fromPartial(object: DeepPartial<ContractCallTx>): ContractCallTx { const message = { ...baseContractCallTx } as ContractCallTx; message.tokens = []; message.fees = []; if ( object.invalidationNonce !== undefined && object.invalidationNonce !== null ) { message.invalidationNonce = object.invalidationNonce as Long; } else { message.invalidationNonce = Long.UZERO; } if ( object.invalidationScope !== undefined && object.invalidationScope !== null ) { message.invalidationScope = object.invalidationScope; } else { message.invalidationScope = new Uint8Array(); } if (object.address !== undefined && object.address !== null) { message.address = object.address; } else { message.address = ""; } if (object.payload !== undefined && object.payload !== null) { message.payload = object.payload; } else { message.payload = new Uint8Array(); } if (object.timeout !== undefined && object.timeout !== null) { message.timeout = object.timeout as Long; } else { message.timeout = Long.UZERO; } if (object.tokens !== undefined && object.tokens !== null) { for (const e of object.tokens) { message.tokens.push(ERC20Token.fromPartial(e)); } } if (object.fees !== undefined && object.fees !== null) { for (const e of object.fees) { message.fees.push(ERC20Token.fromPartial(e)); } } if (object.height !== undefined && object.height !== null) { message.height = object.height as Long; } else { message.height = Long.UZERO; } return message; }, }; const baseERC20Token: object = { contract: "", amount: "" }; export const ERC20Token = { encode( message: ERC20Token, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.contract !== "") { writer.uint32(10).string(message.contract); } if (message.amount !== "") { writer.uint32(18).string(message.amount); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ERC20Token { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseERC20Token } as ERC20Token; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.contract = reader.string(); break; case 2: message.amount = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ERC20Token { const message = { ...baseERC20Token } as ERC20Token; if (object.contract !== undefined && object.contract !== null) { message.contract = String(object.contract); } else { message.contract = ""; } if (object.amount !== undefined && object.amount !== null) { message.amount = String(object.amount); } else { message.amount = ""; } return message; }, toJSON(message: ERC20Token): unknown { const obj: any = {}; message.contract !== undefined && (obj.contract = message.contract); message.amount !== undefined && (obj.amount = message.amount); return obj; }, fromPartial(object: DeepPartial<ERC20Token>): ERC20Token { const message = { ...baseERC20Token } as ERC20Token; if (object.contract !== undefined && object.contract !== null) { message.contract = object.contract; } else { message.contract = ""; } if (object.amount !== undefined && object.amount !== null) { message.amount = object.amount; } else { message.amount = ""; } return message; }, }; const baseIDSet: object = { ids: Long.UZERO }; export const IDSet = { encode(message: IDSet, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { writer.uint32(10).fork(); for (const v of message.ids) { writer.uint64(v); } writer.ldelim(); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): IDSet { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseIDSet } as IDSet; message.ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: if ((tag & 7) === 2) { const end2 = reader.uint32() + reader.pos; while (reader.pos < end2) { message.ids.push(reader.uint64() as Long); } } else { message.ids.push(reader.uint64() as Long); } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): IDSet { const message = { ...baseIDSet } as IDSet; message.ids = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(Long.fromString(e)); } } return message; }, toJSON(message: IDSet): unknown { const obj: any = {}; if (message.ids) { obj.ids = message.ids.map((e) => (e || Long.UZERO).toString()); } else { obj.ids = []; } return obj; }, fromPartial(object: DeepPartial<IDSet>): IDSet { const message = { ...baseIDSet } as IDSet; message.ids = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(e); } } return message; }, }; declare var self: any | undefined; declare var window: any | undefined; var globalThis: any = (() => { if (typeof globalThis !== "undefined") return globalThis; if (typeof self !== "undefined") return self; if (typeof window !== "undefined") return window; if (typeof global !== "undefined") return global; throw "Unable to locate global object"; })(); const atob: (b64: string) => string = globalThis.atob || ((b64) => globalThis.Buffer.from(b64, "base64").toString("binary")); function bytesFromBase64(b64: string): Uint8Array { const bin = atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } const btoa: (bin: string) => string = globalThis.btoa || ((bin) => globalThis.Buffer.from(bin, "binary").toString("base64")); function base64FromBytes(arr: Uint8Array): string { const bin: string[] = []; for (let i = 0; i < arr.byteLength; ++i) { bin.push(String.fromCharCode(arr[i])); } return btoa(bin.join("")); } type Builtin = | Date | Function | Uint8Array | string | number | boolean | undefined | Long; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); }
the_stack
import { Subject, AnonymousSubject } from '../../Subject'; import { Subscriber } from '../../Subscriber'; import { Observable } from '../../Observable'; import { Subscription } from '../../Subscription'; import { Operator } from '../../Operator'; import { ReplaySubject } from '../../ReplaySubject'; import { Observer, NextObserver } from '../../types'; /** * WebSocketSubjectConfig is a plain Object that allows us to make our * webSocket configurable. * * <span class="informal">Provides flexibility to {@link webSocket}</span> * * It defines a set of properties to provide custom behavior in specific * moments of the socket's lifecycle. When the connection opens we can * use `openObserver`, when the connection is closed `closeObserver`, if we * are interested in listening for data comming from server: `deserializer`, * which allows us to customize the deserialization strategy of data before passing it * to the socket client. By default `deserializer` is going to apply `JSON.parse` to each message comming * from the Server. * * ## Example * **deserializer**, the default for this property is `JSON.parse` but since there are just two options * for incomming data, either be text or binarydata. We can apply a custom deserialization strategy * or just simply skip the default behaviour. * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ * url: 'ws://localhost:8081', * //Apply any transformation of your choice. * deserializer: ({data}) => data * }); * * wsSubject.subscribe(console.log); * * // Let's suppose we have this on the Server: ws.send("This is a msg from the server") * //output * // * // This is a msg from the server * ``` * * **serializer** allows us tom apply custom serialization strategy but for the outgoing messages * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ * url: 'ws://localhost:8081', * //Apply any transformation of your choice. * serializer: msg => JSON.stringify({channel: "webDevelopment", msg: msg}) * }); * * wsSubject.subscribe(() => subject.next("msg to the server")); * * // Let's suppose we have this on the Server: ws.send("This is a msg from the server") * //output * // * // {"channel":"webDevelopment","msg":"msg to the server"} * ``` * * **closeObserver** allows us to set a custom error when an error raise up. * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ * url: 'ws://localhost:8081', * closeObserver: { next(closeEvent) { const customError = { code: 6666, reason: "Custom evil reason" } console.log(`code: ${customError.code}, reason: ${customError.reason}`); } } * }); * * //output * // code: 6666, reason: Custom evil reason * ``` * * **openObserver**, Let's say we need to make some kind of init task before sending/receiving msgs to the * webSocket or sending notification that the connection was successful, this is when * openObserver is usefull for. * ```ts * import { webSocket } from 'rxjs/webSocket'; * * const wsSubject = webSocket({ * url: 'ws://localhost:8081', * openObserver: { * next: () => { * console.log('connetion ok'); * } * }, * }); * * //output * // connetion ok` * ``` * */ export interface WebSocketSubjectConfig<T> { /** The url of the socket server to connect to */ url: string; /** The protocol to use to connect */ protocol?: string | Array<string>; /** @deprecated use {@link deserializer} */ resultSelector?: (e: MessageEvent) => T; /** * A serializer used to create messages from passed values before the * messages are sent to the server. Defaults to JSON.stringify. */ serializer?: (value: T) => WebSocketMessage; /** * A deserializer used for messages arriving on the socket from the * server. Defaults to JSON.parse. */ deserializer?: (e: MessageEvent) => T; /** * An Observer that watches when open events occur on the underlying web socket. */ openObserver?: NextObserver<Event>; /** * An Observer than watches when close events occur on the underlying webSocket */ closeObserver?: NextObserver<CloseEvent>; /** * An Observer that watches when a close is about to occur due to * unsubscription. */ closingObserver?: NextObserver<void>; /** * A WebSocket constructor to use. This is useful for situations like using a * WebSocket impl in Node (WebSocket is a DOM API), or for mocking a WebSocket * for testing purposes */ WebSocketCtor?: { new(url: string, protocols?: string|string[]): WebSocket }; /** Sets the `binaryType` property of the underlying WebSocket. */ binaryType?: 'blob' | 'arraybuffer'; } const DEFAULT_WEBSOCKET_CONFIG: WebSocketSubjectConfig<any> = { url: '', deserializer: (e: MessageEvent) => JSON.parse(e.data), serializer: (value: any) => JSON.stringify(value), }; const WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT = 'WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }'; export type WebSocketMessage = string | ArrayBuffer | Blob | ArrayBufferView; export class WebSocketSubject<T> extends AnonymousSubject<T> { private _config: WebSocketSubjectConfig<T>; /** @deprecated This is an internal implementation detail, do not use. */ _output: Subject<T>; private _socket: WebSocket; constructor(urlConfigOrSource: string | WebSocketSubjectConfig<T> | Observable<T>, destination?: Observer<T>) { super(); if (urlConfigOrSource instanceof Observable) { this.destination = destination; this.source = urlConfigOrSource as Observable<T>; } else { const config = this._config = { ...DEFAULT_WEBSOCKET_CONFIG }; this._output = new Subject<T>(); if (typeof urlConfigOrSource === 'string') { config.url = urlConfigOrSource; } else { for (let key in urlConfigOrSource) { if (urlConfigOrSource.hasOwnProperty(key)) { config[key] = urlConfigOrSource[key]; } } } if (!config.WebSocketCtor && WebSocket) { config.WebSocketCtor = WebSocket; } else if (!config.WebSocketCtor) { throw new Error('no WebSocket constructor can be found'); } this.destination = new ReplaySubject(); } } lift<R>(operator: Operator<T, R>): WebSocketSubject<R> { const sock = new WebSocketSubject<R>(this._config as WebSocketSubjectConfig<any>, <any> this.destination); sock.operator = operator; sock.source = this; return sock; } private _resetState() { this._socket = null; if (!this.source) { this.destination = new ReplaySubject(); } this._output = new Subject<T>(); } /** * Creates an {@link Observable}, that when subscribed to, sends a message, * defined by the `subMsg` function, to the server over the socket to begin a * subscription to data over that socket. Once data arrives, the * `messageFilter` argument will be used to select the appropriate data for * the resulting Observable. When teardown occurs, either due to * unsubscription, completion or error, a message defined by the `unsubMsg` * argument will be send to the server over the WebSocketSubject. * * @param subMsg A function to generate the subscription message to be sent to * the server. This will still be processed by the serializer in the * WebSocketSubject's config. (Which defaults to JSON serialization) * @param unsubMsg A function to generate the unsubscription message to be * sent to the server at teardown. This will still be processed by the * serializer in the WebSocketSubject's config. * @param messageFilter A predicate for selecting the appropriate messages * from the server for the output stream. */ multiplex(subMsg: () => any, unsubMsg: () => any, messageFilter: (value: T) => boolean) { const self = this; return new Observable((observer: Observer<any>) => { try { self.next(subMsg()); } catch (err) { observer.error(err); } const subscription = self.subscribe(x => { try { if (messageFilter(x)) { observer.next(x); } } catch (err) { observer.error(err); } }, err => observer.error(err), () => observer.complete()); return () => { try { self.next(unsubMsg()); } catch (err) { observer.error(err); } subscription.unsubscribe(); }; }); } private _connectSocket() { const { WebSocketCtor, protocol, url, binaryType } = this._config; const observer = this._output; let socket: WebSocket = null; try { socket = protocol ? new WebSocketCtor(url, protocol) : new WebSocketCtor(url); this._socket = socket; if (binaryType) { this._socket.binaryType = binaryType; } } catch (e) { observer.error(e); return; } const subscription = new Subscription(() => { this._socket = null; if (socket && socket.readyState === 1) { socket.close(); } }); socket.onopen = (e: Event) => { const { _socket } = this; if (!_socket) { socket.close(); this._resetState(); return; } const { openObserver } = this._config; if (openObserver) { openObserver.next(e); } const queue = this.destination; this.destination = Subscriber.create<T>( (x) => { if (socket.readyState === 1) { try { const { serializer } = this._config; socket.send(serializer(x)); } catch (e) { this.destination.error(e); } } }, (e) => { const { closingObserver } = this._config; if (closingObserver) { closingObserver.next(undefined); } if (e && e.code) { socket.close(e.code, e.reason); } else { observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT)); } this._resetState(); }, () => { const { closingObserver } = this._config; if (closingObserver) { closingObserver.next(undefined); } socket.close(); this._resetState(); } ) as Subscriber<any>; if (queue && queue instanceof ReplaySubject) { subscription.add((<ReplaySubject<T>>queue).subscribe(this.destination)); } }; socket.onerror = (e: Event) => { this._resetState(); observer.error(e); }; socket.onclose = (e: CloseEvent) => { this._resetState(); const { closeObserver } = this._config; if (closeObserver) { closeObserver.next(e); } if (e.wasClean) { observer.complete(); } else { observer.error(e); } }; socket.onmessage = (e: MessageEvent) => { try { const { deserializer } = this._config; observer.next(deserializer(e)); } catch (err) { observer.error(err); } }; } /** @deprecated This is an internal implementation detail, do not use. */ _subscribe(subscriber: Subscriber<T>): Subscription { const { source } = this; if (source) { return source.subscribe(subscriber); } if (!this._socket) { this._connectSocket(); } this._output.subscribe(subscriber); subscriber.add(() => { const { _socket } = this; if (this._output.observers.length === 0) { if (_socket && _socket.readyState === 1) { _socket.close(); } this._resetState(); } }); return subscriber; } unsubscribe() { const { _socket } = this; if (_socket && _socket.readyState === 1) { _socket.close(); } this._resetState(); super.unsubscribe(); } }
the_stack
import { loadAcceleratorConfig } from '@aws-accelerator/common-config/src/load'; import { DynamoDB } from '@aws-accelerator/common/src/aws/dynamodb'; import { IPv4CidrRange, IPv4Prefix, Pool } from 'ip-num'; import { v4 as uuidv4 } from 'uuid'; import { loadAssignedVpcCidrPool, loadAssignedSubnetCidrPool, loadCidrPools, } from '@aws-accelerator/common/src/util/common'; import { getUpdateValueInput } from './utils/dynamodb-requests'; import { VpcConfig } from '@aws-accelerator/common-config'; import { AssignedVpcCidrPool } from '@aws-accelerator/common-outputs/src/cidr-pools'; export interface GetBaseLineInput { configFilePath: string; configRepositoryName: string; configCommitId: string; outputTableName: string; vpcCidrPoolAssignedTable: string; subnetCidrPoolAssignedTable: string; cidrPoolsTable: string; acceleratorVersion?: string; storeAllOutputs?: boolean; } export interface ConfigurationOrganizationalUnit { ouId: string; ouKey: string; ouName: string; } export interface GetBaseelineOutput { baseline: string; storeAllOutputs: boolean; phases: number[]; organizationAdminRole: string; } const dynamoDB = new DynamoDB(); export interface AssignCidrInput { vpcCidrPoolAssignedTable: string; subnetCidrPoolAssignedTable: string; cidrPoolsTable: string; configFilePath: string; configRepositoryName: string; configCommitId: string; } /** * Step to return baseline from configuration, storeAllOutputs flag based on DDB entries in Outputs and OrgAdminRole name from Config * Run AssignDynamicCidrs to assign Cidr for VPC and Subnet if cidr-src is dynamic * @param input GetBaseLineInput * @returns GetBaseelineOutput */ export const handler = async (input: GetBaseLineInput): Promise<GetBaseelineOutput> => { console.log(`Loading configuration...`); console.log(JSON.stringify(input, null, 2)); const { configFilePath, configRepositoryName, configCommitId, outputTableName, storeAllOutputs, cidrPoolsTable, subnetCidrPoolAssignedTable, vpcCidrPoolAssignedTable, } = input; // Retrieve Configuration from Code Commit with specific commitId const config = await loadAcceleratorConfig({ repositoryName: configRepositoryName, filePath: configFilePath, commitId: configCommitId, }); const globalOptionsConfig = config['global-options']; const baseline = globalOptionsConfig['ct-baseline'] ? 'CONTROL_TOWER' : 'ORGANIZATIONS'; let runStoreAllOutputs: boolean = !!storeAllOutputs; if (!runStoreAllOutputs) { // Checking whether DynamoDB outputs table is empty or not runStoreAllOutputs = await dynamoDB.isEmpty(outputTableName); } await assignDynamicCidrs({ configCommitId, configFilePath, configRepositoryName, cidrPoolsTable, subnetCidrPoolAssignedTable, vpcCidrPoolAssignedTable, }); console.log( JSON.stringify( { baseline, storeAllOutputs: runStoreAllOutputs, phases: [-1, 0, 1, 2, 3], }, null, 2, ), ); return { baseline, storeAllOutputs: runStoreAllOutputs, phases: [-1, 0, 1, 2, 3], organizationAdminRole: globalOptionsConfig['organization-admin-role'] || 'AWSCloudFormationStackSetExecutionRole', }; }; async function assignDynamicCidrs(input: AssignCidrInput) { const { cidrPoolsTable, configCommitId, configFilePath, configRepositoryName, subnetCidrPoolAssignedTable, vpcCidrPoolAssignedTable, } = input; const config = await loadAcceleratorConfig({ repositoryName: configRepositoryName, filePath: configFilePath, commitId: configCommitId, }); const assignedSubnetCidrPools = await loadAssignedSubnetCidrPool(subnetCidrPoolAssignedTable); const cidrPools = await loadCidrPools(cidrPoolsTable); if (cidrPools.length === 0 && config['global-options']['cidr-pools'].length > 0) { // load cidrs from config to ddb for (const [index, configCidrPool] of Object.entries(config['global-options']['cidr-pools'])) { const updateExpression = getUpdateValueInput([ { key: 'c', name: 'cidr', type: 'S', value: configCidrPool.cidr.toCidrString(), }, { key: 'r', name: 'region', type: 'S', value: configCidrPool.region, }, { key: 'p', name: 'pool', type: 'S', value: configCidrPool.pool, }, ]); await dynamoDB.updateItem({ TableName: cidrPoolsTable, Key: { id: { S: `${parseInt(index, 10) + 1}` }, }, ...updateExpression, }); } cidrPools.push(...(await loadCidrPools(cidrPoolsTable))); } const lookupCidrs = async ( accountKey: string, vpcConfig: VpcConfig, assignedVpcCidrPools: AssignedVpcCidrPool[], ouKey?: string, ) => { let existingCidrs = assignedVpcCidrPools.filter( vp => vp.region === vpcConfig.region && vp['vpc-name'] === vpcConfig.name && ((vp['account-Key'] && vp['account-Key'] === accountKey) || vp['account-ou-key'] === `account/${accountKey}`), ); if (existingCidrs.length === 0) { existingCidrs = assignedVpcCidrPools.filter( vp => vp.region === vpcConfig.region && vp['vpc-name'] === vpcConfig.name && vp['account-ou-key'] === `organizational-unit/${ouKey}`, ); } if (existingCidrs.length === 0) { throw new Error(`VPC "${vpcConfig.region}/${vpcConfig.name}" Cidr-Src is lookup and didn't find entry in DDB`); } for (const existingCidr of existingCidrs) { if (existingCidr['account-ou-key'] === `organizational-unit/${ouKey}`) { await updateVpcCidr(vpcCidrPoolAssignedTable, uuidv4(), { accountOuKey: `account/${accountKey}`, cidr: existingCidr.cidr, pool: existingCidr.pool, region: vpcConfig.region, vpc: vpcConfig.name, accountKey, vpcAssignedId: `${existingCidr['vpc-assigned-id']}`, }); } } for (const subnetConfig of vpcConfig.subnets || []) { for (const subnetDef of subnetConfig.definitions) { let existingSubnet = assignedSubnetCidrPools.find( sp => sp['subnet-name'] === subnetConfig.name && sp.az === subnetDef.az && sp['vpc-name'] === vpcConfig.name && sp.region === vpcConfig.region && ((sp['account-Key'] && sp['account-Key'] === accountKey) || sp['account-ou-key'] === `account/${accountKey}`), ); if (!existingSubnet) { existingSubnet = assignedSubnetCidrPools.find( sp => sp['subnet-name'] === subnetConfig.name && sp.az === subnetDef.az && sp['vpc-name'] === vpcConfig.name && sp.region === vpcConfig.region && sp['account-ou-key'] === `organizational-unit/${ouKey}`, ); } if (!existingSubnet) { throw new Error( `Subnet "${vpcConfig.region}/${vpcConfig.name}/${subnetConfig.name}/${subnetDef.az}" Cidr-Src is lookup and didn't find entry in DDB`, ); } if (existingSubnet['account-ou-key'] === `organizational-unit/${ouKey}`) { await updateSubnetCidr(subnetCidrPoolAssignedTable, uuidv4(), { accountOuKey: `account/${accountKey}`, cidr: existingSubnet.cidr, pool: existingSubnet['sub-pool'], region: vpcConfig.region, vpc: vpcConfig.name, subnet: subnetConfig.name, az: subnetDef.az, accountKey, }); } } } }; const dynamicCidrs = async ( accountKey: string, vpcConfig: VpcConfig, assignedVpcCidrPools: AssignedVpcCidrPool[], ) => { const vpcCidr: { [key: string]: string } = {}; for (const vpcCidrObj of vpcConfig.cidr) { const currentPool = cidrPools.find(cp => cp.region === vpcConfig.region && cp.pool === vpcCidrObj.pool); if (!currentPool) { throw new Error(`Didn't find entry for "${vpcCidrObj.pool}" in cidr-pools DDB table`); } const existingCidr = assignedVpcCidrPools.find( vp => vp.region === vpcConfig.region && vp['vpc-name'] === vpcConfig.name && vp.pool === vpcCidrObj.pool && ((vp['account-Key'] && vp['account-Key'] === accountKey) || vp['account-ou-key'] === `account/${accountKey}`), ); if (!existingCidr) { const usedCidrs = assignedVpcCidrPools .filter( vp => vp.region === vpcConfig.region && vp.pool === vpcCidrObj.pool, // ((vp['account-Key'] && vp['account-Key'] === accountKey) || // vp['account-ou-key'] === `account/${accountKey}` || // (ouKey && vp['account-ou-key'] === `organizational-unit/${ouKey}`)), ) .map(vp => vp.cidr); const pool = poolFromCidr(currentPool.cidr); const currentPoolCidrRange = pool.getCidrRange(IPv4Prefix.fromNumber(vpcCidrObj.size!)); vpcCidr[vpcCidrObj.pool] = getAvailableCidr(usedCidrs, currentPoolCidrRange); if ( IPv4CidrRange.fromCidr(currentPool.cidr) .getLast() .isLessThan(IPv4CidrRange.fromCidr(vpcCidr[vpcCidrObj.pool]).getFirst()) ) { throw new Error( `Cidr Pool : "${currentPool.cidr} ran out of space while assigning for VPC: "${vpcConfig.region}/${vpcConfig.name}"`, ); } await updateVpcCidr(vpcCidrPoolAssignedTable, uuidv4(), { accountOuKey: `account/${accountKey}`, cidr: vpcCidr[vpcCidrObj.pool], pool: vpcCidrObj.pool, region: vpcConfig.region, vpc: vpcConfig.name, accountKey, }); } else { vpcCidr[vpcCidrObj.pool] = existingCidr.cidr; } } const usedSubnetCidrs = assignedSubnetCidrPools .filter( sp => sp.region === vpcConfig.region && sp['vpc-name'] === vpcConfig.name, // ((vp['account-Key'] && vp['account-Key'] === accountKey) || // vp['account-ou-key'] === `account/${accountKey}` || // (ouKey && vp['account-ou-key'] === `organizational-unit/${ouKey}`)), ) .map(sp => sp.cidr); for (const subnetConfig of vpcConfig.subnets || []) { for (const subnetDef of subnetConfig.definitions) { if (!subnetDef.cidr) { throw new Error( `Didn't find Cidr in Configuration for Subnet "${accountKey}/${vpcConfig.name}/${subnetConfig.name}"`, ); } console.log( `Creating Dynamic CIDR for "${subnetConfig.name}.${subnetDef.az}" of pool ${ subnetDef.cidr.pool } with VPC Cidr ${vpcCidr[subnetDef.cidr.pool]}`, ); const subnetPool = Pool.fromCidrRanges([IPv4CidrRange.fromCidr(vpcCidr[subnetDef.cidr.pool])]); let subnetCidr = ''; const existingSubnet = assignedSubnetCidrPools.find( sp => sp['subnet-name'] === subnetConfig.name && sp.az === subnetDef.az && sp['vpc-name'] === vpcConfig.name && sp.region === vpcConfig.region && ((sp['account-Key'] && sp['account-Key'] === accountKey) || sp['account-ou-key'] === `account/${accountKey}`), ); if (!existingSubnet) { const currentSubnetCidrRange = subnetPool.getCidrRange(IPv4Prefix.fromNumber(subnetDef.cidr.size!)); subnetCidr = getAvailableCidr(usedSubnetCidrs, currentSubnetCidrRange); if ( IPv4CidrRange.fromCidr(vpcCidr[subnetDef.cidr.pool]) .getLast() .isLessThan(IPv4CidrRange.fromCidr(subnetCidr).getFirst()) ) { throw new Error( `Error while creating dynamic CIDR for Subnets in VPC: "${vpcConfig.region}/${vpcConfig.name}"`, ); } console.log(`Dynamic CIDR for "${subnetConfig.name}.${subnetDef.az}" is "${subnetCidr}"`); await updateSubnetCidr(subnetCidrPoolAssignedTable, uuidv4(), { accountOuKey: `account/${accountKey}`, cidr: subnetCidr, pool: subnetDef.cidr.pool, region: vpcConfig.region, vpc: vpcConfig.name, subnet: subnetConfig.name, az: subnetDef.az, accountKey, }); } else { subnetCidr = existingSubnet.cidr; } } } }; // creating an IPv4 range from CIDR notation for (const { accountKey, vpcConfig, ouKey } of config.getVpcConfigs()) { if (vpcConfig['cidr-src'] === 'provided') { continue; } const assignedVpcCidrPools = await loadAssignedVpcCidrPool(vpcCidrPoolAssignedTable); if (vpcConfig['cidr-src'] === 'lookup') { await lookupCidrs(accountKey, vpcConfig, assignedVpcCidrPools, ouKey); } else if (vpcConfig['cidr-src'] === 'dynamic') { await dynamicCidrs(accountKey, vpcConfig, assignedVpcCidrPools); } } } function getAvailableCidr(usedCidrs: string[], currentPoolCidrRange: IPv4CidrRange): string { let alreadyUsed = false; do { for (const usedCidr of usedCidrs) { const usedCidrObj = IPv4CidrRange.fromCidr(usedCidr); if ( usedCidrObj.isEquals(currentPoolCidrRange) || usedCidrObj.contains(currentPoolCidrRange) || currentPoolCidrRange.contains(usedCidrObj) ) { currentPoolCidrRange = currentPoolCidrRange.nextRange()!; alreadyUsed = true; break; } else { alreadyUsed = false; } } } while (alreadyUsed); usedCidrs.push(currentPoolCidrRange.toCidrString()); return currentPoolCidrRange.toCidrString(); } async function updateVpcCidr(tableName: string, id: string, input: { [key: string]: string }) { const updateExpression = getUpdateValueInput([ { key: 'a', name: 'account-ou-key', type: 'S', value: input.accountOuKey, }, { key: 'r', name: 'region', type: 'S', value: input.region, }, { key: 'c', name: 'cidr', type: 'S', value: input.cidr, }, { key: 'p', name: 'pool', type: 'S', value: input.pool, }, { key: 're', name: 'requester', type: 'S', value: 'Accelerator', }, { key: 's', name: 'status', type: 'S', value: 'assigned', }, { key: 'v', name: 'vpc-name', type: 'S', value: input.vpc, }, { key: 'ak', name: 'account-key', type: 'S', value: input.accountKey, }, { key: 'vi', name: 'vpc-assigned-id', type: 'N', value: input.vpcAssignedId, }, ]); await dynamoDB.updateItem({ TableName: tableName, Key: { id: { S: id }, }, ...updateExpression, }); } async function updateSubnetCidr(tableName: string, id: string, input: { [key: string]: string }) { const updateExpression = getUpdateValueInput([ { key: 'a', name: 'account-ou-key', type: 'S', value: input.accountOuKey, }, { key: 'r', name: 'region', type: 'S', value: input.region, }, { key: 'c', name: 'cidr', type: 'S', value: input.cidr, }, { key: 'p', name: 'subnet-pool', type: 'S', value: input.pool, }, { key: 're', name: 'requester', type: 'S', value: 'Accelerator', }, { key: 's', name: 'status', type: 'S', value: 'assigned', }, { key: 'v', name: 'vpc-name', type: 'S', value: input.vpc, }, { key: 'sn', name: 'subnet-name', type: 'S', value: input.subnet, }, { key: 'az', name: 'az', type: 'S', value: input.az, }, ]); await dynamoDB.updateItem({ TableName: tableName, Key: { id: { S: id }, }, ...updateExpression, }); } function poolFromCidr(cidr: string) { try { return Pool.fromCidrRanges([IPv4CidrRange.fromCidr(cidr)]); } catch (e) { throw new Error(`Error while generating pool for cidr "${cidr}": ${e}`); } }
the_stack
import * as util from 'util' import { AccessToken, AccessTokenApi } from '@tnwx/accesstoken' import { HttpKit } from '@tnwx/kits' /** * @author Javen * @copyright javendev@126.com * @description 微信摇一摇 设备管理 */ export class ShakeAroundDeviceApi { private static applyIdUrl: string = 'https://api.weixin.qq.com/shakearound/device/applyid?access_token=%s' /** * 申请设备ID * @param quantity 申请的设备ID的数量,单次新增设备超过500个,需走人工审核流程 * @param applyReason 申请理由,不超过100个汉字或200个英文字母 * @param comment 备注,不超过15个汉字或30个英文字母 * @param poiId 设备关联的门店ID,关联门店后,在门店1KM的范围内有优先摇出信息的机会。门店相关信息具体可 查看门店相关的接口文档 * @param accessToken */ public static async applyId(quantity: number, applyReason: string, comment?: string, poiId?: number, accessToken?: AccessToken) { let map = new Map<string, any>() map.set('quantity', quantity) map.set('apply_reason', applyReason) if (comment) map.set('comment', comment) if (poiId) map.set('poi_id', poiId) if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.applyIdUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost(url, JSON.stringify(map)) } private static applyStatusUrl: string = 'https://api.weixin.qq.com/shakearound/device/applystatus?access_token=%s' /** * 查询设备ID申请审核状态 * @param applyId 批次ID,申请设备ID时所返回的批次ID * @param accessToken */ public static async getApplyStatus(applyId: number, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.applyStatusUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ apply_id: applyId }) ) } private static updateUrl: string = 'https://api.weixin.qq.com/shakearound/device/update?access_token=%s' /** * 编辑设备的备注信息 * @param deviceIdentifier 可用设备ID或完整的UUID、Major、Minor指定设备,二者选其一。 * @param comment 设备的备注信息,不超过15个汉字或30个英文字母。 * @param accessToken */ public static async updateDeviceInfo(deviceIdentifier: DeviceIdentifier, comment: string, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.updateUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ device_identifier: deviceIdentifier, comment: comment }) ) } private static bindLocationUrl: string = 'https://api.weixin.qq.com/shakearound/device/bindlocation?access_token=%s' /** * 配置设备与门店的关联关系 * @param deviceIdentifier 指定的设备ID * @param poiId 设备关联的门店ID,关联门店后,在门店1KM的范围内有优先摇出信息的机会。当值为0时,将清除设备已关联的门店ID。门店相关信息具体可 查看门店相关的接口文档 * @param type 为1时,关联的门店和设备归属于同一公众账号; 为2时,关联的门店为其他公众账号的门店 * @param poiAppid 当Type为2时,必填。关联门店所归属的公众账号的APPID * @param accessToken */ public static async bindLocation(deviceIdentifier: DeviceIdentifier, poiId: number, type: number = 1, poiAppid?: string, accessToken?: AccessToken) { let map = new Map<string, any>() map.set('device_identifier', deviceIdentifier) map.set('poi_id', poiId) if (type == 2) { map.set('type', 2) if (poiAppid) map.set('poi_appid', poiAppid) } if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.bindLocationUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost(url, JSON.stringify(map)) } private static searchUrl: string = 'https://api.weixin.qq.com/shakearound/device/search?access_token=%s' /** * 查询设备列表 * @param deviceIdentifier 指定的设备ID * @param accessToken */ public static async searchByDevice(deviceIdentifier: DeviceIdentifier, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.searchUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ device_identifiers: deviceIdentifier, type: 1 }) ) } /** * 需要分页查询或者指定范围内的设备时 * @param lastSeen 前一次查询列表末尾的设备ID , 第一次查询last_seen 为0 * @param count 待查询的设备数量,不能超过50个 * @param accessToken */ public static async searchPage(lastSeen: number, count: number, accessToken?: AccessToken) { if (lastSeen < 0) lastSeen = 0 if (count > 50) count = 50 if (count < 1) count = 1 if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.searchUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ last_seen: lastSeen, type: 2, count: count }) ) } /** * 当需要根据批次ID查询时 * @param applyId 批次ID,申请设备ID时所返回的批次ID * @param lastSeen 前一次查询列表末尾的设备ID , 第一次查询last_seen 为0 * @param count 待查询的设备数量,不能超过50个 * @param accessToken */ public static async searchPageByApplyId(applyId: number, lastSeen: number, count: number, accessToken?: AccessToken) { if (lastSeen < 0) lastSeen = 0 if (count > 50) count = 50 if (count < 1) count = 1 if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.searchUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ apply_id: applyId, last_seen: lastSeen, type: 3, count: count }) ) } private static bindPageUrl: string = 'https://api.weixin.qq.com/shakearound/device/bindpage?access_token=%s' /** * 配置设备与页面的关联关系 * @param deviceIdentifier 指定页面的设备ID * @param pageIds 待关联的页面列表 * @param accessToken */ public static async bindPage(deviceIdentifier: DeviceIdentifier, pageIds: number[], accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.bindPageUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ device_identifier: deviceIdentifier, page_ids: pageIds }) ) } private static relationSearchUrl: string = 'https://api.weixin.qq.com/shakearound/relation/search?access_token=%s' /** * 查询设备与页面的关联关系,当查询指定设备所关联的页面时 * @param deviceIdentifier 指定页面的设备ID * @param accessToken */ public static async relationSearch(deviceIdentifier: DeviceIdentifier, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.relationSearchUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ device_identifier: deviceIdentifier, type: 1 }) ) } /** * * @param pageId 指定的页面id * @param begin 关联关系列表的起始索引值 * @param count 待查询的关联关系数量,不能超过50个 * @param accessToken */ public static async relationSearchByPage(pageId: number, begin: number, count: number, accessToken?: AccessToken) { if (begin < 0) begin = 0 if (count > 50) count = 50 if (count < 1) count = 1 if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.relationSearchUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ type: 2, page_id: pageId, begin: begin, count: count }) ) } private static addGroupUrl: string = 'https://api.weixin.qq.com/shakearound/device/group/add?access_token=%s' /** * 新增分组 每个帐号下最多只有1000个分组。 * @param groupName 分组名称,不超过100汉字或200个英文字母 * @param accessToken */ public static async addGroup(groupName: string, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.addGroupUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ group_name: groupName }) ) } private static updateGroupUrl: string = 'https://api.weixin.qq.com/shakearound/device/group/update?access_token=%s' /** * 编辑分组信息 * @param groupId 分组唯一标识,全局唯一 * @param groupName 分组名称,不超过100汉字或200个英文字母 * @param accessToken */ public static async updateGroup(groupId: number, groupName: string, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.updateGroupUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ group_id: groupId, group_name: groupName }) ) } private static deleteGroupUrl: string = 'https://api.weixin.qq.com/shakearound/device/group/delete?access_token=%s' /** * 删除分组 * @param groupId 分组唯一标识,全局唯一 * @param accessToken */ public static async deleteGroup(groupId: number, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.deleteGroupUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ group_id: groupId }) ) } private static getGroupListUrl: string = 'https://api.weixin.qq.com/shakearound/device/group/getlist?access_token=%s' /** * 查询分组列表 * @param begin 分组列表的起始索引值 * @param count 待查询的分组数量,不能超过1000个 * @param accessToken */ public static async getGroupList(begin: number, count: number, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.getGroupListUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ begin: begin, count: count }) ) } private static getGroupDetailUrl: string = 'https://api.weixin.qq.com/shakearound/device/group/getdetail?access_token=%s' /** * 查询分组详情 * @param groupId 分组唯一标识,全局唯一 * @param begin 分组列表的起始索引值 * @param count 待查询的分组数量,不能超过1000个 * @param accessToken */ public static async getGroupDetail(groupId: number, begin: number, count: number, accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.getGroupDetailUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ groupId: groupId, begin: begin, count: count }) ) } private static addDeviceUrl: string = 'https://api.weixin.qq.com/shakearound/device/group/adddevice?access_token=%s' /** * 添加设备到分组 * @param groupId 分组唯一标识,全局唯一 * @param deviceIdentifierList 设备id列表 每次添加设备上限为1000 * @param accessToken */ public static async addDeviceToGroup(groupId: number, deviceIdentifierList: DeviceIdentifier[], accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.addDeviceUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ groupId: groupId, device_identifiers: deviceIdentifierList }) ) } private static deleteGroupDeviceUrl = 'https://api.weixin.qq.com/shakearound/device/group/deletedevice?access_token=%s' /** * 从分组中移除设备 * @param groupId 分组唯一标识,全局唯一 * @param deviceIdentifierList 设备id列表 每次删除设备上限为1000 * @param accessToken */ public static async deleteDeviceFromGroup(groupId: number, deviceIdentifierList: DeviceIdentifier[], accessToken?: AccessToken) { if (!accessToken) { accessToken = await AccessTokenApi.getAccessToken() } let url = util.format(this.deleteGroupDeviceUrl, accessToken.getAccessToken) return HttpKit.getHttpDelegate.httpPost( url, JSON.stringify({ groupId: groupId, device_identifiers: deviceIdentifierList }) ) } } export class DeviceIdentifier { private device_id: number private uuid: string private major: number private minor: number public set setDeviceId(deviceId: number) { this.device_id = deviceId } public get getDeviceId(): number { return this.device_id } public set setUuid(uuid: string) { this.uuid = uuid } public get getUuit(): string { return this.uuid } public set setMajor(major: number) { this.major = major } public get getMajor(): number { return this.major } public set setMinor(minor: number) { this.minor = minor } public get getMinor(): number { return this.minor } }
the_stack
import { genMountFn, triggerTouchEvents, genDelayedSelectorSpy } from '@taro-ui-vue3/test-utils/helper' import { Calendar } from "@taro-ui-vue3/types/calendar" import dayjs from "dayjs/esm/index" import * as utils from '@taro-ui-vue3/utils/common' import AtCalendar from '../index.vue' import AtCalendarBody from '../body/index.vue' import AtCalendarController from '../controller/index.vue' import AtCalendarHeader from '../ui/day-list/index.vue' import AtCalendarList from '../ui/date-list/index.vue' describe("AtCalendarHeader", () => { const mountFn = genMountFn(AtCalendarHeader) it("should render calendar header and match snapshot", async () => { const wrapper = mountFn() expect(wrapper.element).toMatchSnapshot() const days = ['日', '一', '二', '三', '四', '五', '六'] const dayEls = wrapper.findAll(".header__flex-item") days.forEach((day, index) => { expect(dayEls[index].text()).toEqual(day) }) }) }) describe("AtCalendarList", () => { const mountFn = genMountFn(AtCalendarList) const list: Calendar.List<Calendar.Item> = [ { value: '2021/06/04', text: 4, type: 0, marks: [{ value: '2021/06/04' }], isActive: true, isToday: true, isBeforeMin: true, isAfterMax: true, isDisabled: true, isSelected: true, isSelectedHead: true, isSelectedTail: true, }, { value: '2021/06/05', text: 5, type: 1, marks: [{ value: '2021/06/05' }], }, { value: '2021/06/06', text: 6, type: -1, marks: [{ value: '2021/06/06' }], } ] it("should render calendar list and match snapshot", async () => { const wrapper = mountFn({ list }) expect(wrapper.element).toMatchSnapshot() }) it("should emit click event", async () => { const wrapper = mountFn({ list }) await wrapper.find(".flex__item").trigger('tap') expect(wrapper.emitted()).toHaveProperty('click') }) it("should emit long-click event", async () => { const wrapper = mountFn({ list }) await wrapper.find(".flex__item").trigger('longpress') expect(wrapper.emitted()).toHaveProperty('long-click') }) }) describe("AtCalendarController", () => { const mountFn = genMountFn(AtCalendarController) it("should render calendar header and match snapshot", async () => { const wrapper = mountFn({ generateDate: '2021-04-01' }) expect(wrapper.element).toMatchSnapshot() }) it("should render prop hideArrow", async () => { const wrapper = mountFn({ hideArrow: true }) expect( wrapper .findAll('.controller__arrow') .length ).toEqual(0) }) it("should render prop generateDate", async () => { const wrapper = mountFn({ generateDate: "2021-05-01" }) expect( wrapper.get('picker').attributes('value') ).toEqual('2021-05') expect( wrapper.get('.controller__info').text() ).toEqual('2021 年 05 月') }) it.each([ 'minDate', 'maxDate' ])("should render prop %s", async (propName) => { const wrapper = mountFn({ [propName]: "2021-05-01" }) const attrs = { minDate: 'start', maxDate: 'end' } expect( wrapper.get('picker').attributes(attrs[propName]) ).toEqual('2021-05') }) it("should render emit pre-month event", async () => { const wrapper = mountFn() wrapper.find(".controller__arrow--left").trigger("tap") expect(wrapper.emitted()).toHaveProperty("pre-month") }) it("should render emit next-month event", async () => { const wrapper = mountFn() wrapper.find(".controller__arrow--right").trigger("tap") expect(wrapper.emitted()).toHaveProperty("next-month") }) it("should render emit select-date event", async () => { const wrapper = mountFn() wrapper.get("picker").trigger("change") expect(wrapper.emitted()).toHaveProperty("select-date") }) }) describe("AtCalendarBody", () => { const generateDate = "2021-05-04" const mountFn = genMountFn(AtCalendarBody) let delayedSelector: jest.SpyInstance beforeAll(() => { jest.mock('@taro-ui-vue3/utils/common') jest.useFakeTimers() delayedSelector = genDelayedSelectorSpy(utils, { width: 480, height: 480 }) }) afterAll(() => { delayedSelector.mockRestore() }) it("should render non-swiper calendar body and match snapshot", async () => { const wrapper = mountFn({ isSwiper: false, generateDate }) expect( wrapper.find('.body__slider--now').exists() ).toBeTruthy() expect( wrapper.find('.body__slider--pre').exists() ).toBeFalsy() expect( wrapper.find('.body__slider--next').exists() ).toBeFalsy() expect(wrapper.element).toMatchSnapshot() }) it("should render h5 calendar body and match snapshot", async () => { process.env.TARO_ENV = 'h5' const wrapper = mountFn({ generateDate }) expect( wrapper .find('.main > .main__body > .body__slider--pre') .exists() ).toBeTruthy() expect( wrapper .find('.main > .main__body > .body__slider--now') .exists() ).toBeTruthy() expect( wrapper .find('.main > .main__body > .body__slider--next') .exists() ).toBeTruthy() expect(wrapper.element).toMatchSnapshot() process.env.TARO_ENV = 'h5' }) it("should render miniapp calendar body and match snapshot", async () => { process.env.TARO_ENV = 'weapp' const wrapper = mountFn({ generateDate }) expect(wrapper.element).toMatchSnapshot() expect( wrapper .findAll('.main > swiper > swiper-item') .length ).toEqual(3) process.env.TARO_ENV = 'h5' }) it('should render prop isVertical in h5', async () => { const wrapper = mountFn({ isVertical: true, generateDate }) let h5MainBodyStyle = wrapper .find('.main__body--slider') .attributes('style') expect(h5MainBodyStyle).toContain( 'transform: translateY(-100%) translate3d(0,0px,0);' ) expect(h5MainBodyStyle).toContain( 'flex-direction: column;' ) await wrapper.setProps({ isVertical: false }) h5MainBodyStyle = wrapper .find('.main__body--slider') .attributes('style') expect(h5MainBodyStyle).toContain( 'transform: translateX(-100%) translate3d(0px,0,0);' ) expect(h5MainBodyStyle).not.toContain( 'flex-direction: column;' ) }) it('should render prop isVertical in weapp', async () => { process.env.TARO_ENV = 'weapp' const wrapper = mountFn({ isVertical: true, generateDate }) const swiperEl = wrapper.find('.main__body') expect(swiperEl.attributes('vertical')).toBe('true') process.env.TARO_ENV = 'h5' }) describe("events:\n", () => { it("should emit events day-click and long-click if not using swiper in h5", async () => { const wrapper = mountFn({ isSwiper: false, generateDate }) const dateList = wrapper.find('.body__slider--now .flex__item') await dateList.trigger('tap') await dateList.trigger('longpress') expect(wrapper.emitted()).toHaveProperty('day-click') expect(wrapper.emitted()).toHaveProperty('long-click') }) it("should emit events swipe-month, day-click and long-click in h5", async () => { const wrapper = mountFn({ generateDate }) const dateList = wrapper .find('.body__slider--now .flex__item') await dateList.trigger('tap') await dateList.trigger('longpress') expect(wrapper.emitted()).toHaveProperty('day-click') expect(wrapper.emitted()).toHaveProperty('long-click') let swiperEl = wrapper.find('.main.at-calendar-slider__main') await triggerTouchEvents( swiperEl, { clientX: 50, clientY: 200 }, { clientX: 350, clientY: 200 } ) jest.advanceTimersByTime(300) await wrapper.vm.$nextTick() expect(wrapper.emitted()).toHaveProperty('swipe-month') expect(wrapper.emitted('swipe-month')).toHaveLength(1) expect(wrapper.emitted()['swipe-month'][0]).toEqual([-1]) await wrapper.setProps({ isVertical: true, generateDate: Date.now() }) swiperEl = wrapper.find('.main__body') await triggerTouchEvents( swiperEl, { clientX: 200, clientY: 400 }, { clientX: 200, clientY: 50 } ) jest.advanceTimersByTime(300) await wrapper.vm.$nextTick() expect(wrapper.emitted('swipe-month')).toHaveLength(2) expect(wrapper.emitted()['swipe-month'][1]).toEqual([1]) }) it("should not emit swipe-month in h5 if touch distance is shorter than breakpoint", async () => { const wrapper = mountFn({ isVertical: true }) const swiperEl = wrapper.find('.main.at-calendar-slider__main') await triggerTouchEvents( swiperEl, { clientX: 350, clientY: 200 }, { clientX: 350, clientY: 350 } ) jest.advanceTimersByTime(300) await wrapper.vm.$nextTick() expect(wrapper.emitted()).not.toHaveProperty('swipe-month') }) it("should emit events swipe-month, day-click and long-click in miniapp", async () => { process.env.TARO_ENV = "weapp" const wrapper = mountFn({ generateDate }) const dateEl = wrapper .find('.main__body swiper-item[item-id="1"] .flex__item') await dateEl.trigger('tap') await dateEl.trigger('longpress') expect(wrapper.emitted()).toHaveProperty('day-click') expect(wrapper.emitted()).toHaveProperty('long-click') let swiperEl = wrapper.find('.main__body') await triggerTouchEvents( swiperEl, { clientX: 50, clientY: 200 }, { clientX: 350, clientY: 200 } ) await swiperEl.trigger('change', { detail: { current: 0, source: 'touch' } }) await swiperEl.trigger('animationfinish') expect(wrapper.emitted()).toHaveProperty('swipe-month') expect(wrapper.emitted('swipe-month')).toHaveLength(1) expect(wrapper.emitted()['swipe-month'][0]).toEqual([-1]) await wrapper.setProps({ isVertical: true }) swiperEl = wrapper.find('.main__body') await triggerTouchEvents( swiperEl, { clientX: 200, clientY: 400 }, { clientX: 200, clientY: 50 } ) await swiperEl.trigger('change', { detail: { current: 2, source: 'touch' } }) await swiperEl.trigger('animationfinish') expect(wrapper.emitted('swipe-month')).toHaveLength(2) expect(wrapper.emitted()['swipe-month'][1]).toEqual([1]) process.env.TARO_ENV = "h5" }) }) }) describe('AtCalendar', () => { const mountFn = genMountFn(AtCalendar) const paddingZero = (digit) => { return digit < 10 ? `0${digit}` : `${digit}` } const normalizeDateString = (dateStr): string => { const d = dateStr.split('-') return `${d[0]}-${paddingZero(d[1])}-${paddingZero(d[2])}` } const today = new Date() const todayStr = normalizeDateString(today .toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) .split(/上午|下午/)[0] .replace(/\//g, '-') .trimEnd() ) const dString = todayStr.substring(0, 7) let delayedSelector: jest.SpyInstance beforeAll(() => { jest.mock('@taro-ui-vue3/utils/common') jest.useFakeTimers() delayedSelector = genDelayedSelectorSpy(utils, { width: 480, height: 480 }) }) afterAll(() => { delayedSelector.mockRestore() }) it('should render marks', async () => { today.setDate(today.getDate() - 28) const prevM = new Date(today).toISOString().substring(0, 10) const wrapper = mountFn({ marks: [{ value: prevM }] }) expect( wrapper .findAll('.flex__item:not(.flex__item--blur) .mark') .length ).toBe(1) await wrapper.setProps({ marks: [ { value: `${dString}-21` }, { value: prevM }, { value: `${dString}-23` } ] }) await wrapper.vm.$nextTick() expect(wrapper .findAll('.flex__item:not(.flex__item--blur) .mark') .length ).toBe(3) }) it('should render minDate and maxDate', async () => { const wrapper = mountFn({ currentDate: '2020-12-27', minDate: '2020-12-27', maxDate: '2020-12-28' }) expect( wrapper .findAll( '.body__slider--now .flex__item--now:not(.flex__item--blur)' ) .length ).toBe(2) expect( wrapper .findAll( '.body__slider--now > .at-calendar__list > .flex__item--now.flex__item--blur' ) .length ).toBe(29) }) // need to enable handleSelectedDates in plugin.ts // currently selectedDates not supported it.skip('should render multi-selected dates', async () => { const wrapper = mountFn({ isMultiSelect: true, currentDate: '2021-06-04', selectedDates: [{ start: '2021-06-16', end: '2021-06-17' }] }) const currentMonth = wrapper .find('.main__body--slider .body__slider--now') const itemNow = '.flex__item--now' const itemSelected = '.flex__item--selected' const itemSelectedHead = '.flex__item--selected-head' const itemSelectedTail = '.flex__item--selected-tail' const itemText = '.flex__item-container > .container-text' expect(currentMonth.findAll(itemNow).length).toEqual(30) const selectedEls = currentMonth.findAll(itemSelected) expect(selectedEls.length).toBe(2) expect(selectedEls[0].classes()).toContain(itemSelectedHead) expect( selectedEls[0] .find(itemText) .text() ).toEqual(16) expect(selectedEls[1].classes()).toContain(itemSelectedTail) expect( selectedEls[1] .find(itemText) .text() ).toEqual(17) }) it('should render valid dates', async () => { const wrapper = mountFn({ validDates: [ { value: `${dString}-21` }, { value: `${dString}-25` } ] }) expect( wrapper .findAll( '.body__slider--now .flex__item--now:not(.flex__item--blur)' ) .length ).toBe(2) }) describe('events:\n', () => { let mockFn: jest.Mock<any, any> let currentDate = todayStr let year = parseInt(currentDate.split('-')[0]) let month = parseInt(currentDate.split('-')[1]) beforeEach(() => { mockFn = jest.fn() }) afterEach(() => { mockFn.mockRestore() }) it('should emit click-pre-month', async () => { const wrapper = mountFn({ currentDate, onClickPreMonth: mockFn }) expect( wrapper.find('.controller__info').text() ).toEqual(`${year} 年 ${paddingZero(month)} 月`) await wrapper.find('.controller__arrow--left').trigger('tap') expect( wrapper.find('.controller__info').text() ).toEqual( `${month === 1 ? year - 1 : year} 年 ${month === 1 ? 12 : paddingZero(month - 1)} 月` ) expect(wrapper.emitted()).toHaveProperty('click-pre-month') expect(mockFn).toBeCalled() }) it('should emit click-next-month', async () => { const wrapper = mountFn({ currentDate, onClickNextMonth: mockFn }) expect( wrapper.find('.controller__info').text() ).toEqual(`${year} 年 ${paddingZero(month)} 月`) await wrapper.find('.controller__arrow--right').trigger('tap') expect( wrapper.find('.controller__info').text() ).toEqual( `${month === 12 ? year + 1 : year} 年 ${month === 12 ? '01' : paddingZero(month + 1)} 月` ) expect(wrapper.emitted()).toHaveProperty('click-next-month') expect(mockFn).toBeCalled() }) it('should emit day-click and select-date', async () => { const onSelectDate = jest.fn() const wrapper = mountFn({ currentDate, onSelectDate, onDayClick: mockFn }) await wrapper .find('.flex__item--today') .trigger('tap', { value: currentDate }) expect(wrapper.emitted()).toHaveProperty('day-click') expect( wrapper.emitted('day-click')![0] ).toEqual([{ value: currentDate }]) expect(mockFn).toBeCalled() expect( mockFn.mock.calls[0][0] ).toEqual({ value: currentDate }) await wrapper.vm.$nextTick() expect(wrapper.emitted()).toHaveProperty('select-date') expect( wrapper.emitted('select-date')![0] ).toEqual([{ value: { start: currentDate, end: currentDate } }]) expect(onSelectDate).toBeCalled() expect( onSelectDate.mock.calls[0][0] ).toEqual({ value: { start: currentDate, end: currentDate } }) }) it('should emit day-long-click', async () => { const wrapper = mountFn({ currentDate, onDayLongClick: mockFn, }) await wrapper .find('.flex__item--today') .trigger('longpress', { value: currentDate }) expect(wrapper.emitted()).toHaveProperty('day-long-click') expect( wrapper.emitted('day-long-click')![0] ).toEqual([{ value: currentDate }]) expect(mockFn).toBeCalled() expect(mockFn.mock.calls[0][0]).toEqual({ value: currentDate }) }) it('should emit month-change when picking dates from the controller', async () => { const wrapper = mountFn({ onMonthChange: mockFn }) await wrapper .find('.at-calendar__controller > picker') .trigger('change', { detail: { value: '2020-12-27' } }) expect(wrapper.emitted()).toHaveProperty('month-change') expect( wrapper.emitted('month-change')![0] ).toEqual(['2020-12-27']) expect(mockFn).toBeCalled() expect(mockFn.mock.calls[0][0]).toEqual('2020-12-27') }) it('should emit month-change by swiping when use Swiper in h5', async () => { const wrapper = mountFn({ isSwiper: true, onMonthChange: mockFn }) const touchEL = wrapper.find('.at-calendar-slider__main') await triggerTouchEvents( touchEL, { clientX: 50, clientY: 200 }, { clientX: 350, clientY: 200 } ) jest.advanceTimersByTime(300) await wrapper.vm.$nextTick() expect(wrapper.emitted()).toHaveProperty('month-change') expect(mockFn).toBeCalled() }) it('should emit month-change by swiping in miniapp', async () => { process.env.TARO_ENV = "weapp" const wrapper = mountFn({ isSwiper: true, onMonthChange: mockFn }) const touchEL = wrapper.find('swiper.main__body') expect(touchEL.exists()).toBe(true) await triggerTouchEvents( touchEL, { clientX: 50, clientY: 200 }, { clientX: 350, clientY: 200 } ) await touchEL.trigger('change', { detail: { current: 0, source: 'touch' } }) await touchEL.trigger('animationfinish') expect(wrapper.emitted()).toHaveProperty('month-change') expect(mockFn).toBeCalled() process.env.TARO_ENV = "h5" }) // TODO: mock how to select multiple dates it('should select multiple dates', async () => { const onSelectDate = jest.fn() const onDayClick = jest.fn() const wrapper = mountFn({ isMultiSelect: true, currentDate: { start: '2021-05-01', end: '2021-05-01' }, onSelectDate, onDayClick }) const monthSlider = '.main__body--slider .body__slider--now' const itemNow = '.flex__item--now' const itemSelectedHead = '.flex__item--selected-head' const itemSelectedTail = '.flex__item--selected-tail' let currentMonth = wrapper.find(monthSlider) let dayEls = currentMonth.findAll(itemNow) expect( currentMonth.findAll(itemNow).length ).toEqual(31) // mock click 2021-05-10 and 2021-05-16 await dayEls[9].trigger('tap') await dayEls[15].trigger('tap', { value: '2021-05-16', type: 0, isSelected: true, isSelectedTail: true }) currentMonth = wrapper.find(monthSlider) dayEls = currentMonth.findAll(itemNow) expect(onDayClick.mock.calls.length).toBe(2) expect(onSelectDate.mock.calls.length).toBe(2) expect( dayEls[9].classes() ).toContain(itemSelectedHead.substring(1)) expect( onDayClick.mock.calls[0][0] ).toEqual({ "value": "2021-05-10" }) expect( onSelectDate.mock.calls[0][0] ).toEqual({ "value": { "start": "2021-05-10" } }) // expect( // dayEls[15].classes() // ).toContain(itemSelectedTail.substring(1)) // expect( // onDayClick.mock.calls[1][1] // ).toBe({ "value": "2021-05-16" }) // expect( // onSelectDate.mock.calls[1][1] // ).toBe({ // "value": { // "start": "2021-05-10", // "end": "2021-05-16" // } // }) }) }) })
the_stack
'use strict' import * as React from 'react' import type { ReactElement } from 'react' import { hatetrisAi } from '../../enemy-ais/hatetris-ai' import { lovetrisAi } from '../../enemy-ais/lovetris-ai' import { brzAi } from '../../enemy-ais/brzustowski' import { burgAi } from '../../enemy-ais/burgiel' import hatetrisReplayCodec from '../../replay-codecs/hatetris-replay-codec' import { Well } from '../Well/Well' import './Game.css' const minWidth = 4 const moves = ['L', 'R', 'D', 'U'] type Piece = { x: number, y: number, o: number, id: string } type Orientation = { yMin: number, yDim: number, xMin: number, xDim: number, rows: number[] } type Rotations = { [pieceId: string]: Orientation[] } type RotationSystem = { placeNewPiece: (wellWidth: number, pieceId: string) => Piece; rotations: Rotations } type CoreState = { score: number, well: number[], } type WellState = { core: CoreState, ai: any, piece: Piece } type GetNextCoreStates = (core: CoreState, pieceId: string) => CoreState[] type EnemyAi = ( currentCoreState: CoreState, currentAiState: any, getNextCoreStates: GetNextCoreStates ) => (string | [string, any]) type Enemy = { shortDescription: string | ReactElement, buttonDescription: string, ai: EnemyAi } type GameProps = { bar: number, replayTimeout: number, rotationSystem: RotationSystem, wellDepth: number, wellWidth: number } type GameState = { error: { interpretation: string, real: string }, displayEnemy: boolean, enemy: Enemy, customAiCode: string, mode: string, wellStateId: number, wellStates: WellState[], replay: any[], replayCopiedTimeoutId: ReturnType<typeof setTimeout>, replayTimeoutId: ReturnType<typeof setTimeout> } export type { CoreState, WellState, GameProps, RotationSystem, EnemyAi } export const hatetris: Enemy = { shortDescription: 'HATETRIS', buttonDescription: 'HATETRIS, the original and worst', ai: hatetrisAi } export const lovetris: Enemy = { shortDescription: '❤️', buttonDescription: 'all 4x1 pieces, all the time', ai: lovetrisAi } export const brz: Enemy = { shortDescription: ( <a href='https://open.library.ubc.ca/media/download/pdf/831/1.0079748/1' > Brzustowski </a> ), buttonDescription: 'Brzustowski (1992)', ai: brzAi } const burg: Enemy = { shortDescription: ( <a href='https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.55.8562&rep=rep1&type=pdf' > Burgiel </a> ), buttonDescription: 'Burgiel (1997)', ai: burgAi } const enemies = [hatetris, lovetris, brz, burg] const pieceIds = ['I', 'J', 'L', 'O', 'S', 'T', 'Z'] class Game extends React.Component<GameProps, GameState> { constructor (props: GameProps) { super(props) const { rotationSystem, bar, wellDepth, wellWidth } = this.props if (Object.keys(rotationSystem.rotations).length < 1) { throw Error('Have to have at least one piece!') } if (wellDepth < bar) { throw Error("Can't have well with depth " + String(wellDepth) + ' less than bar at ' + String(bar)) } if (wellWidth < minWidth) { throw Error("Can't have well with width " + String(wellWidth) + ' less than ' + String(minWidth)) } this.state = { error: null, displayEnemy: false, // don't show it unless the user selects one manually enemy: hatetris, customAiCode: '', mode: 'INITIAL', wellStateId: -1, wellStates: [], replay: [], replayCopiedTimeoutId: undefined, replayTimeoutId: undefined } } validateAiResult (coreState: CoreState, aiState: any) { const { enemy } = this.state const aiResult: any = enemy.ai(coreState, aiState, this.getNextCoreStates) const [unsafePieceId, nextAiState] = Array.isArray(aiResult) ? aiResult : [aiResult, aiState] if (pieceIds.includes(unsafePieceId)) { return [unsafePieceId, nextAiState] } throw Error(`Bad piece ID: ${unsafePieceId}`) } getFirstWellState (): WellState { const { rotationSystem, wellDepth, wellWidth } = this.props const firstCoreState = { well: Array(wellDepth).fill(0), score: 0 } const [firstPieceId, firstAiState] = this.validateAiResult(firstCoreState, undefined) return { core: firstCoreState, ai: firstAiState, piece: rotationSystem.placeNewPiece(wellWidth, firstPieceId) } } /** Generate a unique integer to describe the position and orientation of this piece. `x` varies between -3 and (`wellWidth` - 1) inclusive, so range = `wellWidth` + 3 `y` varies between 0 and (`wellDepth` + 2) inclusive, so range = `wellDepth` + 3 `o` varies between 0 and 3 inclusive, so range = 4 */ hashCode = (piece: Piece): number => (piece.x * (this.props.wellDepth + 3) + piece.y) * 4 + piece.o /** Given a well and a piece ID, find all possible places where it could land and return the array of "possible future" states. All of these states will have `null` `piece` because the piece is landed; some will have a positive `score`. */ getNextCoreStates: GetNextCoreStates = (core: CoreState, pieceId: string): CoreState[] => { const { rotationSystem, wellDepth, wellWidth } = this.props let piece = rotationSystem.placeNewPiece(wellWidth, pieceId) // move the piece down to a lower position before we have to // start pathfinding for it // move through empty rows while ( piece.y + 4 < wellDepth && // piece is above the bottom core.well[piece.y + 4] === 0 // nothing immediately below it ) { piece = this.getNextState({ core, ai: undefined, piece }, 'D').piece } const piecePositions = [piece] const seen = new Set() seen.add(this.hashCode(piece)) const possibleFutures: CoreState[] = [] // A simple `forEach` won't work here because we are appending to the list as we go let i = 0 while (i < piecePositions.length) { piece = piecePositions[i] // apply all possible moves moves.forEach(move => { const nextState = this.getNextState({ core, ai: undefined, piece }, move) const newPiece = nextState.piece if (newPiece === null) { // piece locked? better add that to the list // do NOT check locations, they aren't significant here possibleFutures.push(nextState.core) } else { // transform succeeded? // new location? append to list // check locations, they are significant const newHashCode = this.hashCode(newPiece) if (!seen.has(newHashCode)) { piecePositions.push(newPiece) seen.add(newHashCode) } } }) i++ } return possibleFutures } /** Input {wellState, piece} and a move, return the new {wellState, piece}. */ getNextState (wellState: WellState, move: string): WellState { const { rotationSystem, bar, wellDepth, wellWidth } = this.props let nextWell = wellState.core.well let nextScore = wellState.core.score const nextAiState = wellState.ai let nextPiece = { ...wellState.piece } // apply transform if (move === 'L') { nextPiece.x-- } if (move === 'R') { nextPiece.x++ } if (move === 'D') { nextPiece.y++ } if (move === 'U') { nextPiece.o = (nextPiece.o + 1) % 4 } const orientation = rotationSystem.rotations[nextPiece.id][nextPiece.o] const xActual = nextPiece.x + orientation.xMin const yActual = nextPiece.y + orientation.yMin if ( xActual < 0 || // off left side xActual + orientation.xDim > wellWidth || // off right side yActual < 0 || // off top (??) yActual + orientation.yDim > wellDepth || // off bottom orientation.rows.some((row, y) => wellState.core.well[yActual + y] & (row << xActual) ) // obstruction ) { if (move === 'D') { // Lock piece nextWell = wellState.core.well.slice() const orientation = rotationSystem.rotations[wellState.piece.id][wellState.piece.o] // this is the top left point in the bounding box of this orientation of this piece const xActual = wellState.piece.x + orientation.xMin const yActual = wellState.piece.y + orientation.yMin // row by row bitwise line alteration for (let row = 0; row < orientation.yDim; row++) { // can't negative bit-shift, but alas X can be negative nextWell[yActual + row] |= (orientation.rows[row] << xActual) } // check for complete lines now // NOTE: completed lines don't count if you've lost for (let row = 0; row < orientation.yDim; row++) { if ( yActual >= bar && nextWell[yActual + row] === (1 << wellWidth) - 1 ) { // move all lines above this point down for (let k = yActual + row; k > 1; k--) { nextWell[k] = nextWell[k - 1] } // insert a new blank line at the top // though of course the top line will always be blank anyway nextWell[0] = 0 nextScore++ } } nextPiece = null } else { // No move nextPiece = wellState.piece } } return { core: { well: nextWell, score: nextScore }, ai: nextAiState, piece: nextPiece } } handleClickStart = () => { const { replayCopiedTimeoutId, replayTimeoutId } = this.state // there may be a replay in progress, this // must be killed clearTimeout(replayTimeoutId) clearTimeout(replayCopiedTimeoutId) let firstWellState: WellState try { firstWellState = this.getFirstWellState() } catch (error) { console.error(error) this.setState({ error: { interpretation: 'Caught this exception while trying to generate the first piece using your custom enemy AI. Game abandoned.', real: error.message } }) return } // clear the field and get ready for a new game this.setState({ mode: 'PLAYING', wellStateId: 0, wellStates: [firstWellState], replay: [], replayCopiedTimeoutId: undefined, replayTimeoutId: undefined }) } handleClickSelectAi = () => { this.setState({ mode: 'SELECT_AI' }) } handleClickReplay = () => { const { replayTimeout } = this.props let { replayTimeoutId } = this.state // there may be a replay in progress, this // must be killed clearTimeout(replayTimeoutId) // user inputs replay string const string = window.prompt('Paste replay string...') if (string === null) { return } const replay = hatetrisReplayCodec.decode(string) // TODO: what if the replay is bad? let firstWellState: WellState try { firstWellState = this.getFirstWellState() } catch (error) { console.error(error) this.setState({ error: { interpretation: 'Caught this exception while trying to generate the first piece using your custom enemy AI. Game abandoned.', real: error.message } }) return } const wellStateId = 0 replayTimeoutId = wellStateId in replay ? setTimeout(this.handleReplayTimeout, replayTimeout) : undefined const mode = wellStateId in replay ? 'REPLAYING' : 'PLAYING' // GO. this.setState({ mode, wellStateId, wellStates: [firstWellState], replay, replayTimeoutId }) } handleReplayTimeout = () => { const { replayTimeout } = this.props const { mode, replay, wellStateId } = this.state let nextReplayTimeoutId if (mode === 'REPLAYING') { this.handleRedo() if (wellStateId + 1 in replay) { nextReplayTimeoutId = setTimeout(this.handleReplayTimeout, replayTimeout) } } else { console.warn('Ignoring input replay step because mode is', mode) } this.setState({ replayTimeoutId: nextReplayTimeoutId }) } // Accepts the input of a move and attempts to apply that // transform to the live piece in the live well. // Returns the new state. handleMove (move: string) { const { bar, rotationSystem, wellWidth } = this.props const { mode, replay, wellStateId, wellStates } = this.state const nextWellStateId = wellStateId + 1 let nextReplay let nextWellStates if (wellStateId in replay && move === replay[wellStateId]) { nextReplay = replay nextWellStates = wellStates } else { // Push the new move nextReplay = replay.slice(0, wellStateId).concat([move]) // And truncate the future nextWellStates = wellStates.slice(0, wellStateId + 1) } if (!(nextWellStateId in nextWellStates)) { const nextWellState = this.getNextState(nextWellStates[wellStateId], move) nextWellStates = [...nextWellStates, nextWellState] } const nextWellState = nextWellStates[nextWellStateId] // Is the game over? // It is impossible to get bits at row (bar - 2) or higher without getting a bit at // row (bar - 1), so there is only one line which we need to check. const gameIsOver = nextWellState.core.well[bar - 1] !== 0 const nextMode = gameIsOver ? 'GAME_OVER' : mode // no live piece? make a new one // suited to the new world, of course if (nextWellState.piece === null && nextMode !== 'GAME_OVER') { let pieceId: string let aiState: any try { // TODO: `nextWellState.core.well` should be more complex and contain colour // information, whereas the well passed to the AI should be a simple // array of integers [pieceId, aiState] = this.validateAiResult(nextWellState.core, nextWellState.ai) } catch (error) { console.error(error) this.setState({ error: { interpretation: 'Caught this exception while trying to generate a new piece using your custom AI. Game halted.', real: error.message } }) return } nextWellState.ai = aiState nextWellState.piece = rotationSystem.placeNewPiece(wellWidth, pieceId) } this.setState({ mode: nextMode, wellStateId: nextWellStateId, wellStates: nextWellStates, replay: nextReplay }) } handleLeft = () => { const { mode } = this.state if (mode === 'PLAYING') { this.handleMove('L') } else { console.warn('Ignoring event L because mode is', mode) } } handleRight = () => { const { mode } = this.state if (mode === 'PLAYING') { this.handleMove('R') } else { console.warn('Ignoring event R because mode is', mode) } } handleDown = () => { const { mode } = this.state if (mode === 'PLAYING') { this.handleMove('D') } else { console.warn('Ignoring event D because mode is', mode) } } handleUp = () => { const { mode } = this.state if (mode === 'PLAYING') { this.handleMove('U') } else { console.warn('Ignoring event U because mode is', mode) } } handleUndo = () => { const { replayTimeoutId, wellStateId, wellStates } = this.state // There may be a replay in progress, this // must be killed clearTimeout(replayTimeoutId) this.setState({ replayTimeoutId: undefined }) const nextWellStateId = wellStateId - 1 if (nextWellStateId in wellStates) { this.setState({ mode: 'PLAYING', wellStateId: nextWellStateId }) } else { console.warn('Ignoring undo event because start of history has been reached') } } handleRedo = () => { const { mode, replay, wellStateId } = this.state if (mode === 'PLAYING' || mode === 'REPLAYING') { if (wellStateId in replay) { this.handleMove(replay[wellStateId]) } else { console.warn('Ignoring redo event because end of history has been reached') } } else { console.warn('Ignoring redo event because mode is', mode) } } handleDocumentKeyDown = (event: KeyboardEvent) => { if (event.key === 'Left' || event.key === 'ArrowLeft') { this.handleLeft() } if (event.key === 'Right' || event.key === 'ArrowRight') { this.handleRight() } if (event.key === 'Down' || event.key === 'ArrowDown') { this.handleDown() } if (event.key === 'Up' || event.key === 'ArrowUp') { this.handleUp() } if (event.key === 'z' && event.ctrlKey === true) { this.handleUndo() } if (event.key === 'y' && event.ctrlKey === true) { this.handleRedo() } } handleClickCopyReplay = () => { const { replay } = this.state return navigator.clipboard.writeText(hatetrisReplayCodec.encode(replay)) .then(() => { const replayCopiedTimeoutId = setTimeout(this.handleCopiedTimeout, 3000) this.setState({ replayCopiedTimeoutId }) }) } handleCopiedTimeout = () => { this.setState({ replayCopiedTimeoutId: undefined }) } handleClickDone = () => { this.setState({ mode: 'INITIAL' }) } handleClickEnemy = (enemy: Enemy) => { this.setState({ displayEnemy: true, enemy, mode: 'INITIAL' }) } handleClickCustomEnemy = () => { this.setState({ mode: 'PASTE' }) } handleCancelCustomEnemy = () => { this.setState({ mode: 'SELECT_AI' }) } handleCustomAiChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { this.setState({ customAiCode: event.target.value }) } handleSubmitCustomEnemy = () => { const { customAiCode } = this.state let ai: EnemyAi try { // eslint-disable-next-line no-new-func ai = Function(` "use strict" return (${customAiCode}) `)() } catch (error) { console.error(error) this.setState({ error: { interpretation: 'Caught this exception while trying to evaluate your custom AI JavaScript.', real: error.message } }) return } this.handleClickEnemy({ shortDescription: 'custom', buttonDescription: 'this is never actually used', ai }) } handleClickDismissError = () => { this.setState({ error: null }) } render () { const { bar, rotationSystem, wellDepth, wellWidth } = this.props const { customAiCode, displayEnemy, enemy, error, mode, replay, replayCopiedTimeoutId, wellStateId, wellStates } = this.state const wellState = wellStateId === -1 ? null : wellStates[wellStateId] const score = wellState && wellState.core.score if (error !== null) { return ( <div className='game'> <h2 style={{ fontWeight: 'bold', fontSize: '150%' }}>Error</h2> <p> <code style={{ fontFamily: 'monospace' }}>{error.real}</code> </p> <p> {error.interpretation} </p> <h3 style={{ fontWeight: 'bold' }}>To fix this</h3> <p> Check your browser console for more information. Use this information to fix your AI code and submit it again. Or, use one of the preset AIs instead. </p> <p> <button className='game__button e2e__dismiss-error' type='button' onClick={this.handleClickDismissError} > OK </button> </p> </div> ) } return ( <div className='game'> <div className='game__top'> <div className='game__topleft'> <Well bar={bar} rotationSystem={rotationSystem} wellDepth={wellDepth} wellWidth={wellWidth} wellState={wellState} /> </div> <div className='game__topright'> <p className='game__paragraph'> you&apos;re playing <b>HATETRIS</b> by qntm </p> {displayEnemy && ( <p className='game__paragraph e2e__enemy-short'> AI: {enemy.shortDescription} </p> )} {score !== null && ( <p className='game__paragraph e2e__score'> score: {score} </p> )} <div className='game__spacer' /> <p className='game__paragraph'> <a href='http://qntm.org/hatetris'> about </a> </p> <p className='game__paragraph'> <a href='https://github.com/qntm/hatetris'> source code </a> </p> <p className='game__paragraph'> replays encoded using <a href='https://github.com/qntm/base2048'>Base2048</a> </p> </div> </div> {mode === 'INITIAL' && ( <div className='game__bottom'> <button className='game__button e2e__start-button' type='button' onClick={this.handleClickStart} > start new game </button> <div className='game__paragraph' style={{ display: 'flex', gap: '10px' }}> <button className='game__button e2e__replay-button' type='button' onClick={this.handleClickReplay} > show a replay </button> <button className='game__button e2e__select-ai' type='button' onClick={this.handleClickSelectAi} > select AI </button> </div> </div> )} {mode === 'SELECT_AI' && ( <div className='game__bottom game__bottom--select-ai'> <p> Select AI: </p> { enemies.map(enemy => ( <button className='game__button e2e__enemy' key={enemy.buttonDescription} type='button' onClick={() => this.handleClickEnemy(enemy)} > {enemy.buttonDescription} </button> )) } <button className='game__button e2e__custom-enemy' type='button' onClick={this.handleClickCustomEnemy} > use custom AI </button> </div> )} {mode === 'PASTE' && ( <div className='game__bottom'> <p>Enter custom code:</p> <div> <textarea autoFocus style={{ width: '100%' }} onChange={this.handleCustomAiChange} className='e2e__ai-textarea' > {customAiCode} </textarea> </div> <div style={{ display: 'flex', gap: '10px' }}> <p style={{ flex: '1 1 100%' }}> <a href="https://github.com/qntm/hatetris#writing-a-custom-ai"> how to write a custom AI </a> </p> <button className='game__button e2e__cancel-custom-enemy' type='button' onClick={this.handleCancelCustomEnemy} > cancel </button> <button className='game__button e2e__submit-custom-enemy' type='button' onClick={this.handleSubmitCustomEnemy} > go </button> </div> </div> )} {mode === 'PLAYING' && ( <div className='game__bottom'> <div style={{ display: 'flex', gap: '10px' }}> <button className='game__button' disabled={!(wellStateId - 1 in wellStates)} type='button' onClick={this.handleUndo} title='Press Ctrl+Z to undo' > ↶ </button> <button className='game__button e2e__up' type='button' onClick={this.handleUp} title='Press Up to rotate' > ⟳ </button> <button className='game__button' disabled={!(wellStateId + 1 in wellStates)} type='button' onClick={this.handleRedo} title='Press Ctrl+Y to redo' > ↷ </button> </div> <div style={{ display: 'flex', gap: '10px' }}> <button className='game__button e2e__left' type='button' onClick={this.handleLeft} title='Press Left to move left' > ← </button> <button className='game__button e2e__down' type='button' onClick={this.handleDown} title='Press Down to move down' > ↓ </button> <button className='game__button e2e__right' type='button' onClick={this.handleRight} title='Press Right to move right' > → </button> </div> </div> )} {mode === 'REPLAYING' && ( <div className='game__bottom'> replaying... </div> )} {mode === 'GAME_OVER' && ( <div className='game__bottom'> <div> replay of last game: </div> <div className='game__replay-out e2e__replay-out'> {hatetrisReplayCodec.encode(replay)} </div> <div style={{ display: 'flex', gap: '10px' }}> <button className='game__button e2e__replay-button' type='button' onClick={this.handleUndo} > undo last move </button> <button className='game__button e2e__copy-replay' type='button' onClick={this.handleClickCopyReplay} > {replayCopiedTimeoutId ? 'copied!' : 'copy replay'} </button> <button className='game__button e2e__done' type='button' onClick={this.handleClickDone} > done </button> </div> </div> )} </div> ) } componentDidMount () { document.addEventListener('keydown', this.handleDocumentKeyDown) } componentWillUnmount () { const { replayCopiedTimeoutId, replayTimeoutId } = this.state clearTimeout(replayCopiedTimeoutId) clearTimeout(replayTimeoutId) document.removeEventListener('keydown', this.handleDocumentKeyDown) } } export default Game
the_stack
import { analyzeTokenTypes, charCodeToOptimizedIndex, cloneEmptyGroups, DEFAULT_MODE, LineTerminatorOptimizedTester, performRuntimeChecks, performWarningRuntimeChecks, SUPPORT_STICKY, validatePatterns } from "./lexer" import { cloneArr, cloneObj, forEach, IDENTITY, isArray, isEmpty, isUndefined, keys, last, map, merge, NOOP, PRINT_WARNING, reduce, reject, timer, toFastProperties } from "@chevrotain/utils" import { augmentTokenTypes } from "./tokens" import { CustomPatternMatcherFunc, ILexerConfig, ILexerDefinitionError, ILexingError, IMultiModeLexerDefinition, IToken, TokenType } from "@chevrotain/types" import { defaultLexerErrorProvider } from "../scan/lexer_errors_public" import { clearRegExpParserCache } from "./reg_exp_parser" export interface ILexingResult { tokens: IToken[] groups: { [groupName: string]: IToken[] } errors: ILexingError[] } export enum LexerDefinitionErrorType { MISSING_PATTERN, INVALID_PATTERN, EOI_ANCHOR_FOUND, UNSUPPORTED_FLAGS_FOUND, DUPLICATE_PATTERNS_FOUND, INVALID_GROUP_TYPE_FOUND, PUSH_MODE_DOES_NOT_EXIST, MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE, MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY, MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST, LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED, SOI_ANCHOR_FOUND, EMPTY_MATCH_PATTERN, NO_LINE_BREAKS_FLAGS, UNREACHABLE_PATTERN, IDENTIFY_TERMINATOR, CUSTOM_LINE_BREAK } export interface IRegExpExec { exec: CustomPatternMatcherFunc } const DEFAULT_LEXER_CONFIG: ILexerConfig = { deferDefinitionErrorsHandling: false, positionTracking: "full", lineTerminatorsPattern: /\n|\r\n?/g, lineTerminatorCharacters: ["\n", "\r"], ensureOptimizations: false, safeMode: false, errorMessageProvider: defaultLexerErrorProvider, traceInitPerf: false, skipValidations: false } Object.freeze(DEFAULT_LEXER_CONFIG) export class Lexer { public static SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" + "be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace." public static NA = /NOT_APPLICABLE/ public lexerDefinitionErrors: ILexerDefinitionError[] = [] public lexerDefinitionWarning: ILexerDefinitionError[] = [] protected patternIdxToConfig: any = {} protected charCodeToPatternIdxToConfig: any = {} protected modes: string[] = [] protected defaultMode: string protected emptyGroups: { [groupName: string]: IToken } = {} private config: ILexerConfig = undefined private trackStartLines: boolean = true private trackEndLines: boolean = true private hasCustom: boolean = false private canModeBeOptimized: any = {} private traceInitPerf: boolean | number private traceInitMaxIdent: number private traceInitIndent: number constructor( protected lexerDefinition: TokenType[] | IMultiModeLexerDefinition, config: ILexerConfig = DEFAULT_LEXER_CONFIG ) { if (typeof config === "boolean") { throw Error( "The second argument to the Lexer constructor is now an ILexerConfig Object.\n" + "a boolean 2nd argument is no longer supported" ) } // todo: defaults func? this.config = merge(DEFAULT_LEXER_CONFIG, config) const traceInitVal = this.config.traceInitPerf if (traceInitVal === true) { this.traceInitMaxIdent = Infinity this.traceInitPerf = true } else if (typeof traceInitVal === "number") { this.traceInitMaxIdent = traceInitVal this.traceInitPerf = true } this.traceInitIndent = -1 this.TRACE_INIT("Lexer Constructor", () => { let actualDefinition: IMultiModeLexerDefinition let hasOnlySingleMode = true this.TRACE_INIT("Lexer Config handling", () => { if ( this.config.lineTerminatorsPattern === DEFAULT_LEXER_CONFIG.lineTerminatorsPattern ) { // optimized built-in implementation for the defaults definition of lineTerminators this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester } else { if ( this.config.lineTerminatorCharacters === DEFAULT_LEXER_CONFIG.lineTerminatorCharacters ) { throw Error( "Error: Missing <lineTerminatorCharacters> property on the Lexer config.\n" + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS" ) } } if (config.safeMode && config.ensureOptimizations) { throw Error( '"safeMode" and "ensureOptimizations" flags are mutually exclusive.' ) } this.trackStartLines = /full|onlyStart/i.test( this.config.positionTracking ) this.trackEndLines = /full/i.test(this.config.positionTracking) // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition. if (isArray(lexerDefinition)) { actualDefinition = <any>{ modes: {} } actualDefinition.modes[DEFAULT_MODE] = cloneArr( <TokenType[]>lexerDefinition ) actualDefinition[DEFAULT_MODE] = DEFAULT_MODE } else { // no conversion needed, input should already be a IMultiModeLexerDefinition hasOnlySingleMode = false actualDefinition = cloneObj( <IMultiModeLexerDefinition>lexerDefinition ) } }) if (this.config.skipValidations === false) { this.TRACE_INIT("performRuntimeChecks", () => { this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat( performRuntimeChecks( actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters ) ) }) this.TRACE_INIT("performWarningRuntimeChecks", () => { this.lexerDefinitionWarning = this.lexerDefinitionWarning.concat( performWarningRuntimeChecks( actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters ) ) }) } // for extra robustness to avoid throwing an none informative error message actualDefinition.modes = actualDefinition.modes ? actualDefinition.modes : {} // an error of undefined TokenTypes will be detected in "performRuntimeChecks" above. // this transformation is to increase robustness in the case of partially invalid lexer definition. forEach(actualDefinition.modes, (currModeValue, currModeName) => { actualDefinition.modes[currModeName] = reject<TokenType>( currModeValue, (currTokType) => isUndefined(currTokType) ) }) const allModeNames = keys(actualDefinition.modes) forEach( actualDefinition.modes, (currModDef: TokenType[], currModName) => { this.TRACE_INIT(`Mode: <${currModName}> processing`, () => { this.modes.push(currModName) if (this.config.skipValidations === false) { this.TRACE_INIT(`validatePatterns`, () => { this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat( validatePatterns(<TokenType[]>currModDef, allModeNames) ) }) } // If definition errors were encountered, the analysis phase may fail unexpectedly/ // Considering a lexer with definition errors may never be used, there is no point // to performing the analysis anyhow... if (isEmpty(this.lexerDefinitionErrors)) { augmentTokenTypes(currModDef) let currAnalyzeResult this.TRACE_INIT(`analyzeTokenTypes`, () => { currAnalyzeResult = analyzeTokenTypes(currModDef, { lineTerminatorCharacters: this.config.lineTerminatorCharacters, positionTracking: config.positionTracking, ensureOptimizations: config.ensureOptimizations, safeMode: config.safeMode, tracer: this.TRACE_INIT.bind(this) }) }) this.patternIdxToConfig[currModName] = currAnalyzeResult.patternIdxToConfig this.charCodeToPatternIdxToConfig[currModName] = currAnalyzeResult.charCodeToPatternIdxToConfig this.emptyGroups = merge( this.emptyGroups, currAnalyzeResult.emptyGroups ) this.hasCustom = currAnalyzeResult.hasCustom || this.hasCustom this.canModeBeOptimized[currModName] = currAnalyzeResult.canBeOptimized } }) } ) this.defaultMode = actualDefinition.defaultMode if ( !isEmpty(this.lexerDefinitionErrors) && !this.config.deferDefinitionErrorsHandling ) { const allErrMessages = map(this.lexerDefinitionErrors, (error) => { return error.message }) const allErrMessagesString = allErrMessages.join( "-----------------------\n" ) throw new Error( "Errors detected in definition of Lexer:\n" + allErrMessagesString ) } // Only print warning if there are no errors, This will avoid pl forEach(this.lexerDefinitionWarning, (warningDescriptor) => { PRINT_WARNING(warningDescriptor.message) }) this.TRACE_INIT("Choosing sub-methods implementations", () => { // Choose the relevant internal implementations for this specific parser. // These implementations should be in-lined by the JavaScript engine // to provide optimal performance in each scenario. if (SUPPORT_STICKY) { this.chopInput = <any>IDENTITY this.match = this.matchWithTest } else { this.updateLastIndex = NOOP this.match = this.matchWithExec } if (hasOnlySingleMode) { this.handleModes = NOOP } if (this.trackStartLines === false) { this.computeNewColumn = IDENTITY } if (this.trackEndLines === false) { this.updateTokenEndLineColumnLocation = NOOP } if (/full/i.test(this.config.positionTracking)) { this.createTokenInstance = this.createFullToken } else if (/onlyStart/i.test(this.config.positionTracking)) { this.createTokenInstance = this.createStartOnlyToken } else if (/onlyOffset/i.test(this.config.positionTracking)) { this.createTokenInstance = this.createOffsetOnlyToken } else { throw Error( `Invalid <positionTracking> config option: "${this.config.positionTracking}"` ) } if (this.hasCustom) { this.addToken = this.addTokenUsingPush this.handlePayload = this.handlePayloadWithCustom } else { this.addToken = this.addTokenUsingMemberAccess this.handlePayload = this.handlePayloadNoCustom } }) this.TRACE_INIT("Failed Optimization Warnings", () => { const unOptimizedModes = reduce( this.canModeBeOptimized, (cannotBeOptimized, canBeOptimized, modeName) => { if (canBeOptimized === false) { cannotBeOptimized.push(modeName) } return cannotBeOptimized }, [] ) if (config.ensureOptimizations && !isEmpty(unOptimizedModes)) { throw Error( `Lexer Modes: < ${unOptimizedModes.join( ", " )} > cannot be optimized.\n` + '\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' + "\t Or inspect the console log for details on how to resolve these issues." ) } }) this.TRACE_INIT("clearRegExpParserCache", () => { clearRegExpParserCache() }) this.TRACE_INIT("toFastProperties", () => { toFastProperties(this) }) }) } public tokenize( text: string, initialMode: string = this.defaultMode ): ILexingResult { if (!isEmpty(this.lexerDefinitionErrors)) { const allErrMessages = map(this.lexerDefinitionErrors, (error) => { return error.message }) const allErrMessagesString = allErrMessages.join( "-----------------------\n" ) throw new Error( "Unable to Tokenize because Errors detected in definition of Lexer:\n" + allErrMessagesString ) } const lexResult = this.tokenizeInternal(text, initialMode) return lexResult } // There is quite a bit of duplication between this and "tokenizeInternalLazy" // This is intentional due to performance considerations. private tokenizeInternal(text: string, initialMode: string): ILexingResult { let i, j, k, matchAltImage, longerAlt, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, droppedChar, msg, match const orgText = text const orgLength = orgText.length let offset = 0 let matchedTokensIndex = 0 // initializing the tokensArray to the "guessed" size. // guessing too little will still reduce the number of array re-sizes on pushes. // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory // but would still have a faster runtime by avoiding (All but one) array resizing. const guessedNumberOfTokens = this.hasCustom ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements. : Math.floor(text.length / 10) const matchedTokens = new Array(guessedNumberOfTokens) const errors: ILexingError[] = [] let line = this.trackStartLines ? 1 : undefined let column = this.trackStartLines ? 1 : undefined const groups: any = cloneEmptyGroups(this.emptyGroups) const trackLines = this.trackStartLines const lineTerminatorPattern = this.config.lineTerminatorsPattern let currModePatternsLength = 0 let patternIdxToConfig = [] let currCharCodeToPatternIdxToConfig = [] const modeStack = [] const emptyArray = [] Object.freeze(emptyArray) let getPossiblePatterns = undefined function getPossiblePatternsSlow() { return patternIdxToConfig } function getPossiblePatternsOptimized(charCode) { const optimizedCharIdx = charCodeToOptimizedIndex(charCode) const possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx] if (possiblePatterns === undefined) { return emptyArray } else { return possiblePatterns } } const pop_mode = (popToken) => { // TODO: perhaps avoid this error in the edge case there is no more input? if ( modeStack.length === 1 && // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition" // So no error should occur. popToken.tokenType.PUSH_MODE === undefined ) { // if we try to pop the last mode there lexer will no longer have ANY mode. // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode. const msg = this.config.errorMessageProvider.buildUnableToPopLexerModeMessage( popToken ) errors.push({ offset: popToken.startOffset, line: popToken.startLine !== undefined ? popToken.startLine : undefined, column: popToken.startColumn !== undefined ? popToken.startColumn : undefined, length: popToken.image.length, message: msg }) } else { modeStack.pop() const newMode = last(modeStack) patternIdxToConfig = this.patternIdxToConfig[newMode] currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode] currModePatternsLength = patternIdxToConfig.length const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { getPossiblePatterns = getPossiblePatternsOptimized } else { getPossiblePatterns = getPossiblePatternsSlow } } } function push_mode(newMode) { modeStack.push(newMode) currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode] patternIdxToConfig = this.patternIdxToConfig[newMode] currModePatternsLength = patternIdxToConfig.length currModePatternsLength = patternIdxToConfig.length const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { getPossiblePatterns = getPossiblePatternsOptimized } else { getPossiblePatterns = getPossiblePatternsSlow } } // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not // seem to matter performance wise. push_mode.call(this, initialMode) let currConfig while (offset < orgLength) { matchedImage = null const nextCharCode = orgText.charCodeAt(offset) const chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode) const chosenPatternsLength = chosenPatternIdxToConfig.length for (i = 0; i < chosenPatternsLength; i++) { currConfig = chosenPatternIdxToConfig[i] const currPattern = currConfig.pattern payload = null // manually in-lined because > 600 chars won't be in-lined in V8 const singleCharCode = currConfig.short if (singleCharCode !== false) { if (nextCharCode === singleCharCode) { // single character string matchedImage = currPattern } } else if (currConfig.isCustom === true) { match = currPattern.exec(orgText, offset, matchedTokens, groups) if (match !== null) { matchedImage = match[0] if (match.payload !== undefined) { payload = match.payload } } else { matchedImage = null } } else { this.updateLastIndex(currPattern, offset) matchedImage = this.match(currPattern, text, offset) } if (matchedImage !== null) { // even though this pattern matched we must try a another longer alternative. // this can be used to prioritize keywords over identifiers longerAlt = currConfig.longerAlt if (longerAlt !== undefined) { // TODO: micro optimize, avoid extra prop access // by saving/linking longerAlt on the original config? const longerAltLength = longerAlt.length for (k = 0; k < longerAltLength; k++) { const longerAltConfig = patternIdxToConfig[longerAlt[k]] const longerAltPattern = longerAltConfig.pattern altPayload = null // single Char can never be a longer alt so no need to test it. // manually in-lined because > 600 chars won't be in-lined in V8 if (longerAltConfig.isCustom === true) { match = longerAltPattern.exec( orgText, offset, matchedTokens, groups ) if (match !== null) { matchAltImage = match[0] if (match.payload !== undefined) { altPayload = match.payload } } else { matchAltImage = null } } else { this.updateLastIndex(longerAltPattern, offset) matchAltImage = this.match(longerAltPattern, text, offset) } if (matchAltImage && matchAltImage.length > matchedImage.length) { matchedImage = matchAltImage payload = altPayload currConfig = longerAltConfig // Exit the loop early after matching one of the longer alternatives // The first matched alternative takes precedence break } } } break } } // successful match if (matchedImage !== null) { imageLength = matchedImage.length group = currConfig.group if (group !== undefined) { tokType = currConfig.tokenTypeIdx // TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside // createFullToken method newToken = this.createTokenInstance( matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength ) this.handlePayload(newToken, payload) // TODO: optimize NOOP in case there are no special groups? if (group === false) { matchedTokensIndex = this.addToken( matchedTokens, matchedTokensIndex, newToken ) } else { groups[group].push(newToken) } } text = this.chopInput(text, imageLength) offset = offset + imageLength // TODO: with newlines the column may be assigned twice column = this.computeNewColumn(column, imageLength) if (trackLines === true && currConfig.canLineTerminator === true) { let numOfLTsInMatch = 0 let foundTerminator let lastLTEndOffset lineTerminatorPattern.lastIndex = 0 do { foundTerminator = lineTerminatorPattern.test(matchedImage) if (foundTerminator === true) { lastLTEndOffset = lineTerminatorPattern.lastIndex - 1 numOfLTsInMatch++ } } while (foundTerminator === true) if (numOfLTsInMatch !== 0) { line = line + numOfLTsInMatch column = imageLength - lastLTEndOffset this.updateTokenEndLineColumnLocation( newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength ) } } // will be NOOP if no modes present this.handleModes(currConfig, pop_mode, push_mode, newToken) } else { // error recovery, drop characters until we identify a valid token's start point const errorStartOffset = offset const errorLine = line const errorColumn = column let foundResyncPoint = false while (!foundResyncPoint && offset < orgLength) { // drop chars until we succeed in matching something droppedChar = orgText.charCodeAt(offset) // Identity Func (when sticky flag is enabled) text = this.chopInput(text, 1) offset++ for (j = 0; j < currModePatternsLength; j++) { const currConfig = patternIdxToConfig[j] const currPattern = currConfig.pattern // manually in-lined because > 600 chars won't be in-lined in V8 const singleCharCode = currConfig.short if (singleCharCode !== false) { if (orgText.charCodeAt(offset) === singleCharCode) { // single character string foundResyncPoint = true } } else if (currConfig.isCustom === true) { foundResyncPoint = currPattern.exec(orgText, offset, matchedTokens, groups) !== null } else { this.updateLastIndex(currPattern, offset) foundResyncPoint = currPattern.exec(text) !== null } if (foundResyncPoint === true) { break } } } errLength = offset - errorStartOffset // at this point we either re-synced or reached the end of the input text msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage( orgText, errorStartOffset, errLength, errorLine, errorColumn ) errors.push({ offset: errorStartOffset, line: errorLine, column: errorColumn, length: errLength, message: msg }) } } // if we do have custom patterns which push directly into the // TODO: custom tokens should not push directly?? if (!this.hasCustom) { // if we guessed a too large size for the tokens array this will shrink it to the right size. matchedTokens.length = matchedTokensIndex } return { tokens: matchedTokens, groups: groups, errors: errors } } private handleModes(config, pop_mode, push_mode, newToken) { if (config.pop === true) { // need to save the PUSH_MODE property as if the mode is popped // patternIdxToPopMode is updated to reflect the new mode after popping the stack const pushMode = config.push pop_mode(newToken) if (pushMode !== undefined) { push_mode.call(this, pushMode) } } else if (config.push !== undefined) { push_mode.call(this, config.push) } } private chopInput(text, length): string { return text.substring(length) } private updateLastIndex(regExp, newLastIndex): void { regExp.lastIndex = newLastIndex } // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler private updateTokenEndLineColumnLocation( newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength ): void { let lastCharIsLT, fixForEndingInLT if (group !== undefined) { // a none skipped multi line Token, need to update endLine/endColumn lastCharIsLT = lastLTIdx === imageLength - 1 fixForEndingInLT = lastCharIsLT ? -1 : 0 if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) { // if a token ends in a LT that last LT only affects the line numbering of following Tokens newToken.endLine = line + fixForEndingInLT // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd) // inclusive to exclusive range. newToken.endColumn = column - 1 + -fixForEndingInLT } // else single LT in the last character of a token, no need to modify the endLine/EndColumn } } private computeNewColumn(oldColumn, imageLength) { return oldColumn + imageLength } // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime. /* istanbul ignore next - place holder */ private createTokenInstance(...args: any[]): IToken { return null } private createOffsetOnlyToken(image, startOffset, tokenTypeIdx, tokenType) { return { image, startOffset, tokenTypeIdx, tokenType } } private createStartOnlyToken( image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn ) { return { image, startOffset, startLine, startColumn, tokenTypeIdx, tokenType } } private createFullToken( image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength ) { return { image, startOffset, endOffset: startOffset + imageLength - 1, startLine, endLine: startLine, startColumn, endColumn: startColumn + imageLength - 1, tokenTypeIdx, tokenType } } // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime. /* istanbul ignore next - place holder */ private addToken(tokenVector, index, tokenToAdd): number { return 666 } private addTokenUsingPush(tokenVector, index, tokenToAdd): number { tokenVector.push(tokenToAdd) return index } private addTokenUsingMemberAccess(tokenVector, index, tokenToAdd): number { tokenVector[index] = tokenToAdd index++ return index } // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime. /* istanbul ignore next - place holder */ private handlePayload(token: IToken, payload: any): void {} private handlePayloadNoCustom(token: IToken, payload: any): void {} private handlePayloadWithCustom(token: IToken, payload: any): void { if (payload !== null) { token.payload = payload } } /* istanbul ignore next - place holder to be replaced with chosen alternative at runtime */ private match(pattern: RegExp, text: string, offset?: number): string { return null } private matchWithTest(pattern: RegExp, text: string, offset: number): string { const found = pattern.test(text) if (found === true) { return text.substring(offset, pattern.lastIndex) } return null } private matchWithExec(pattern, text): string { const regExpArray = pattern.exec(text) return regExpArray !== null ? regExpArray[0] : regExpArray } // Duplicated from the parser's perf trace trait to allow future extraction // of the lexer to a separate package. TRACE_INIT<T>(phaseDesc: string, phaseImpl: () => T): T { // No need to optimize this using NOOP pattern because // It is not called in a hot spot... if (this.traceInitPerf === true) { this.traceInitIndent++ const indent = new Array(this.traceInitIndent + 1).join("\t") if (this.traceInitIndent < this.traceInitMaxIdent) { console.log(`${indent}--> <${phaseDesc}>`) } const { time, value } = timer(phaseImpl) /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ const traceMethod = time > 10 ? console.warn : console.log if (this.traceInitIndent < this.traceInitMaxIdent) { traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`) } this.traceInitIndent-- return value } else { return phaseImpl() } } }
the_stack
declare const enum CBATTError { Success = 0, InvalidHandle = 1, ReadNotPermitted = 2, WriteNotPermitted = 3, InvalidPdu = 4, InsufficientAuthentication = 5, RequestNotSupported = 6, InvalidOffset = 7, InsufficientAuthorization = 8, PrepareQueueFull = 9, AttributeNotFound = 10, AttributeNotLong = 11, InsufficientEncryptionKeySize = 12, InvalidAttributeValueLength = 13, UnlikelyError = 14, InsufficientEncryption = 15, UnsupportedGroupType = 16, InsufficientResources = 17 } declare var CBATTErrorDomain: string; declare class CBATTRequest extends NSObject { static alloc(): CBATTRequest; // inherited from NSObject static new(): CBATTRequest; // inherited from NSObject readonly central: CBCentral; readonly characteristic: CBCharacteristic; readonly offset: number; value: NSData; } declare var CBAdvertisementDataIsConnectable: string; declare var CBAdvertisementDataLocalNameKey: string; declare var CBAdvertisementDataManufacturerDataKey: string; declare var CBAdvertisementDataOverflowServiceUUIDsKey: string; declare var CBAdvertisementDataServiceDataKey: string; declare var CBAdvertisementDataServiceUUIDsKey: string; declare var CBAdvertisementDataSolicitedServiceUUIDsKey: string; declare var CBAdvertisementDataTxPowerLevelKey: string; declare class CBAttribute extends NSObject { static alloc(): CBAttribute; // inherited from NSObject static new(): CBAttribute; // inherited from NSObject readonly UUID: CBUUID; } declare const enum CBAttributePermissions { Readable = 1, Writeable = 2, ReadEncryptionRequired = 4, WriteEncryptionRequired = 8 } declare class CBCentral extends CBPeer { static alloc(): CBCentral; // inherited from NSObject static new(): CBCentral; // inherited from NSObject readonly maximumUpdateValueLength: number; } declare class CBCentralManager extends CBManager { static alloc(): CBCentralManager; // inherited from NSObject static new(): CBCentralManager; // inherited from NSObject static supportsFeatures(features: CBCentralManagerFeature): boolean; delegate: CBCentralManagerDelegate; readonly isScanning: boolean; constructor(o: { delegate: CBCentralManagerDelegate; queue: NSObject; }); constructor(o: { delegate: CBCentralManagerDelegate; queue: NSObject; options: NSDictionary<string, any>; }); cancelPeripheralConnection(peripheral: CBPeripheral): void; connectPeripheralOptions(peripheral: CBPeripheral, options: NSDictionary<string, any>): void; initWithDelegateQueue(delegate: CBCentralManagerDelegate, queue: NSObject): this; initWithDelegateQueueOptions(delegate: CBCentralManagerDelegate, queue: NSObject, options: NSDictionary<string, any>): this; registerForConnectionEventsWithOptions(options: NSDictionary<string, any>): void; retrieveConnectedPeripheralsWithServices(serviceUUIDs: NSArray<CBUUID> | CBUUID[]): NSArray<CBPeripheral>; retrievePeripheralsWithIdentifiers(identifiers: NSArray<NSUUID> | NSUUID[]): NSArray<CBPeripheral>; scanForPeripheralsWithServicesOptions(serviceUUIDs: NSArray<CBUUID> | CBUUID[], options: NSDictionary<string, any>): void; stopScan(): void; } interface CBCentralManagerDelegate extends NSObjectProtocol { centralManagerConnectionEventDidOccurForPeripheral?(central: CBCentralManager, event: CBConnectionEvent, peripheral: CBPeripheral): void; centralManagerDidConnectPeripheral?(central: CBCentralManager, peripheral: CBPeripheral): void; centralManagerDidDisconnectPeripheralError?(central: CBCentralManager, peripheral: CBPeripheral, error: NSError): void; centralManagerDidDiscoverPeripheralAdvertisementDataRSSI?(central: CBCentralManager, peripheral: CBPeripheral, advertisementData: NSDictionary<string, any>, RSSI: number): void; centralManagerDidFailToConnectPeripheralError?(central: CBCentralManager, peripheral: CBPeripheral, error: NSError): void; centralManagerDidUpdateANCSAuthorizationForPeripheral?(central: CBCentralManager, peripheral: CBPeripheral): void; centralManagerDidUpdateState(central: CBCentralManager): void; centralManagerWillRestoreState?(central: CBCentralManager, dict: NSDictionary<string, any>): void; } declare var CBCentralManagerDelegate: { prototype: CBCentralManagerDelegate; }; declare const enum CBCentralManagerFeature { ExtendedScanAndConnect = 1 } declare var CBCentralManagerOptionRestoreIdentifierKey: string; declare var CBCentralManagerOptionShowPowerAlertKey: string; declare var CBCentralManagerRestoredStatePeripheralsKey: string; declare var CBCentralManagerRestoredStateScanOptionsKey: string; declare var CBCentralManagerRestoredStateScanServicesKey: string; declare var CBCentralManagerScanOptionAllowDuplicatesKey: string; declare var CBCentralManagerScanOptionSolicitedServiceUUIDsKey: string; declare const enum CBCentralManagerState { Unknown = 0, Resetting = 1, Unsupported = 2, Unauthorized = 3, PoweredOff = 4, PoweredOn = 5 } declare class CBCharacteristic extends CBAttribute { static alloc(): CBCharacteristic; // inherited from NSObject static new(): CBCharacteristic; // inherited from NSObject readonly descriptors: NSArray<CBDescriptor>; readonly isBroadcasted: boolean; readonly isNotifying: boolean; readonly properties: CBCharacteristicProperties; readonly service: CBService; readonly value: NSData; } declare const enum CBCharacteristicProperties { PropertyBroadcast = 1, PropertyRead = 2, PropertyWriteWithoutResponse = 4, PropertyWrite = 8, PropertyNotify = 16, PropertyIndicate = 32, PropertyAuthenticatedSignedWrites = 64, PropertyExtendedProperties = 128, PropertyNotifyEncryptionRequired = 256, PropertyIndicateEncryptionRequired = 512 } declare const enum CBCharacteristicWriteType { WithResponse = 0, WithoutResponse = 1 } declare var CBConnectPeripheralOptionEnableTransportBridgingKey: string; declare var CBConnectPeripheralOptionNotifyOnConnectionKey: string; declare var CBConnectPeripheralOptionNotifyOnDisconnectionKey: string; declare var CBConnectPeripheralOptionNotifyOnNotificationKey: string; declare var CBConnectPeripheralOptionRequiresANCS: string; declare var CBConnectPeripheralOptionStartDelayKey: string; declare const enum CBConnectionEvent { PeerDisconnected = 0, PeerConnected = 1 } declare var CBConnectionEventMatchingOptionPeripheralUUIDs: string; declare var CBConnectionEventMatchingOptionServiceUUIDs: string; declare class CBDescriptor extends CBAttribute { static alloc(): CBDescriptor; // inherited from NSObject static new(): CBDescriptor; // inherited from NSObject readonly characteristic: CBCharacteristic; readonly value: any; } declare const enum CBError { Unknown = 0, InvalidParameters = 1, InvalidHandle = 2, NotConnected = 3, OutOfSpace = 4, OperationCancelled = 5, ConnectionTimeout = 6, PeripheralDisconnected = 7, UUIDNotAllowed = 8, AlreadyAdvertising = 9, ConnectionFailed = 10, ConnectionLimitReached = 11, UnkownDevice = 12, UnknownDevice = 12, OperationNotSupported = 13, PeerRemovedPairingInformation = 14, EncryptionTimedOut = 15, TooManyLEPairedDevices = 16 } declare var CBErrorDomain: string; declare class CBL2CAPChannel extends NSObject { static alloc(): CBL2CAPChannel; // inherited from NSObject static new(): CBL2CAPChannel; // inherited from NSObject readonly PSM: number; readonly inputStream: NSInputStream; readonly outputStream: NSOutputStream; readonly peer: CBPeer; } declare class CBManager extends NSObject { static alloc(): CBManager; // inherited from NSObject static new(): CBManager; // inherited from NSObject readonly authorization: CBManagerAuthorization; readonly state: CBManagerState; static readonly authorization: CBManagerAuthorization; } declare const enum CBManagerAuthorization { NotDetermined = 0, Restricted = 1, Denied = 2, AllowedAlways = 3 } declare const enum CBManagerState { Unknown = 0, Resetting = 1, Unsupported = 2, Unauthorized = 3, PoweredOff = 4, PoweredOn = 5 } declare class CBMutableCharacteristic extends CBCharacteristic { static alloc(): CBMutableCharacteristic; // inherited from NSObject static new(): CBMutableCharacteristic; // inherited from NSObject descriptors: NSArray<CBDescriptor>; permissions: CBAttributePermissions; properties: CBCharacteristicProperties; readonly subscribedCentrals: NSArray<CBCentral>; value: NSData; constructor(o: { type: CBUUID; properties: CBCharacteristicProperties; value: NSData; permissions: CBAttributePermissions; }); initWithTypePropertiesValuePermissions(UUID: CBUUID, properties: CBCharacteristicProperties, value: NSData, permissions: CBAttributePermissions): this; } declare class CBMutableDescriptor extends CBDescriptor { static alloc(): CBMutableDescriptor; // inherited from NSObject static new(): CBMutableDescriptor; // inherited from NSObject constructor(o: { type: CBUUID; value: any; }); initWithTypeValue(UUID: CBUUID, value: any): this; } declare class CBMutableService extends CBService { static alloc(): CBMutableService; // inherited from NSObject static new(): CBMutableService; // inherited from NSObject characteristics: NSArray<CBCharacteristic>; includedServices: NSArray<CBService>; constructor(o: { type: CBUUID; primary: boolean; }); initWithTypePrimary(UUID: CBUUID, isPrimary: boolean): this; } declare class CBPeer extends NSObject implements NSCopying { static alloc(): CBPeer; // inherited from NSObject static new(): CBPeer; // inherited from NSObject readonly identifier: NSUUID; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class CBPeripheral extends CBPeer { static alloc(): CBPeripheral; // inherited from NSObject static new(): CBPeripheral; // inherited from NSObject readonly RSSI: number; readonly ancsAuthorized: boolean; readonly canSendWriteWithoutResponse: boolean; delegate: CBPeripheralDelegate; readonly name: string; readonly services: NSArray<CBService>; readonly state: CBPeripheralState; discoverCharacteristicsForService(characteristicUUIDs: NSArray<CBUUID> | CBUUID[], service: CBService): void; discoverDescriptorsForCharacteristic(characteristic: CBCharacteristic): void; discoverIncludedServicesForService(includedServiceUUIDs: NSArray<CBUUID> | CBUUID[], service: CBService): void; discoverServices(serviceUUIDs: NSArray<CBUUID> | CBUUID[]): void; maximumWriteValueLengthForType(type: CBCharacteristicWriteType): number; openL2CAPChannel(PSM: number): void; readRSSI(): void; readValueForCharacteristic(characteristic: CBCharacteristic): void; readValueForDescriptor(descriptor: CBDescriptor): void; setNotifyValueForCharacteristic(enabled: boolean, characteristic: CBCharacteristic): void; writeValueForCharacteristicType(data: NSData, characteristic: CBCharacteristic, type: CBCharacteristicWriteType): void; writeValueForDescriptor(data: NSData, descriptor: CBDescriptor): void; } interface CBPeripheralDelegate extends NSObjectProtocol { peripheralDidDiscoverCharacteristicsForServiceError?(peripheral: CBPeripheral, service: CBService, error: NSError): void; peripheralDidDiscoverDescriptorsForCharacteristicError?(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: NSError): void; peripheralDidDiscoverIncludedServicesForServiceError?(peripheral: CBPeripheral, service: CBService, error: NSError): void; peripheralDidDiscoverServices?(peripheral: CBPeripheral, error: NSError): void; peripheralDidModifyServices?(peripheral: CBPeripheral, invalidatedServices: NSArray<CBService> | CBService[]): void; peripheralDidOpenL2CAPChannelError?(peripheral: CBPeripheral, channel: CBL2CAPChannel, error: NSError): void; peripheralDidReadRSSIError?(peripheral: CBPeripheral, RSSI: number, error: NSError): void; peripheralDidUpdateName?(peripheral: CBPeripheral): void; peripheralDidUpdateNotificationStateForCharacteristicError?(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: NSError): void; peripheralDidUpdateRSSIError?(peripheral: CBPeripheral, error: NSError): void; peripheralDidUpdateValueForCharacteristicError?(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: NSError): void; peripheralDidUpdateValueForDescriptorError?(peripheral: CBPeripheral, descriptor: CBDescriptor, error: NSError): void; peripheralDidWriteValueForCharacteristicError?(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: NSError): void; peripheralDidWriteValueForDescriptorError?(peripheral: CBPeripheral, descriptor: CBDescriptor, error: NSError): void; peripheralIsReadyToSendWriteWithoutResponse?(peripheral: CBPeripheral): void; } declare var CBPeripheralDelegate: { prototype: CBPeripheralDelegate; }; declare class CBPeripheralManager extends CBManager { static alloc(): CBPeripheralManager; // inherited from NSObject static authorizationStatus(): CBPeripheralManagerAuthorizationStatus; static new(): CBPeripheralManager; // inherited from NSObject delegate: CBPeripheralManagerDelegate; readonly isAdvertising: boolean; constructor(o: { delegate: CBPeripheralManagerDelegate; queue: NSObject; }); constructor(o: { delegate: CBPeripheralManagerDelegate; queue: NSObject; options: NSDictionary<string, any>; }); addService(service: CBMutableService): void; initWithDelegateQueue(delegate: CBPeripheralManagerDelegate, queue: NSObject): this; initWithDelegateQueueOptions(delegate: CBPeripheralManagerDelegate, queue: NSObject, options: NSDictionary<string, any>): this; publishL2CAPChannelWithEncryption(encryptionRequired: boolean): void; removeAllServices(): void; removeService(service: CBMutableService): void; respondToRequestWithResult(request: CBATTRequest, result: CBATTError): void; setDesiredConnectionLatencyForCentral(latency: CBPeripheralManagerConnectionLatency, central: CBCentral): void; startAdvertising(advertisementData: NSDictionary<string, any>): void; stopAdvertising(): void; unpublishL2CAPChannel(PSM: number): void; updateValueForCharacteristicOnSubscribedCentrals(value: NSData, characteristic: CBMutableCharacteristic, centrals: NSArray<CBCentral> | CBCentral[]): boolean; } declare const enum CBPeripheralManagerAuthorizationStatus { NotDetermined = 0, Restricted = 1, Denied = 2, Authorized = 3 } declare const enum CBPeripheralManagerConnectionLatency { Low = 0, Medium = 1, High = 2 } interface CBPeripheralManagerDelegate extends NSObjectProtocol { peripheralManagerCentralDidSubscribeToCharacteristic?(peripheral: CBPeripheralManager, central: CBCentral, characteristic: CBCharacteristic): void; peripheralManagerCentralDidUnsubscribeFromCharacteristic?(peripheral: CBPeripheralManager, central: CBCentral, characteristic: CBCharacteristic): void; peripheralManagerDidAddServiceError?(peripheral: CBPeripheralManager, service: CBService, error: NSError): void; peripheralManagerDidOpenL2CAPChannelError?(peripheral: CBPeripheralManager, channel: CBL2CAPChannel, error: NSError): void; peripheralManagerDidPublishL2CAPChannelError?(peripheral: CBPeripheralManager, PSM: number, error: NSError): void; peripheralManagerDidReceiveReadRequest?(peripheral: CBPeripheralManager, request: CBATTRequest): void; peripheralManagerDidReceiveWriteRequests?(peripheral: CBPeripheralManager, requests: NSArray<CBATTRequest> | CBATTRequest[]): void; peripheralManagerDidStartAdvertisingError?(peripheral: CBPeripheralManager, error: NSError): void; peripheralManagerDidUnpublishL2CAPChannelError?(peripheral: CBPeripheralManager, PSM: number, error: NSError): void; peripheralManagerDidUpdateState(peripheral: CBPeripheralManager): void; peripheralManagerIsReadyToUpdateSubscribers?(peripheral: CBPeripheralManager): void; peripheralManagerWillRestoreState?(peripheral: CBPeripheralManager, dict: NSDictionary<string, any>): void; } declare var CBPeripheralManagerDelegate: { prototype: CBPeripheralManagerDelegate; }; declare var CBPeripheralManagerOptionRestoreIdentifierKey: string; declare var CBPeripheralManagerOptionShowPowerAlertKey: string; declare var CBPeripheralManagerRestoredStateAdvertisementDataKey: string; declare var CBPeripheralManagerRestoredStateServicesKey: string; declare const enum CBPeripheralManagerState { Unknown = 0, Resetting = 1, Unsupported = 2, Unauthorized = 3, PoweredOff = 4, PoweredOn = 5 } declare const enum CBPeripheralState { Disconnected = 0, Connecting = 1, Connected = 2, Disconnecting = 3 } declare class CBService extends CBAttribute { static alloc(): CBService; // inherited from NSObject static new(): CBService; // inherited from NSObject readonly characteristics: NSArray<CBCharacteristic>; readonly includedServices: NSArray<CBService>; readonly isPrimary: boolean; readonly peripheral: CBPeripheral; } declare class CBUUID extends NSObject implements NSCopying { static UUIDWithCFUUID(theUUID: any): CBUUID; static UUIDWithData(theData: NSData): CBUUID; static UUIDWithNSUUID(theUUID: NSUUID): CBUUID; static UUIDWithString(theString: string): CBUUID; static alloc(): CBUUID; // inherited from NSObject static new(): CBUUID; // inherited from NSObject readonly UUIDString: string; readonly data: NSData; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare var CBUUIDCharacteristicAggregateFormatString: string; declare var CBUUIDCharacteristicExtendedPropertiesString: string; declare var CBUUIDCharacteristicFormatString: string; declare var CBUUIDCharacteristicUserDescriptionString: string; declare var CBUUIDCharacteristicValidRangeString: string; declare var CBUUIDClientCharacteristicConfigurationString: string; declare var CBUUIDL2CAPPSMCharacteristicString: string; declare var CBUUIDServerCharacteristicConfigurationString: string;
the_stack
import { Connection, createConnection } from 'typeorm'; import { AccountsTypeorm, entities } from '../src'; const user = { username: 'johndoe', email: 'john@doe.com', password: 'toto', }; let connection: Connection; const url = 'postgres://postgres@localhost:5432/accounts-js-tests-e2e'; describe('TypeormServicePassword', () => { beforeAll(async () => { connection = await createConnection({ type: 'postgres', url, entities, synchronize: true, }); }); afterEach(async () => { await connection.query('delete from "user"'); await connection.query('delete from "user_email"'); await connection.query('delete from "user_service"'); await connection.query('delete from "user_session"'); }); afterAll(async () => { await connection.close(); }); describe('#constructor', () => { it('should have default options', () => { const accountsTypeorm = new AccountsTypeorm({ connection }); expect((accountsTypeorm as any).options).toBeTruthy(); }); it('should get default connection if connection is not provided', () => { const accountsTypeorm = new AccountsTypeorm(); expect((accountsTypeorm as any).userRepository).toBeTruthy(); expect((accountsTypeorm as any).emailRepository).toBeTruthy(); expect((accountsTypeorm as any).serviceRepository).toBeTruthy(); expect((accountsTypeorm as any).sessionRepository).toBeTruthy(); }); }); describe('createUser', () => { it('should create a new user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); const ret = await accountsTypeorm.findUserById(userId); expect(userId).toBeTruthy(); expect(ret).toMatchObject({ id: expect.any(String), username: 'johndoe', emails: [ { address: user.email, verified: false, }, ], services: { password: [ { bcrypt: 'toto', }, ], }, createdAt: expect.any(Date), updatedAt: expect.any(Date), }); }); it('should not overwrite service', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser({ ...user, services: 'test', }); const ret = await accountsTypeorm.findUserById(userId); expect(userId).toBeTruthy(); expect(ret!.services).toMatchObject({ password: [ { bcrypt: 'toto', }, ], }); }); it('should not set username', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser({ email: user.email, password: user.password, }); const ret = await accountsTypeorm.findUserById(userId); expect(ret!.id).toBeTruthy(); expect(ret!.username).not.toBeTruthy(); }); it('should not set email', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser({ username: user.username, password: user.password, }); const ret = await accountsTypeorm.findUserById(userId); expect(ret!.id).toBeTruthy(); expect(ret!.emails).toHaveLength(0); }); it('email should be lowercase', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser({ email: 'JohN@doe.com', password: user.password, }); const ret = await accountsTypeorm.findUserById(userId); expect(ret!.id).toBeTruthy(); expect(ret!.emails![0].address).toEqual('john@doe.com'); }); }); describe('findUserById', () => { it('should return null for not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const ret = await accountsTypeorm.findUserById('402fcb56-e325-4950-9166-63855da0a3fe'); expect(ret).not.toBeTruthy(); }); it('should return user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); const ret = await accountsTypeorm.findUserById(userId); expect(ret).toBeTruthy(); expect(ret!.id).toBeTruthy(); }); }); describe('findUserByEmail', () => { it('should return null for not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const ret = await accountsTypeorm.findUserByEmail('unknow@user.com'); expect(ret).not.toBeTruthy(); }); it('should return user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await accountsTypeorm.createUser(user); const ret = await accountsTypeorm.findUserByEmail(user.email); expect(ret).toBeTruthy(); expect(ret!.id).toBeTruthy(); }); it('should return user with uppercase email', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await accountsTypeorm.createUser({ email: 'JOHN@DOES.COM', password: user.password }); const ret = await accountsTypeorm.findUserByEmail('JOHN@DOES.COM'); expect(ret!.id).toBeTruthy(); expect(ret!.emails![0].address).toEqual('john@does.com'); }); }); describe('findUserByUsername', () => { it('should return null for not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const ret = await accountsTypeorm.findUserByUsername('unknowuser'); expect(ret).not.toBeTruthy(); }); it('should return user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await accountsTypeorm.createUser(user); const ret = await accountsTypeorm.findUserByUsername(user.username); expect(ret).toBeTruthy(); expect(ret!.id).toBeTruthy(); }); }); describe('findUserByServiceIdd', () => { it('should return null for not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection, cache: 1 }); const ret = await accountsTypeorm.findUserByServiceId( 'password', '11111111-1111-1111-1111-11111111' ); expect(ret).toBeFalsy(); }); it('should return user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection, cache: 1 }); const userId = await accountsTypeorm.createUser(user); let ret = await accountsTypeorm.findUserByServiceId('facebook', '1'); expect(ret).not.toBeTruthy(); await accountsTypeorm.setService(userId, 'facebook', { id: '1' }); ret = await accountsTypeorm.findUserByServiceId('facebook', '1'); expect(ret).toBeTruthy(); expect(ret!.id).toEqual(userId); }); }); describe('findUserByEmailVerificationToken', () => { it('should return null for not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const ret = await accountsTypeorm.findUserByEmailVerificationToken('token'); expect(ret).not.toBeTruthy(); }); it('should return user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addEmailVerificationToken(userId, 'john@doe.com', 'token'); const ret = await accountsTypeorm.findUserByEmailVerificationToken('token'); expect(ret).toBeTruthy(); expect(ret!.id).toBeTruthy(); }); }); describe('findUserByResetPasswordToken', () => { it('should return null for not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const ret = await accountsTypeorm.findUserByResetPasswordToken('token'); expect(ret).not.toBeTruthy(); }); it('should return user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addResetPasswordToken(userId, 'john@doe.com', 'token', 'test'); const ret = await accountsTypeorm.findUserByResetPasswordToken('token'); expect(ret).toBeTruthy(); expect(ret!.id).toBeTruthy(); }); }); describe('findUserByServiceId', () => { it('should return null for not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const ret = await accountsTypeorm.findUserByServiceId('facebook', 'invalid'); expect(ret).not.toBeTruthy(); }); it('should return user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); let ret = await accountsTypeorm.findUserByServiceId('facebook', '1'); expect(ret).not.toBeTruthy(); await accountsTypeorm.setService(userId, 'facebook', { id: '1' }); ret = await accountsTypeorm.findUserByServiceId('facebook', '1'); expect(ret).toBeTruthy(); expect(ret!.id).toBeTruthy(); }); }); describe('findPasswordHash', () => { it('should return null on not found user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const ret = await accountsTypeorm.findPasswordHash('402fcb56-e325-4950-9166-63855da0a3fe'); expect(ret).toEqual(null); }); it('should return hash', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); const retUser = await accountsTypeorm.findUserById(userId); const ret = await accountsTypeorm.findPasswordHash(userId); const services: any = retUser!.services; expect(ret).toBeTruthy(); expect(ret).toEqual(services.password[0].bcrypt); }); }); describe('addEmail', () => { it('should throw if user is not found', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await expect( accountsTypeorm.addEmail('402fcb56-e325-4950-9166-63855da0a3fe', 'unknowemail', false) ).rejects.toThrowError('User not found'); }); it('should add email', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const email = 'johns@doe.com'; const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addEmail(userId, email, false); const retUser = await accountsTypeorm.findUserByEmail(email); expect(retUser!.emails!.length).toEqual(2); expect((retUser as any).createdAt).not.toEqual((retUser as any).updatedAt); }); it('should add lowercase email', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const email = 'johnS@doe.com'; const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addEmail(userId, email, false); const retUser = await accountsTypeorm.findUserByEmail(email); expect(retUser!.emails!.length).toEqual(2); expect(retUser!.emails![1].address).toEqual('johns@doe.com'); }); }); describe('removeEmail', () => { it('should throw if user is not found', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await expect( accountsTypeorm.removeEmail('402fcb56-e325-4950-9166-63855da0a3fe', 'unknowemail') ).rejects.toThrowError('User not found'); }); it('should throw if email is not found', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); await expect(accountsTypeorm.removeEmail(userId, 'unknowemail')).rejects.toThrowError( 'Email not found' ); }); it('should remove email', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const email = 'johns@doe.com'; const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addEmail(userId, email, false); await accountsTypeorm.removeEmail(userId, user.email); const retUser = await accountsTypeorm.findUserById(userId); expect(retUser!.emails!.length).toEqual(1); expect(retUser!.emails![0].address).toEqual(email); expect(retUser!.createdAt).not.toEqual(retUser!.updatedAt); }); it('should remove uppercase email', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const email = 'johns@doe.com'; const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addEmail(userId, email, false); await accountsTypeorm.removeEmail(userId, 'JOHN@doe.com'); const retUser = await accountsTypeorm.findUserById(userId); expect(retUser!.emails!.length).toEqual(1); expect(retUser!.emails![0].address).toEqual(email); }); }); describe('verifyEmail', () => { it('should throw if user is not found', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await expect( accountsTypeorm.verifyEmail('402fcb56-e325-4950-9166-63855da0a3fe', 'unknowemail') ).rejects.toThrowError('User not found'); }); it('should throw if email is not found', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); await expect(accountsTypeorm.verifyEmail(userId, 'unknowemail')).rejects.toThrowError( 'Email not found' ); }); it('should verify email', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); let retUser = await accountsTypeorm.findUserById(userId); expect(retUser!.emails!.length).toEqual(1); expect(retUser!.emails![0].address).toBe(user.email); expect(retUser!.emails![0].verified).toBe(false); await accountsTypeorm.verifyEmail(userId, user.email); retUser = await accountsTypeorm.findUserById(userId); expect(retUser!.emails!.length).toEqual(1); expect(retUser!.emails![0].address).toBe(user.email); expect(retUser!.emails![0].verified).toBe(true); expect(retUser!.createdAt).not.toEqual(retUser!.updatedAt); }); }); describe('setUsername', () => { it('should throw if user is not found', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await expect( accountsTypeorm.setUsername('402fcb56-e325-4950-9166-63855da0a3fe', 'username') ).rejects.toThrowError('User not found'); }); it('should change username', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const username = 'johnsdoe'; const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.setUsername(userId, username); const retUser = await accountsTypeorm.findUserById(userId); expect(retUser!.username).toEqual(username); expect(retUser!.createdAt).not.toEqual(retUser!.updatedAt); }); }); describe('setPassword', () => { it('should throw if user is not found', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); await expect( accountsTypeorm.setPassword('402fcb56-e325-4950-9166-63855da0a3fe', 'toto') ).rejects.toThrowError('User not found'); }); it('should change password', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const newPassword = 'newpass'; const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.setPassword(userId, newPassword); const retUser = await accountsTypeorm.findUserById(userId); const services: any = retUser!.services; expect(services.password[0].bcrypt).toBeTruthy(); expect(services.password[0].bcrypt).toEqual(newPassword); expect(retUser!.createdAt).not.toEqual(retUser!.updatedAt); }); }); describe('setService', () => { it('should set service', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); let ret = await accountsTypeorm.findUserByServiceId('google', '1'); expect(ret).not.toBeTruthy(); await accountsTypeorm.setService(userId, 'google', { id: 1 }); ret = await accountsTypeorm.findUserByServiceId('google', '1'); expect(ret).toBeTruthy(); expect(ret!.id).toBeTruthy(); }); }); describe('unsetService', () => { it('should unset service', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.setService(userId, 'telegram', { id: '1' }); await accountsTypeorm.unsetService(userId, 'telegram'); const ret = await accountsTypeorm.findUserByServiceId('telegram', '1'); expect(ret).not.toBeTruthy(); }); }); describe('setUserDeactivated', () => { // TODO: This should be added // it('should throw if user is not found', async () => { // const accountsTypeorm = new AccountsTypeorm({ connection }); // await expect( // accountsTypeorm.setUserDeactivated('402fcb56-e325-4950-9166-63855da0a3fe', true) // ).rejects.toThrowError('User not found'); // }); it('should deactivate user', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); const ret = await accountsTypeorm.findUserById(userId); expect(ret!.deactivated).toBeFalsy(); await accountsTypeorm.setUserDeactivated(userId, true); const ret1 = await accountsTypeorm.findUserById(userId); expect(ret1!.deactivated).toBeTruthy(); }); }); describe('removeAllResetPasswordTokens', () => { it('should remove the password reset tokens', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const testToken = 'testVerificationToken'; const testReason = 'testReason'; const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addResetPasswordToken(userId, user.email, testToken, testReason); const userWithTokens = await accountsTypeorm.findUserByResetPasswordToken(testToken); expect(userWithTokens).toBeTruthy(); await accountsTypeorm.removeAllResetPasswordTokens(userId); const userWithDeletedTokens = await accountsTypeorm.findUserByResetPasswordToken(testToken); expect(userWithDeletedTokens).not.toBeTruthy(); }); }); describe('addEmailVerificationToken', () => { it('should add a token', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addEmailVerificationToken(userId, 'john@doe.com', 'token'); const retUser = await accountsTypeorm.findUserById(userId); const services: any = retUser!.services; expect(services.email.verificationTokens.length).toEqual(1); expect(services.email.verificationTokens[0].address).toEqual('john@doe.com'); expect(services.email.verificationTokens[0].token).toEqual('token'); expect(services.email.verificationTokens[0].when).toBeTruthy(); }); }); describe('addResetPasswordToken', () => { it('should add a token', async () => { const accountsTypeorm = new AccountsTypeorm({ connection }); const userId = await accountsTypeorm.createUser(user); await accountsTypeorm.addResetPasswordToken(userId, 'john@doe.com', 'token', 'reset'); const retUser = await accountsTypeorm.findUserById(userId); const services: any = retUser!.services; expect(services.password.reset.length).toEqual(1); expect(services.password.reset[0].address).toEqual('john@doe.com'); expect(services.password.reset[0].token).toEqual('token'); expect(services.password.reset[0].when).toBeTruthy(); expect(services.password.reset[0].reason).toEqual('reset'); }); }); });
the_stack
import { LoaderOptions, Library, Instance } from './seal' import { Exception, SealError } from './exception' import { VectorConstructorOptions } from './vector' import { MemoryPoolHandle } from './memory-pool-handle' import { PlainText, PlainTextConstructorOptions } from './plain-text' import { Context } from './context' import { UNSUPPORTED_BATCH_ENCODE_ARRAY_TYPE } from './constants' export type BatchEncoderDependencyOptions = { readonly Exception: Exception readonly MemoryPoolHandle: MemoryPoolHandle readonly PlainText: PlainTextConstructorOptions readonly Vector: VectorConstructorOptions } export type BatchEncoderDependencies = { ({ Exception, MemoryPoolHandle, PlainText, Vector }: BatchEncoderDependencyOptions): BatchEncoderConstructorOptions } export type BatchEncoderConstructorOptions = { (context: Context): BatchEncoder } export type BatchEncoderTypes = | Int32Array | Uint32Array | BigInt64Array | BigUint64Array export type BatchEncoder = { readonly instance: Instance readonly unsafeInject: (instance: Instance) => void readonly delete: () => void readonly encode: ( array: BatchEncoderTypes, plainText?: PlainText ) => PlainText | void readonly decode: ( plainText: PlainText, signed?: boolean, pool?: MemoryPoolHandle ) => Int32Array | Uint32Array readonly decodeBigInt: ( plainText: PlainText, signed?: boolean, pool?: MemoryPoolHandle ) => BigInt64Array | BigUint64Array readonly slotCount: number } const BatchEncoderConstructor = (library: Library): BatchEncoderDependencies => ({ Exception, MemoryPoolHandle, PlainText, Vector }: BatchEncoderDependencyOptions): BatchEncoderConstructorOptions => (context): BatchEncoder => { const Constructor = library.BatchEncoder let _instance: Instance try { _instance = new Constructor(context.instance) } catch (e) { throw Exception.safe(e as SealError) } /** * @implements BatchEncoder */ /** * @interface BatchEncoder */ return { /** * Get the underlying WASM instance * * @private * @readonly * @name BatchEncoder#instance * @type {Instance} */ get instance() { return _instance }, /** * Inject this object with a raw WASM instance. No type checking is performed. * * @private * @function * @name BatchEncoder#unsafeInject * @param {Instance} instance WASM instance */ unsafeInject(instance: Instance) { if (_instance) { _instance.delete() _instance = undefined } _instance = instance }, /** * Delete the underlying WASM instance. * * Should be called before dereferencing this object to prevent the * WASM heap from growing indefinitely. * @function * @name BatchEncoder#delete */ delete() { if (_instance) { _instance.delete() _instance = undefined } }, /** * Creates a PlainText from a given matrix. This function "batches" a given matrix * of either signed or unsigned integers modulo the PlainText modulus into a PlainText element, and stores * the result in the destination parameter. The input array must have size at most equal * to the degree of the polynomial modulus. The first half of the elements represent the * first row of the matrix, and the second half represent the second row. The numbers * in the matrix can be at most equal to the PlainText modulus for it to represent * a valid PlainText. * * If the destination PlainText overlaps the input values in memory, the behavior of * this function is undefined. * * @function * @name BatchEncoder#encode * @param {Int32Array|Uint32Array|BigInt64Array|BigUint64Array} array Data to encode * @param {PlainText} [plainText=null] Destination to store the encoded result * @returns {PlainText|void} A new PlainText holding the encoded data or void if one was provided * @example * import SEAL from 'node-seal' * const seal = await SEAL() * ... * const batchEncoder = seal.BatchEncoder(context) * * const plainText = batchEncoder.encode(Int32Array.from([1, -2, 3])) */ encode( array: Int32Array | Uint32Array | BigInt64Array | BigUint64Array, plainText?: PlainText ): PlainText | void { try { if (array.constructor === Int32Array) { if (plainText) { _instance.encode(array, plainText.instance, 'INT32') return } const plain = PlainText() _instance.encode(array, plain.instance, 'INT32') return plain } if (array.constructor === Uint32Array) { if (plainText) { _instance.encode(array, plainText.instance, 'UINT32') return } const plain = PlainText() _instance.encode(array, plain.instance, 'UINT32') return plain } if (array.constructor === BigInt64Array) { // When embind supports BigInt64Arrays we can remove this hack const stringArray = array.toString().split(',') if (plainText) { _instance.encode(stringArray, plainText.instance, 'INT64') return } const plain = PlainText() _instance.encode(stringArray, plain.instance, 'INT64') return plain } if (array.constructor === BigUint64Array) { // When embind supports BigInt64Arrays we can remove this hack const stringArray = array.toString().split(',') if (plainText) { _instance.encode(stringArray, plainText.instance, 'UINT64') return } const plain = PlainText() _instance.encode(stringArray, plain.instance, 'UINT64') return plain } throw new Error(UNSUPPORTED_BATCH_ENCODE_ARRAY_TYPE) } catch (e) { throw Exception.safe(e as SealError) } }, /** * Inverse of encode. This function "unbatches" a given PlainText into a matrix * of signed or unsigned integers modulo the PlainText modulus, and stores the result in the destination * parameter. The input PlainText must have degrees less than the polynomial modulus, * and coefficients less than the PlainText modulus, i.e. it must be a valid PlainText * for the encryption parameters. Dynamic memory allocations in the process are * allocated from the memory pool pointed to by the given MemoryPoolHandle. * * @function * @name BatchEncoder#decode * @param {PlainText} plainText Data to decode * @param {boolean} [signed=true] By default, decode as an Int32Array. If false, decode as an Uint32Array * @param {MemoryPoolHandle} [pool={@link MemoryPoolHandle.global}] * @returns {Int32Array|Uint32Array} TypedArray containing the decoded data * @example * import SEAL from 'node-seal' * const seal = await SEAL() * ... * const batchEncoder = seal.BatchEncoder(context) * * const plainText = batchEncoder.encode(Int32Array.from([1, -2, 3])) * const plainTextU = batchEncoder.encode(Uint32Array.from([1, 2, 3])) * * const result = batchEncoder.decode(plainText) * const resultU = batchEncoder.decode(plainTextU, false) // To decode as an Uint32Array */ decode( plainText: PlainText, signed = true, pool: MemoryPoolHandle = MemoryPoolHandle.global ): Int32Array | Uint32Array { try { if (signed) { const tempVect = Vector() const instance = _instance.decodeInt32(plainText.instance, pool) tempVect.unsafeInject(instance) tempVect.setType('Int32Array') const tempArr = tempVect.toArray() as Int32Array tempVect.delete() return tempArr } const tempVect = Vector() const instance = _instance.decodeUint32(plainText.instance, pool) tempVect.unsafeInject(instance) tempVect.setType('Uint32Array') const tempArr = tempVect.toArray() as Uint32Array tempVect.delete() return tempArr } catch (e) { throw Exception.safe(e as SealError) } }, /** * Performs the same function as the 32-bit decode, but supports true * 64-bit values encapsulated by a BigInt. * * There's no official support for sending a BigInt64Array/BigUint64Array * from C++ to JS, therefore this function uses string conversion to * marshal data which is noticably slower. Use this function if you * absolutely need to marshal values larger than 32 bits. * * @see {@link BatchEncoder#decode} for more information about decode. * @function * @name BatchEncoder#decodeBigInt * @param {PlainText} plainText Data to decode * @param {boolean} [signed=true] By default, decode as an BigInt64Array. If false, decode as an BigUint64Array * @param {MemoryPoolHandle} [pool={@link MemoryPoolHandle.global}] * @returns {BigInt64Array|BigUint64Array} TypedArray containing the decoded data * @example * import SEAL from 'node-seal' * const seal = await SEAL() * ... * const batchEncoder = seal.BatchEncoder(context) * * const plainText = batchEncoder.encode(BigInt64Array.from([1n, -2n, 3n])) * const plainTextU = batchEncoder.encode(BigUint64Array.from([1n, 2n, 3n])) * * const result = batchEncoder.decodeBigInt(plainText) * const resultU = batchEncoder.decodeBigInt(plainTextU, false) // To decode as an BigUint64Array */ decodeBigInt( plainText: PlainText, signed = true, pool: MemoryPoolHandle = MemoryPoolHandle.global ): BigInt64Array | BigUint64Array { try { if (signed) { const instance = _instance.decodeBigInt( plainText.instance, true, pool ) return BigInt64Array.from(instance) } const instance = _instance.decodeBigInt( plainText.instance, false, pool ) return BigUint64Array.from(instance) } catch (e) { throw Exception.safe(e as SealError) } }, /** * The total number of batching slots available to hold data * * @readonly * @name BatchEncoder#slotCount * @type {number} */ get slotCount() { return _instance.slotCount() } } } export const BatchEncoderInit = ({ loader }: LoaderOptions): BatchEncoderDependencies => { const library: Library = loader.library return BatchEncoderConstructor(library) }
the_stack
import { getIntrospectionQuery } from 'graphql' import { useDisableIntrospection } from '@envelop/disable-introspection' import EventSource from 'eventsource' import request from 'supertest' import puppeteer from 'puppeteer' import { CORSOptions, createServer, GraphQLYogaError } from '../src' import { getCounterValue, schema } from '../test-utils/schema' import { createTestSchema } from './__fixtures__/schema' import { renderGraphiQL } from '@graphql-yoga/render-graphiql' import 'json-bigint-patch' import http from 'http' import { useLiveQuery } from '@envelop/live-query' import { InMemoryLiveQueryStore } from '@n1ru4l/in-memory-live-query-store' import { fetch, File, FormData } from 'cross-undici-fetch' describe('Disable Introspection with plugin', () => { it('succeeds introspection query', async () => { const yoga = createServer({ schema, logging: false }) const response = await request(yoga).post('/graphql').send({ query: getIntrospectionQuery(), }) expect(response.statusCode).toBe(200) const body = JSON.parse(response.text) expect(body.errors).toBeUndefined() expect(body.data?.__schema.queryType.name).toBe('Query') }) it('fails introspection query with useDisableIntrospection', async () => { const yoga = createServer({ schema, logging: false, // @ts-ignore plugins: [useDisableIntrospection()], }) const response = await request(yoga).post('/graphql').send({ query: getIntrospectionQuery(), }) expect(response.statusCode).toBe(400) expect(response.headers['content-type']).toBe('application/json') expect(response.body.data).toBeNull() expect(response.body.errors![0]).toMatchInlineSnapshot(` Object { "locations": Array [ Object { "column": 7, "line": 3, }, ], "message": "GraphQL introspection has been disabled, but the requested query contained the field \\"__schema\\".", } `) }) }) describe('Masked Error Option', () => { const typeDefs = /* GraphQL */ ` type Query { hello: String hi: String } ` const resolvers = { Query: { hello: () => { throw new GraphQLYogaError('This error never gets masked.') }, hi: () => { throw new Error('This error will get mask if you enable maskedError.') }, }, } const schema = { typeDefs, resolvers, } const initialEnv = process.env.NODE_ENV afterEach(() => { process.env.NODE_ENV = initialEnv }) it('should mask error', async () => { const yoga = createServer({ schema, maskedErrors: true, logging: false, }) const response = await request(yoga).post('/graphql').send({ query: '{ hi hello }', }) const body = JSON.parse(response.text) expect(body.data.hi).toBeNull() expect(body.errors![0].message).toBe('Unexpected error.') expect(body.data.hello).toBeNull() expect(body.errors![1].message).toBe('This error never gets masked.') }) it('should mask error with custom message', async () => { const yoga = createServer({ schema, maskedErrors: { errorMessage: 'Hahahaha' }, logging: false, }) const response = await request(yoga).post('/graphql').send({ query: '{ hello hi }', }) const body = JSON.parse(response.text) expect(body.data.hello).toBeNull() expect(body.errors![0].message).toBe('This error never gets masked.') expect(body.data.hi).toBeNull() expect(body.errors![1].message).toBe('Hahahaha') }) it('should mask errors by default', async () => { const yoga = createServer({ schema, logging: false, }) const response = await request(yoga).post('/graphql').send({ query: '{ hi hello }', }) const body = JSON.parse(response.text) expect(body.data.hi).toBeNull() expect(body.errors![0].message).toBe('Unexpected error.') expect(body.data.hello).toBeNull() expect(body.errors![1].message).toBe('This error never gets masked.') }) it('includes the original error in the extensions in dev mode (isDev flag)', async () => { const yoga = createServer({ schema, logging: false, maskedErrors: { isDev: true, }, }) const response = await request(yoga).post('/graphql').send({ query: '{ hi hello }', }) const body = JSON.parse(response.text) expect(body.data.hi).toBeNull() expect(body.errors?.[0]?.message).toBe('Unexpected error.') expect(body.errors?.[0]?.extensions).toStrictEqual({ originalError: { message: 'This error will get mask if you enable maskedError.', stack: expect.stringContaining( 'Error: This error will get mask if you enable maskedError.', ), }, }) }) it('includes the original error in the extensions in dev mode (NODE_ENV=development)', async () => { process.env.NODE_ENV = 'development' const yoga = createServer({ schema, logging: false, }) const response = await request(yoga).post('/graphql').send({ query: '{ hi hello }', }) const body = JSON.parse(response.text) expect(body.data.hi).toBeNull() expect(body.errors?.[0]?.message).toBe('Unexpected error.') expect(body.errors?.[0]?.extensions).toStrictEqual({ originalError: { message: 'This error will get mask if you enable maskedError.', stack: expect.stringContaining( 'Error: This error will get mask if you enable maskedError.', ), }, }) }) }) describe('Context error', () => { it('Error thrown within context factory without error masking is not swallowed and does not include stack trace', async () => { const yoga = createServer({ logging: false, maskedErrors: false, context: () => { throw new Error('I like turtles') }, }) const response = await request(yoga).post('/graphql').send({ query: '{ greetings }', }) const body = JSON.parse(response.text) expect(body).toMatchInlineSnapshot(` Object { "data": null, "errors": Array [ Object { "message": "I like turtles", }, ], } `) }) it('Error thrown within context factory with error masking is masked', async () => { const yoga = createServer({ logging: false, context: () => { throw new Error('I like turtles') }, }) const response = await request(yoga).post('/graphql').send({ query: '{ greetings }', }) const body = JSON.parse(response.text) expect(body).toMatchInlineSnapshot(` Object { "data": null, "errors": Array [ Object { "message": "Unexpected error.", }, ], } `) }) it('GraphQLYogaError thrown within context factory with error masking is not masked', async () => { const yoga = createServer({ logging: false, context: () => { throw new GraphQLYogaError('I like turtles') }, }) const response = await request(yoga).post('/graphql').send({ query: '{ greetings }', }) const body = JSON.parse(response.text) expect(body).toMatchInlineSnapshot(` Object { "data": null, "errors": Array [ Object { "message": "I like turtles", }, ], } `) }) }) describe('Requests', () => { const endpoint = '/test-graphql' const yoga = createServer({ schema, logging: false, endpoint }) it('should reject other paths if specific endpoint path is provided', async () => { const response = await request(yoga).get('/graphql') expect(response.status).toBe(404) }) it('should send basic query', async () => { const response = await request(yoga).post(endpoint).send({ query: '{ ping }', }) expect(response.statusCode).toBe(200) const body = JSON.parse(response.text) expect(body.errors).toBeUndefined() expect(body.data.ping).toBe('pong') }) it('should send basic query with GET', async () => { const response = await request(yoga) .get(endpoint + '?query=' + encodeURIComponent('{ ping }')) .send() expect(response.statusCode).toBe(200) const body = JSON.parse(response.text) expect(body.errors).toBeUndefined() expect(body.data.ping).toBe('pong') }) it('should send basic mutation', async () => { const response = await request(yoga) .post(endpoint) .send({ query: /* GraphQL */ ` mutation { echo(message: "hello") } `, }) expect(response.statusCode).toBe(200) const body = JSON.parse(response.text) expect(body.errors).toBeUndefined() expect(body.data.echo).toBe('hello') }) it('should send variables', async () => { const response = await request(yoga) .post(endpoint) .send({ query: /* GraphQL */ ` mutation ($text: String) { echo(message: $text) } `, variables: { text: 'hello', }, }) expect(response.statusCode).toBe(200) const body = JSON.parse(response.text) expect(body.errors).toBeUndefined() expect(body.data.echo).toBe('hello') }) it('should error on malformed query', async () => { const response = await request(yoga).post(endpoint).send({ query: '{ query { ping }', }) const body = JSON.parse(response.text) expect(body.errors).toBeDefined() expect(body.data).toBeNull() }) it('should error missing query', async () => { const response = await request(yoga) .post(endpoint) .send({ query: null, } as any) const body = JSON.parse(response.text) expect(body.data).toBeNull() expect(body.errors?.[0].message).toBe('Must provide query string.') }) }) describe('Incremental Delivery', () => { const yoga = createServer({ schema, logging: false }) beforeAll(() => { return yoga.start() }) afterAll(() => { return yoga.stop() }) it('should upload a file', async () => { const UPLOAD_MUTATION = /* GraphQL */ ` mutation upload($file: File!) { singleUpload(file: $file) { name type text } } ` const fileName = 'test.txt' const fileType = 'text/plain' const fileContent = 'Hello World' const formData = new FormData() formData.set('operations', JSON.stringify({ query: UPLOAD_MUTATION })) formData.set('map', JSON.stringify({ 0: ['variables.file'] })) formData.set('0', new File([fileContent], fileName, { type: fileType })) const response = await fetch(yoga.getServerUrl(), { method: 'POST', body: formData, }) const body = await response.json() expect(body.errors).toBeUndefined() expect(body.data.singleUpload.name).toBe(fileName) expect(body.data.singleUpload.type).toBe(fileType) expect(body.data.singleUpload.text).toBe(fileContent) }) it('should get subscription', async () => { const serverUrl = yoga.getServerUrl() const eventSource = new EventSource( `${serverUrl}?query=subscription{counter}`, ) const counterValue1 = getCounterValue() await new Promise((resolve) => setTimeout(resolve, 300)) expect(getCounterValue() > counterValue1).toBe(true) eventSource.close() await new Promise((resolve) => setTimeout(resolve, 300)) const counterValue2 = getCounterValue() await new Promise((resolve) => setTimeout(resolve, 300)) expect(getCounterValue()).toBe(counterValue2) }) }) describe('health checks', () => { const yogaApp = createServer({ logging: false, }) it('should return 200 status code for health check endpoint', async () => { const result = await request(yogaApp).get('/health') expect(result.status).toBe(200) expect(result.body.message).toBe('alive') }) it('should return 200 status code for readiness check endpoint', async () => { const result = await request(yogaApp).get('/readiness') expect(result.status).toBe(200) expect(result.body.message).toBe('ready') }) }) it('should expose Node req and res objects in the context', async () => { const yoga = createServer({ schema: { typeDefs: /* GraphQL */ ` type Query { isNode: Boolean! } `, resolvers: { Query: { isNode: (_, __, { req, res }) => !!req && !!res, }, }, }, logging: false, }) const response = await request(yoga) .post('/graphql') .send({ query: /* GraphQL */ ` query { isNode } `, }) expect(response.statusCode).toBe(200) const body = JSON.parse(response.text) expect(body.errors).toBeUndefined() expect(body.data.isNode).toBe(true) }) describe('Browser', () => { const liveQueryStore = new InMemoryLiveQueryStore() const endpoint = '/test-graphql' let cors: CORSOptions = {} const yogaApp = createServer({ schema: createTestSchema(), cors: () => cors, logging: false, endpoint, plugins: [ useLiveQuery({ liveQueryStore, }), ], renderGraphiQL, }) let browser: puppeteer.Browser let page: puppeteer.Page const playButtonSelector = `[d="M 11 9 L 24 16 L 11 23 z"]` const stopButtonSelector = `[d="M 10 10 L 23 10 L 23 23 L 10 23 z"]` beforeAll(async () => { await yogaApp.start() browser = await puppeteer.launch({ // If you wanna run tests with open browser // set your PUPPETEER_HEADLESS env to "false" headless: process.env.PUPPETEER_HEADLESS !== 'false', args: ['--incognito'], }) }) beforeEach(async () => { if (page !== undefined) { await page.close() } const context = await browser.createIncognitoBrowserContext() page = await context.newPage() }) afterAll(async () => { await browser.close() await yogaApp.stop() }) const typeOperationText = async (text: string) => { await page.type('.query-editor .CodeMirror textarea', text) // TODO: figure out how we can avoid this wait // it is very likely that there is a delay from textarea -> react state update await new Promise((res) => setTimeout(res, 100)) } const typeVariablesText = async (text: string) => { await page.type('.variable-editor .CodeMirror textarea', text) // TODO: figure out how we can avoid this wait // it is very likely that there is a delay from textarea -> react state update await new Promise((res) => setTimeout(res, 100)) } const waitForResult = async () => { await page.waitForFunction( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore () => !!window.g.resultComponent.viewer.getValue(), ) const resultContents = await page.evaluate(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return window.g.resultComponent.viewer.getValue() }) return resultContents } describe('GraphiQL', () => { it('execute simple query operation', async () => { await page.goto(`http://localhost:4000${endpoint}`) await typeOperationText('{ alwaysTrue }') await page.click('.execute-button') const resultContents = await waitForResult() expect(resultContents).toEqual( JSON.stringify( { data: { alwaysTrue: true, }, }, null, 2, ), ) }) it('execute mutation operation', async () => { await page.goto(`http://localhost:4000${endpoint}`) await typeOperationText( `mutation ($number: Int!) { setFavoriteNumber(number: $number) }`, ) await typeVariablesText(`{ "number": 3 }`) await page.click('.execute-button') const resultContents = await waitForResult() expect(resultContents).toEqual( JSON.stringify( { data: { setFavoriteNumber: 3, }, }, null, 2, ), ) }) test('execute SSE (subscription) operation', async () => { await page.goto(`http://localhost:4000${endpoint}`) await typeOperationText(`subscription { count(to: 2) }`) await page.click('.execute-button') await new Promise((res) => setTimeout(res, 50)) const [resultContents, isShowingStopButton] = await page.evaluate( (stopButtonSelector) => { return [ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore window.g.resultComponent.viewer.getValue(), !!window.document.querySelector(stopButtonSelector), ] }, stopButtonSelector, ) expect(JSON.parse(resultContents)).toEqual({ data: { count: 1, }, }) expect(isShowingStopButton).toEqual(true) await new Promise((resolve) => setTimeout(resolve, 300)) const [resultContents1, isShowingPlayButton] = await page.evaluate( (playButtonSelector) => { return [ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore window.g.resultComponent.viewer.getValue(), !!window.document.querySelector(playButtonSelector), ] }, playButtonSelector, ) expect(JSON.parse(resultContents1)).toEqual({ data: { count: 2, }, }) expect(isShowingPlayButton).toEqual(true) }) test('show the query provided in the search param', async () => { const query = '{ alwaysTrue }' await page.goto( `http://localhost:4000${endpoint}?query=${encodeURIComponent(query)}`, ) await page.click('.execute-button') const resultContents = await waitForResult() expect(resultContents).toEqual( JSON.stringify( { data: { alwaysTrue: true, }, }, null, 2, ), ) }) test('should show BigInt correctly', async () => { await page.goto(`http://localhost:4000/${endpoint}`) await typeOperationText(`{ bigint }`) await page.click('.execute-button') const resultContents = await waitForResult() expect(resultContents).toEqual(`{ "data": { "bigint": ${BigInt('112345667891012345')} } }`) }) test('should show live queries correctly', async () => { await page.goto(`http://localhost:4000${endpoint}`) await typeOperationText(`query @live { liveCounter }`) await page.click('.execute-button') await new Promise((res) => setTimeout(res, 50)) const [resultContents, isShowingStopButton] = await page.evaluate( (stopButtonSelector) => { return [ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore window.g.resultComponent.viewer.getValue(), !!window.document.querySelector(stopButtonSelector), ] }, stopButtonSelector, ) const resultJson = JSON.parse(resultContents) expect(resultJson).toEqual({ data: { liveCounter: 1, }, isLive: true, }) liveQueryStore.invalidate('Query.liveCounter') const watchDog = await page.waitForFunction(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const value = window.g.resultComponent.viewer.getValue() return value.includes('2') }) await watchDog const [resultContents1] = await page.evaluate((playButtonSelector) => { return [ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore window.g.resultComponent.viewer.getValue(), !!window.document.querySelector(playButtonSelector), ] }, playButtonSelector) const resultJson1 = JSON.parse(resultContents1) expect(resultJson1).toEqual({ data: { liveCounter: 2, }, isLive: true, }) }) }) describe('CORS', () => { const anotherOriginPort = 4000 + Math.floor(Math.random() * 1000) const anotherServer = http.createServer((req, res) => { res.end(/* HTML */ ` <html> <head> <title>Another Origin</title> </head> <body> <h1>Another Origin</h1> <p id="result">RESULT_HERE</p> <script> async function fetchData() { try { const response = await fetch( 'http://localhost:4000${endpoint}', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ alwaysTrue }', }), }, ) document.getElementById('result').innerHTML = await response.text() } catch (e) { document.getElementById('result').innerHTML = e.stack } } fetchData() </script> </body> </html> `) }) beforeAll(async () => { await new Promise<void>((resolve) => anotherServer.listen(anotherOriginPort, () => resolve()), ) }) afterAll(async () => { await new Promise<void>((resolve) => anotherServer.close(() => resolve())) }) test('allow other origins by default', async () => { await page.goto(`http://localhost:${anotherOriginPort}`) const result = await page.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 100)) return document.getElementById('result')?.innerHTML }) expect(result).toEqual( JSON.stringify({ data: { alwaysTrue: true, }, }), ) }) test('allow if specified', async () => { cors = { origin: [`http://localhost:${anotherOriginPort}`], } await page.goto(`http://localhost:${anotherOriginPort}`) const result = await page.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 100)) return document.getElementById('result')?.innerHTML }) expect(result).toEqual( JSON.stringify({ data: { alwaysTrue: true, }, }), ) }) test('restrict other origins if provided', async () => { cors = { origin: ['http://localhost:4000'], } await page.goto(`http://localhost:${anotherOriginPort}`) const result = await page.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 100)) return document.getElementById('result')?.innerHTML }) expect(result).toContain('Failed to fetch') }) test('send specific origin back to user if credentials are set true', async () => { cors = { origin: [`http://localhost:${anotherOriginPort}`], credentials: true, } await page.goto(`http://localhost:${anotherOriginPort}`) const result = await page.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 100)) return document.getElementById('result')?.innerHTML }) expect(result).toEqual( JSON.stringify({ data: { alwaysTrue: true, }, }), ) }) }) })
the_stack
import {js_beautify} from 'js-beautify'; import {transform, transformFile} from 'rcre-runtime-syntax-transform'; describe('ExpressionString代码转转', () => { it('BinaryExpression', () => { const cases: [string, number | string | boolean][] = [ ['1 + 1 * 2', 3], ['1 * 4', 4], ['8 % 3', 2], ['8 / 2', 4], ['2 ** 3', 8], ['2 in [1,2,3,4]', true], ['10 >>> 1', 5], ['10 >= 10', true], ['12 > 10', true], ['10 <= 10', true], ['12 < 14', true], ['true == 1', true], ['1 + "2"', '12'], ['null + null', 0], ['111 + 222', 333], ['1 + 1 > 0', true], ['-1 + 1', 0] ]; for (let i = 0; i < cases.length; i++) { let code = (transform(cases[i][0])); expect(code).toBe(js_beautify(`((runTime: any) => { return ${cases[i][0]}; }) as any`)); } }); describe('Literal and Identifier Test', () => { it('x + 1', () => { let code = 'x + 1'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.x + 1; }) as any`)); }); it('1 - x', () => { let code = '1 - x'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 - runTime.x; }) as any`)); }); }); describe('memberExpression Test', () => { it('obj.age === 10', () => { let code = 'obj.age === 10'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.obj.age === 10; }) as any`)); }); it('obj.age + obj.age === 20', () => { let code = 'obj.age + obj.age === 20'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.obj.age + runTime.obj.age === 20; }) as any`)); }); it('obj.inner.deep === 2', () => { let code = 'obj.inner.deep === 2'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.obj.inner.deep === 2; }) as any`)); }); it('obj.arr[0] === 1', () => { let code = 'obj.arr[0] === 1'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.obj.arr[0] === 1; }) as any`)); }); it('obj.arr[obj.index] === 1', () => { let code = 'obj.arr[obj.index] === 1'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.obj.arr[runTime.obj.index] === 1; }) as any`)); }); it('$data', () => { let code = '$data'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.$data; }) as any`)); }); }); describe('ObjectExpression', () => { it('({name: 1, age: 2})', () => { let code = '({name: 1, age: 2})'; expect(js_beautify(transform(code))).toBe(js_beautify(`((runTime: any) => { return ({name: 1, age: 2}); }) as any`)); }); it('({name: x, age: y})', () => { let code = '({name: x, age: y})'; expect(js_beautify(transform(code))).toBe(js_beautify(`((runTime: any) => { return ({name: runTime.x, age: runTime.y}); }) as any`)); }); it('$data.str.split()', () => { let code = '$data.str.split()'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.$data.str.split(); }) as any`)); }); it('String.prototype.split.call($data.str, ",")', () => { let code = 'String.prototype.split.call($data.str, ",")'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.String.prototype.split.call(runTime.$data.str, ","); }) as any`)); }); it('$args.value.length === 0', () => { let code = '$args.value.length === 0'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.$args.value.length === 0; }) as any`)); }); it('[1,2,3,4,5,6].slice(3)', () => { let code = '[1,2,3,4,5,6].slice(3)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return [1,2,3,4,5,6].slice(3); }) as any`)); }); it('Array.prototype.slice.call([1,2,3,4,5,6], 2)', () => { let code = 'Array.prototype.slice.call([1,2,3,4,5,6], 2)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.Array.prototype.slice.call([1,2,3,4,5,6], 2); }) as any`)); }); it('Array.prototype.slice.apply([1,2,3,4,5,6], [2])', () => { let code = 'Array.prototype.slice.apply([1,2,3,4,5,6], [2])'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.Array.prototype.slice.apply([1,2,3,4,5,6], [2]); }) as any`)); }); it('JSON.stringify({name: 1, age: 2})', () => { let code = 'JSON.stringify({name: 1, age: 2})'; expect(js_beautify(transform(code))).toBe(js_beautify(`((runTime: any) => { return runTime.JSON.stringify({name: 1, age: 2}); }) as any`)); }); }); describe('ConditionExpression', () => { it('1 + 1 > 0 ? true : false', () => { let code = '1 + 1 > 0 ? true : false'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 + 1 > 0 ? true : false; }) as any`)); }); it('1 + 1 < 0 ? true : false', () => { let code = '1 + 1 < 0 ? true : false'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 + 1 < 0 ? true : false; }) as any`)); }); it('({name: true}).name ? true : false', () => { let code = '({name: true}).name ? true : false'; expect(js_beautify(transform(code))).toBe(js_beautify(`((runTime: any) => { return ({name: true}).name ? true : false; }) as any`)); }); it('1 > 0 ? sumAll(prev, next) : sumAll(-prev, -next)', () => { let code = '1 > 0 ? sumAll(prev, next) : sumAll(-prev, -next)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 > 0 ? runTime.sumAll(runTime.prev, runTime.next) : runTime.sumAll(-runTime.prev, -runTime.next); }) as any`)); }); it('1 < 0 ? sumAll(prev, next) : sumAll(-prev, -next)', () => { let code = '1 < 0 ? sumAll(prev, next) : sumAll(-prev, -next)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 < 0 ? runTime.sumAll(runTime.prev, runTime.next) : runTime.sumAll(-runTime.prev, -runTime.next); }) as any`)); }); it('$data.str.length', () => { let code = '$data.str.length'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.$data.str.length; }) as any`)); }); it('$data.number.toFixed(2)', () => { let code = '$data.number.toFixed(2)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.$data.number.toFixed(2); }) as any`)); }); }); describe('ArrayExpression', () => { it('[1,2,3,4]', () => { let code = '[1,2,3,4]'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return [1,2,3,4]; }) as any`)); }); it('[1,2,3, ..."hello"]', () => { let code = '[1,2,3, ..."hello"]'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return [1,2,3, ..."hello"]; }) as any`)); }); it('[a, b, c, d, e, f, g]', () => { let code = '[a, b, c, d, e, f, g]'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return [runTime.a, runTime.b, runTime.c, runTime.d, runTime.e, runTime.f, runTime.g]; }) as any`)); }); it('[[],[],[[[]]]]', () => { let code = '[[],[],[[[a]]]]'; expect(js_beautify(transform(code))).toBe(js_beautify(`((runTime: any) => { return [[],[],[[[runTime.a]]]]; }) as any`)); }); }); describe('complex example', () => { it('$data.dateDiff === "1" && $data.dataKind === 1', () => { let code = '$data.dateDiff === "1" && $data.dataKind === 1'; expect(js_beautify(transform(code))).toBe(js_beautify(`((runTime: any) => { return runTime.$data.dateDiff === "1" && runTime.$data.dataKind === 1; }) as any`)); }); it('!($data.dateDiff === "1" && $data.dataKind === 1)', () => { let code = '!($data.dateDiff === "1" && $data.dataKind === 1)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return !(runTime.$data.dateDiff === "1" && runTime.$data.dataKind === 1); }) as any`)); }); }); describe('UnaryExpression', () => { it('!1', () => { let code = '!1'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return !1; }) as any`)); }); it('!a', () => { let code = '!a'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return !runTime.a; }) as any`)); }); it('-a', () => { let code = '-a'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return -runTime.a; }) as any`)); }); it('+a', () => { let code = '+a'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return +runTime.a; }) as any`)); }); }); describe('LogicExpression', () => { it('true || 0', () => { let code = 'true || 0'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return true || 0; }) as any`)); }); it('1 + 1 > 0 || false', () => { let code = '1 + 1 > 0 || false'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 + 1 > 0 || false; }) as any`)); }); it('1 + 1 < 0 || -1', () => { let code = '1 + 1 < 0 || -1'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 + 1 < 0 || -1; }) as any`)); }); it('1 + 1 > 0 && 1', () => { let code = '1 + 1 > 0 && 1'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 + 1 > 0 && 1; }) as any`)); }); it('1 + 1 > 0 && 1', () => { let code = '1 + 1 > 0 && 1'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 + 1 > 0 && 1; }) as any`)); }); it('1 + 1 > 0 && 1', () => { let code = '1 + 1 > 0 && a'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return 1 + 1 > 0 && runTime.a; }) as any`)); }); }); describe('FunctionExpression', () => { it('sum(1, 1)', () => { let code = 'sum(1, 1)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.sum(1, 1); }) as any`)); }); it('sum(sum(sum(sum(1, 2), sum(3, 4)), sum(5, 6)), sum(7, 8)))', () => { let code = 'sum(sum(sum(sum(1, 2), sum($data.name, 4)), sum(5, 6)), sum(7, 8)))'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.sum(runTime.sum(runTime.sum(runTime.sum(1, 2), runTime.sum(runTime.$data.name, 4)), runTime.sum(5, 6)), runTime.sum(7, 8)); }) as any`)); }); it('$data.sum', () => { let code = '$data.sum'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.$data.sum; }) as any`)); }); }); describe('Regexp', () => { it('/1462853203791|1462853496485|1462854074707|1462854136999/.test("1462853496485")', () => { let code = '/1462853203791|1462853496485|1462854074707|1462854136999/.test("1462853496485")'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return /1462853203791|1462853496485|1462854074707|1462854136999/.test("1462853496485"); }) as any`)); }); it('concat("1", "sum")', () => { let code = 'concat("1", "sum")'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return runTime.concat("1", "sum"); }) as any`)); }); }); describe('NewExpression', () => { it('new F(1,2,3,4)', () => { let code = 'new F(1,2,3,4)'; expect(transform(code)).toBe(js_beautify(`((runTime: any) => { return new runTime.F(1,2,3,4); }) as any`)); }); }); // describe('反斜杠字符串', () => { // it('反斜杠"', () => { // let code = '$data.calendarTotal.enabledReserveTotal === 0 ? \\"gd-inquiry-cell-danger\\" : \\"gd-inquiry-cell-success\\"'; // console.log(transform(code)); // }); // }); }); describe('transformFile', () => { it('只有一个ExpressionString的代码', () => { let code = `var body = { body: [{ type: 'button', text: '#ES{$data.name}' }] };`; expect(js_beautify(transformFile(code))).toEqual(js_beautify(`var body = { body: [{ type: 'button', text: (((runTime: any) => { return runTime.$data.name; }) as any) }] };`)); }); it('2个ExpressionString代码', () => { let code = `var body = { body: [{ type: 'button', text: '#ES{$data.name}' }, { type: 'text', text: '#ES{$moment.unix($data.startTime).format("YYYY-MM-DD")}' }] };`; expect(js_beautify(transformFile(code))).toEqual(js_beautify(` var body = { body: [{ type: 'button', text: (((runTime: any) => { return runTime.$data.name; }) as any) }, { type: 'text', text: (((runTime: any) => { return runTime.$moment.unix(runTime.$data.startTime).format("YYYY-MM-DD"); }) as any) }] }; `)); }); it('带有空格的ExpressionString', () => { let code = `var body = { body: [{ type: 'button', text: '#ES{$data.name}' }, { type: 'text', text: \`#ES{ $moment.unix( $data.startTime ) .format("YYYY-MM-DD")} \` }] };`; expect(js_beautify(transformFile(code))).toEqual(js_beautify(`var body = { body: [{ type: 'button', text: (((runTime: any) => { return runTime.$data.name; }) as any) }, { type: 'text', text: (((runTime: any) => { return runTime.$moment.unix(runTime.$data.startTime).format("YYYY-MM-DD"); }) as any) }] };`)); }); it('一个字符串有2个ExpressionString', () => { let code = ` import a from 'a'; var code = { body: [{ type: 'text', text: '唉 #ES{$data.name} W的 #ES{$data.age} W的' }] }`; expect(js_beautify(transformFile(code))).toBe(js_beautify('import a from \'a\'; \n var code = {\n' + ' body: [{\n' + ' type: \'text\',\n' + ' text: (((runTime: any) => {\n' + ' return `\\u5509 ${runTime.$data.name} W\\u7684 ${runTime.$data.age} W\\u7684`;\n' + ' }) as any)\n' + ' }]\n' + ' };')); }); it('一个字符串3个ExpressionString', () => { let code = ` var code = { body: [{ type: 'text', text: '#ES{$data.name} W的 #ES{$data.age}' }, { type: 'text', text: 'EE #ES{$data.username} BB #ES{$data.namespace} AA #ES{$data.code} DD' }] }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { body: [{ type: 'text', text: (((runTime: any) => { return \`\${runTime.$data.name} W\\u7684 \${runTime.$data.age}\`; }) as any) }, { type: 'text', text: (((runTime: any) => { return \`EE \${runTime.$data.username} BB \${runTime.$data.namespace} AA \${runTime.$data.code} DD\`; }) as any) }] };`)); }); it('属性访问模式的模板字符串', () => { let code = `var code = { body: [{ type: 'text', text: \`#ES{$data.\${KEY}.name}\` }] }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { body: [{ type: 'text', text: (((runTime: any) => { return runTime.$data[KEY].name; }) as any) }] };`)); }); it('字符串模式的模板字符串', () => { let code = `var code = { body: [{ type: 'text', text: \`#ES{$data.\${KEY}.name + "abcdefg\${STRING_KEY}"}\` }] }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { body: [{ type: 'text', text: (((runTime: any) => { return runTime.$data[KEY].name + ("abcdefg" + STRING_KEY + ""); }) as any) }] };`)); }); it('普通模板的模板字符串', () => { let code = `var code = { body: [{ type: 'text', text: \`#ES{\${FLAG} ? \${CPT} : \${CPM}}\` }] }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { body: [{ type: 'text', text: (((runTime: any) => { return FLAG ? CPT : CPM; }) as any) }] };`)); }); it('常见情况的模板字符串', () => { let code = `var code = { type: 'checkbox', name: 'creationDownCheckbox', model: 'format', groups: \`#ES{getCreationItems( checkboxHasSel([ \${config.plan} ? $data.planDownCheckbox : false, \${config.unit} ? $data.unitDownCheckbox : false, false ]), hasPermission('gd_download_creations_playdata_show') )}\` }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { type: 'checkbox', name: 'creationDownCheckbox', model: 'format', groups: (((runTime: any) => { return runTime.getCreationItems(runTime.checkboxHasSel(` + `[config.plan ? runTime.$data.planDownCheckbox : false, config.unit ? runTime.$data.unitDownCheckbox : false, false]),` + `runTime.hasPermission(\"gd_download_creations_playdata_show\")); }) as any) };`)); }); it('实例代码Two', () => { let code = `var code = { show: \`#ES{$item.mode == "\${CPM}"}\` };`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { show: (((runTime: any) => { return runTime.$item.mode == ("" + CPM + ""); }) as any) };`)); }); it('BinaryExpression & StringLiteral', () => { let code = `var code = { className: '#ES{$data.calendarTotal.enabledReserveTotal === 0 ? ' + '"gd-inquiry-cell-danger" : "gd-inquiry-cell-success"}' }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { className: (((runTime: any) => { return runTime.$data.calendarTotal.enabledReserveTotal === 0 ? "gd-inquiry-cell-danger" : "gd-inquiry-cell-success"; }) as any) };`)); }); it('BinaryExpression & TemplateExpression', () => { let code = `var code = { className: \`#ES{$data.\${CPM}}\` + 'abcd' + \`#ES{$data.test}\` }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { className: (((runTime: any) => { return \`\${runTime.$data[CPM]}abcd\${runTime.$data.test}\`; }) as any) };`)); }); it('TemplateExpression + TemplateExpression', () => { let code = `var code = { className: \`#ES{$data.\${CPM}}\` + \`#ES{$data.\${CPT}}\` };`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { className: (((runTime: any) => { return \`\${runTime.$data[CPM]}\${runTime.$data[CPT]}\`; }) as any) };`)); }); it('TemplateExpression + Template + Template', () => { let code = `var code = { className: \`#ES{$data.\${CPM}}\` + \`#ES{$data.\${CPT}}\` + \`#ES{$data.\${ABC}}\` };`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { className: (((runTime: any) => { return \`\${runTime.$data[CPM]}\${runTime.$data[CPT]}\${runTime.$data[ABC]}\`; }) as any) };`)); }); it('object key is ExpressionString', () => { let code = `var code = { 'key#ES{$data.key}qwewqe': 'abcd#ES{$data.name}eefrg' };`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { [(((runTime: any) => { return \`key\${runTime.$data.key}qwewqe\`; }) as any)()]: (((runTime: any) => { return \`abcd\${runTime.$data.name}eefrg\`; }) as any) };`)); console.log(transformFile(code)); }); it('object key with computedExpressionString', () => { let code = `var code = { ['key#ES{$data.key}qweq']: 'abc#ES{$data.anme}qweqwe' }`; expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { [(((runTime: any) => { return \`key\${runTime.$data.key}qweq\`; }) as any)()]: (((runTime: any) => { return \`abc\${runTime.$data.anme}qweqwe\`; }) as any) };`)); }); it('object key with computed TemplateString', () => { let code = `var code = { [\`key#ES{$data.\${KEY}}qwd\`]: 'abc#ES{$data.name}qweqwe' };`; // transformFile(code); expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { [(((runTime: any) => { return \`key\${runTime.$data[KEY]}qwd\`; }) as any)()]: (((runTime: any) => { return \`abc\${runTime.$data.name}qweqwe\`; }) as any) };`)); }); it('complex expressionString', () => { let code = `var code = { show: \`#ES{ $data.sales_type !== "-1" && $data.mode === '\${CPM}' && !/1481698145541|1481698231751/.test($data.place_id) && $data.special_mode !== "\${ORDER_CHASE}" }\`, }`; /* tslint-disable */ expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { show: (((runTime: any) => { return runTime.$data.sales_type !== "-1" && runTime.$data.mode === ("" + CPM + "") && !/1481698145541|1481698231751/.test(runTime.$data.place_id) && runTime.$data.special_mode !== ("" + ORDER_CHASE + ""); }) as any), };`)); }); it('Template object in function', () => { let code = `var code = { show: \`#ES{ $data.filterMode === '\${CPT}' ? \${JSON.stringify(filterCPTSaleTypeConfig)} : $data.filterMode === '\${CPM}' ? \${JSON.stringify(filterCPMSaleTypeConfig.CPT)} : \${JSON.stringify(filterAllSaleTypeConfig)} }\`, }`; /* tslint-disable */ expect(js_beautify(transformFile(code))).toBe(js_beautify(`var code = { show: (((runTime: any) => { return runTime.$data.filterMode === ("" + CPT + "") ? JSON.stringify(filterCPTSaleTypeConfig) : runTime.$data.filterMode === ("" + CPM + "") ? JSON.stringify(filterCPMSaleTypeConfig.CPT) : JSON.stringify(filterAllSaleTypeConfig); }) as any), };`)); }); });
the_stack
import { IsometricCanvas, IsometricRectangle, IsometricCircle, IsometricPath, PlaneView, SVGPathAnimation, SVGRectangleAnimation, SVGCircleAnimation } from '../src'; describe('Snapshot tests', (): void => { let container: HTMLDivElement; beforeEach((): void => { container = document.createElement('div'); document.body.appendChild(container); }); afterEach((): void => { if (container.parentNode && container.parentNode === document.body) { document.body.removeChild(container); } }); it('Draw rectangles', (): void => { const cube = new IsometricCanvas(container, { backgroundColor: '#CCC', scale: 120, width: 500, height: 320 }); const commonProps = {height: 1, width: 1}; const topPiece = new IsometricRectangle({...commonProps, planeView: PlaneView.TOP}); const rightPiece = new IsometricRectangle({...commonProps, planeView: PlaneView.FRONT}); const leftPiece = new IsometricRectangle({...commonProps, planeView: PlaneView.SIDE}); topPiece.top = 1; rightPiece.right = 1; leftPiece.left = 1; cube.addChild(topPiece).addChild(rightPiece).addChild(leftPiece); expect(container).toMatchSnapshot(); }); it('Draw circles', (): void => { const cube = new IsometricCanvas(container, { backgroundColor: '#CCC', scale: 120, width: 500, height: 320 }); const commonProps = {radius: 0.5}; const topPiece = new IsometricCircle({...commonProps, planeView: PlaneView.TOP}); const rightPiece = new IsometricCircle({...commonProps, planeView: PlaneView.FRONT}); const leftPiece = new IsometricCircle({...commonProps, planeView: PlaneView.SIDE}); topPiece.right = topPiece.left = 0.5; topPiece.top = 1; rightPiece.left = rightPiece.top = 0.5; rightPiece.right = 1; leftPiece.right = leftPiece.top = 0.5; leftPiece.left = 1; cube.addChild(topPiece).addChild(rightPiece).addChild(leftPiece); expect(container).toMatchSnapshot(); }); it('Draw methods', (): void => { const isometric = new IsometricCanvas(container, { backgroundColor: '#CCC', scale: 120, width: 500, height: 320 }); const bottomT = new IsometricPath(); const bottomR = new IsometricPath(); const bottomL = new IsometricPath(); const topT = new IsometricPath(); const topR = new IsometricPath(); const topL = new IsometricPath(); bottomT.moveTo(0, 0, .5).lineTo(1, 0, .5).lineTo(1, 1, .5).lineTo(0, 1, .5); bottomR.moveTo(1, 0, .5).lineTo(1, 0, 0).lineTo(1, 1, 0).lineTo(1, 1, .5); bottomL.moveTo(1, 1, .5).lineTo(1, 1, 0).lineTo(0, 1, 0).lineTo(0, 1, .5); topT.moveTo(.25, .25, 1.25).lineTo(.75, .25, 1.25).lineTo(.75, .75, 1).lineTo(.25, .75, 1); topR.moveTo(.75, .25, 1.25).lineTo(.75, .75, 1).lineTo(.75, .75, .5).lineTo(.75, .25, .5); topL.moveTo(.75, .75, 1).lineTo(.25, .75, 1).lineTo(.25, .75, .5).lineTo(.75, .75, .5); isometric.addChildren(bottomT, bottomR, bottomL, topT, topR, topL); expect(container).toMatchSnapshot(); }); it('Draw commands', (): void => { const isometric = new IsometricCanvas(container, { backgroundColor: '#CCC', scale: 120, width: 500, height: 320 }); const right = new IsometricPath(); const top1 = new IsometricPath(); const top2 = new IsometricPath(); const top3 = new IsometricPath(); const top4 = new IsometricPath(); const left1 = new IsometricPath(); const left2 = new IsometricPath(); right.draw('M1 0 0 L1 1 0 L1 1 0.25 L1 0.5 0.25 L1 0.5 1 L1 0 1'); top1.draw('M0.25 0.5 1 C0.5 0.5 0.75 0.75 0.5 1 L0.75 0 1 C0.5 0 0.75 0.25 0 1 L0.25 0.5 1'); top2.draw('M1 0 1 L0.75 0 1 L0.75 0.5 1 L1 0.5 1 L1 0 1 M0 0 1 L0.25 0 1 L0.25 0.5 1 L0 0.5 1 L0 0 1'); top3.draw('M0 0.5 0.5 L0.5 0.5 0.5 L0.5 1 0.5 L0 1 0.5'); top4.draw('M0.5 0.5 0.5 L1 0.5 0.25 L1 1 0.25 L0.5 1 0.5'); left1.draw('M0 0.5 1 L0 0.5 0.5 L0.5 0.5 0.5 L1 0.5 0.25 L1 0.5 1 L0.75 0.5 1 C0.5 0.5 0.75 0.25 0.5 1 L0 0.5 1'); left2.draw('M0 1 0.5 L0.5 1 0.5 L1 1 0.25 L1 1 0 L0 1 0'); isometric.addChildren(right, top1, top2, top3, top4, left1, left2); expect(container).toMatchSnapshot(); }); it('Draw curves with method aliases', (): void => { const cube = new IsometricCanvas(container, { backgroundColor: '#CCC', scale: 120, width: 500, height: 320 }); const under = new IsometricPath({ fillColor: '#EEE' }); const top = new IsometricPath(); const right = new IsometricPath(); const left = new IsometricPath(); under .mt(0, 0, 1) .mt(0.25, 0, 1).ct(0.5, 0, 0.75, 0.75, 0, 1).lt(1, 0, 1) .lt(1, 0, 0.75).ct(0.75, 0, 0.5, 1, 0, 0.25).lt(1, 0, 0) .lt(1, 0.25, 0).ct(0.75, 0.5, 0, 1, 0.75, 0).lt(1, 1, 0) .lt(0.75, 1, 0).ct(0.5, 0.75, 0, 0.25, 1, 0).lt(0, 1, 0) .lt(0, 1, 0.25).ct(0, 0.75, 0.5, 0, 1, 0.75).lt(0, 1, 1) .lt(0, 0.75, 1).ct(0, 0.5, 0.75, 0, 0.25, 1).lt(0, 0, 1); top .mt(0, 0, 1) .lt(0.25, 0, 1).ct(0.5, 0.25, 1, 0.75, 0, 1).lt(1, 0, 1) .lt(1, 0.25, 1).ct(0.75, 0.5, 1, 1, 0.75, 1).lt(1, 1, 1) .lt(0.75, 1, 1).ct(0.5, 0.75, 1, 0.25, 1, 1).lt(0, 1, 1) .lt(0, 0.75, 1).ct(0.25, 0.5, 1, 0, 0.25, 1).lt(0, 0, 1); right .mt(1, 0, 1) .lt(1, 0, 0.75).ct(1, 0.25, 0.5, 1, 0, 0.25).lt(1, 0, 0) .lt(1, 0.25, 0).ct(1, 0.5, 0.25, 1, 0.75, 0).lt(1, 1, 0) .lt(1, 1, 0.25).ct(1, 0.75, 0.5, 1, 1, 0.75).lt(1, 1, 1) .lt(1, 0.75, 1).ct(1, 0.5, 0.75, 1, 0.25, 1).lt(1, 0, 1); left .mt(1, 1, 1) .lt(1, 1, 0.75).ct(0.75, 1, 0.5, 1, 1, 0.25).lt(1, 1, 0) .lt(0.75, 1, 0).ct(0.5, 1, 0.25, 0.25, 1, 0).lt(0, 1, 0) .lt(0, 1, 0.25).ct(0.25, 1, 0.5, 0, 1, 0.75).lt(0, 1, 1) .lt(0.25, 1, 1).ct(0.5, 1, 0.75, 0.75, 1, 1).lt(1, 1, 1); cube.addChildren(under, top, right, left); expect(container).toMatchSnapshot(); }); it('Draw animations', (): void => { const isometric = new IsometricCanvas(container, { backgroundColor: '#CCC', scale: 120, width: 500, height: 320 }); const commonProps = {height: 1, width: 1}; const duration = 3; const colorAnimationProps = { property: 'fillColor', duration, values: ['#FFF', '#DDD', '#FFF'] }; const topPiece = new IsometricPath(); const rightPiece = new IsometricRectangle({...commonProps, planeView: PlaneView.FRONT}); const leftPiece = new IsometricRectangle({...commonProps, planeView: PlaneView.SIDE}); topPiece.mt(0, 0, 1).lt(1, 0, 1).lt(1, 1, 1).lt(0, 1, 1); rightPiece.right = 1; leftPiece.left = 1; topPiece .addAnimation({ property: 'path', duration, values: [ 'M0 0 1 L1 0 1 L1 1 1 L0 1 1', 'M0 0 0.5 L1 0 0.5 L1 1 0.5 L0 1 0.5', 'M0 0 1 L1 0 1 L1 1 1 L0 1 1' ] } as SVGPathAnimation) .addAnimation(colorAnimationProps as SVGPathAnimation); rightPiece .addAnimation({ property: 'height', duration, from: 1, to: 0.5 } as SVGRectangleAnimation) .addAnimation(colorAnimationProps as SVGRectangleAnimation); leftPiece .addAnimation({ property: 'height', duration, values: 0.5 } as SVGRectangleAnimation) .addAnimation(colorAnimationProps as SVGRectangleAnimation); isometric.addChildren(topPiece, rightPiece, leftPiece); expect(container).toMatchSnapshot(); }); it('Remove animations', (): void => { const isometric = new IsometricCanvas(container, { backgroundColor: '#CCC', scale: 120, width: 500, height: 320 }); const commonProps = {height: 1, width: 1}; const colorAnimationProps = { property: 'fillColor', values: ['#FFF', '#DDD', '#FFF'] }; const topPiece = new IsometricPath(); const rightPiece = new IsometricRectangle({...commonProps, planeView: PlaneView.FRONT}); const leftPiece = new IsometricRectangle({...commonProps, planeView: PlaneView.SIDE}); const circlePiece = new IsometricCircle({radius: 1, planeView: PlaneView.TOP}); topPiece.mt(0, 0, 1).lt(1, 0, 1).lt(1, 1, 1).lt(0, 1, 1); rightPiece.right = 1; leftPiece.left = 1; topPiece .addAnimation({ property: 'path', values: 'M0 0 1 L1 0 1 L1 1 1 L0 1 1' } as SVGPathAnimation) .addAnimation(colorAnimationProps as SVGPathAnimation); rightPiece .addAnimation({ property: 'height', from: 1, to: 0.5 } as SVGRectangleAnimation) .addAnimation(colorAnimationProps as SVGRectangleAnimation); leftPiece .addAnimation({ property: 'height', values: [1, 0.5] } as SVGRectangleAnimation) .addAnimation(colorAnimationProps as SVGRectangleAnimation); circlePiece .addAnimation({ property: 'radius', from: 1, to: 0.5 }) .addAnimation(colorAnimationProps as SVGCircleAnimation); // Remove animation before adding the elements rightPiece.removeAnimations(); topPiece.removeAnimationByIndex(1); circlePiece.removeAnimationByIndex(0); isometric.addChildren(topPiece, rightPiece, leftPiece, circlePiece); // Redraw the elements with animations topPiece.update(); // Remove animations after adding the elements leftPiece.removeAnimationByIndex(0); leftPiece.removeAnimations(); circlePiece.removeAnimations(); // Remove a wrong index topPiece.removeAnimationByIndex(1); topPiece.removeAnimationByIndex(10); // Add another animation topPiece.addAnimation({ property: 'path', from: 'M0 0 1 L1 0 1 L1 1 1 L0 1 1', to: 'M0 0 0.5 L1 0 0.5 L1 1 0.5 L0 1 0.5' } as SVGPathAnimation); topPiece.removeAnimations(); circlePiece .addAnimation({ property: 'radius', values: [0.5, 1] }); circlePiece.removeAnimationByIndex(0); circlePiece .addAnimation({ property: 'radius', values: 1 }); circlePiece.removeAnimations(); circlePiece .addAnimation({ property: 'left', from: 0, to: 1 }); circlePiece.removeAnimations(); expect(container).toMatchSnapshot(); }); });
the_stack
import Accordion, { AccordionDumb } from './components/Accordion/Accordion'; import Autocomplete, { AutocompleteDumb, } from './components/Autocomplete/Autocomplete'; import ButtonGroup, { ButtonGroupDumb, } from './components/ButtonGroup/ButtonGroup'; import SingleLineLoadingSkeleton from './components/LoadingSkeletons/SingleLineLoadingSkeleton'; import SearchableSelect, { SearchableSelectDumb, } from './components/SearchableSelect/SearchableSelect'; import DateSelect, { DateSelectDumb } from './components/DateSelect/DateSelect'; import SearchableMultiSelect, { SearchableMultiSelectDumb, } from './components/SearchableMultiSelect/SearchableMultiSelect'; import SearchableSingleSelect, { SearchableSingleSelectDumb, } from './components/SearchableSingleSelect/SearchableSingleSelect'; import DropMenu, { DropMenuDumb } from './components/DropMenu/DropMenu'; import Expander, { ExpanderDumb } from './components/Expander/Expander'; import ExpanderPanel, { ExpanderPanelDumb, } from './components/ExpanderPanel/ExpanderPanel'; import Paginator, { PaginatorDumb } from './components/Paginator/Paginator'; import PieChart, { PieChartDumb } from './components/PieChart/PieChart'; // @ts-ignore: not converted yet import RadioGroup, { RadioGroupDumb } from './components/RadioGroup/RadioGroup'; import SearchField, { SearchFieldDumb, } from './components/SearchField/SearchField'; import Sidebar, { SidebarDumb } from './components/Sidebar/Sidebar'; import SingleSelect, { SingleSelectDumb, } from './components/SingleSelect/SingleSelect'; import SplitButton, { SplitButtonDumb, } from './components/SplitButton/SplitButton'; import Submarine, { SubmarineDumb } from './components/Submarine/Submarine'; import Tabs, { TabsDumb } from './components/Tabs/Tabs'; import ToolTip, { ToolTipDumb } from './components/ToolTip/ToolTip'; import VerticalListMenu, { VerticalListMenuDumb, } from './components/VerticalListMenu/VerticalListMenu'; import VerticalTabs, { VerticalTabsDumb, } from './components/VerticalTabs/VerticalTabs'; // dumb components import AddURLIcon from './components/Icon/AddURLIcon/AddURLIcon'; import AddColumnIcon from './components/Icon/AddColumnIcon/AddColumnIcon'; import AnalyzeDataIcon from './components/Icon/AnalyzeDataIcon/AnalyzeDataIcon'; import ArrowIcon from './components/Icon/ArrowIcon/ArrowIcon'; import AsteriskIcon from './components/Icon/AsteriskIcon/AsteriskIcon'; import AttachIcon from './components/Icon/AttachIcon/AttachIcon'; import AudioIcon from './components/Icon/AudioIcon/AudioIcon'; import Axis from './components/Axis/Axis'; // @ts-ignore: not converted yet import AxisLabel from './components/AxisLabel/AxisLabel'; import BackUpArrowIcon from './components/Icon/BackUpArrowIcon/BackUpArrowIcon'; import Badge from './components/Badge/Badge'; import Banner from './components/Banner/Banner'; import Bar from './components/Bar/Bar'; // @ts-ignore: not converted yet import BarChart from './components/BarChart/BarChart'; import BarChartIcon from './components/Icon/BarChartIcon/BarChartIcon'; import BarChartLoadingSkeleton from './components/LoadingSkeletons/BarChartLoadingSkeleton'; // @ts-ignore: not converted yet import Bars from './components/Bars/Bars'; import BellIcon from './components/Icon/BellIcon/BellIcon'; import BookIcon from './components/Icon/BookIcon/BookIcon'; import Breadcrumb from './components/Breadcrumb/Breadcrumb'; import Button from './components/Button/Button'; import CalculatorIcon from './components/Icon/CalculatorIcon/CalculatorIcon'; import CalendarIcon from './components/Icon/CalendarIcon/CalendarIcon'; import ChatIcon from './components/Icon/ChatIcon/ChatIcon'; import CheckIcon from './components/Icon/CheckIcon/CheckIcon'; import Checkbox from './components/Checkbox/Checkbox'; import CheckboxLabeled from './components/CheckboxLabeled/CheckboxLabeled'; import ChevronIcon from './components/Icon/ChevronIcon/ChevronIcon'; import ClockIcon from './components/Icon/ClockIcon/ClockIcon'; import CodeIcon from './components/Icon/CodeIcon/CodeIcon'; import Collapsible from './components/Collapsible/Collapsible'; import ComplexTableLoadingSkeleton from './components/LoadingSkeletons/ComplexTableLoadingSkeleton'; import ContextMenu from './components/ContextMenu/ContextMenu'; import CloseIcon from './components/Icon/CloseIcon/CloseIcon'; import CrownIcon from './components/Icon/CrownIcon/CrownIcon'; import DangerIcon from './components/Icon/DangerIcon/DangerIcon'; import DangerLightIcon from './components/Icon/DangerLightIcon/DangerLightIcon'; // @ts-ignore: not converted yet import DataTable from './components/DataTable/DataTable'; import DeleteIcon from './components/Icon/DeleteIcon/DeleteIcon'; import DotsIcon from './components/Icon/DotsIcon/DotsIcon'; import DoubleChevronIcon from './components/Icon/DoubleChevronIcon/DoubleChevronIcon'; import Dialog from './components/Dialog/Dialog'; import DownloadIcon from './components/Icon/DownloadIcon/DownloadIcon'; import DragCaptureZone from './components/DragCaptureZone/DragCaptureZone'; import DraggableLineChart from './components/DraggableLineChart/DraggableLineChart'; import DraggableList from './components/DraggableList/DraggableList'; import DuplicateIcon from './components/Icon/DuplicateIcon/DuplicateIcon'; import EditIcon from './components/Icon/EditIcon/EditIcon'; import EligibilityIcon from './components/Icon/EligibilityIcon/EligibilityIcon'; import EligibilityLightIcon from './components/Icon/EligibilityLightIcon/EligibilityLightIcon'; import EmptyStateWrapper from './components/EmptyStateWrapper/EmptyStateWrapper'; import EnvelopeIcon from './components/Icon/EnvelopeIcon/EnvelopeIcon'; import EqualsIcon from './components/Icon/EqualsIcon/EqualsIcon'; import FileIcon from './components/Icon/FileIcon/FileIcon'; import FilterIcon from './components/Icon/FilterIcon/FilterIcon'; // @ts-ignore: not converted yet import FlagIcon from './components/Icon/FlagIcon/FlagIcon'; import FolderIcon from './components/Icon/FolderIcon/FolderIcon'; // @ts-ignore: not converted yet import FourSquaresIcon from './components/Icon/FourSquaresIcon/FourSquaresIcon'; import GetMaximumIcon from './components/Icon/GetMaximumIcon/GetMaximumIcon'; import GlobeIcon from './components/Icon/GlobeIcon/GlobeIcon'; import Grid from './components/Grid/Grid'; import GroupLoadingSkeleton from './components/LoadingSkeletons/GroupLoadingSkeleton'; import HamburgerMenuIcon from './components/Icon/HamburgerMenuIcon/HamburgerMenuIcon'; import HeaderLoadingSkeleton from './components/LoadingSkeletons/HeaderLoadingSkeleton'; import HelpIcon from './components/Icon/HelpIcon/HelpIcon'; import HideIcon from './components/Icon/HideIcon/HideIcon'; import HomeIcon from './components/Icon/HomeIcon/HomeIcon'; import HostedIcon from './components/Icon/HostedIcon/HostedIcon'; import Icon from './components/Icon/Icon'; import IconSelect from './components/IconSelect/IconSelect'; import ImageIcon from './components/Icon/ImageIcon/ImageIcon'; import InfoIcon from './components/Icon/InfoIcon/InfoIcon'; import InfoLightIcon from './components/Icon/InfoLightIcon/InfoLightIcon'; import InheritedSettingsIcon from './components/Icon/InheritedSettingsIcon/InheritedSettingsIcon'; import Legend from './components/Legend/Legend'; import LightbulbIcon from './components/Icon/LightbulbIcon/LightbulbIcon'; import Line from './components/Line/Line'; // @ts-ignore: not converted yet import LineChart from './components/LineChart/LineChart'; import LineChartLoadingSkeleton from './components/LoadingSkeletons/LineChartLoadingSkeleton'; import Lines from './components/Lines/Lines'; import LinkedIcon from './components/Icon/LinkedIcon/LinkedIcon'; import LoadingIcon from './components/Icon/LoadingIcon/LoadingIcon'; import LoadingIndicator from './components/LoadingIndicator/LoadingIndicator'; import LoadingMessage from './components/LoadingMessage/LoadingMessage'; import LockedIcon from './components/Icon/LockedIcon/LockedIcon'; import MaximizeIcon from './components/Icon/MaximizeIcon/MaximizeIcon'; import MegaphoneIcon from './components/Icon/MegaphoneIcon/MegaphoneIcon'; import MinimizeIcon from './components/Icon/MinimizeIcon/MinimizeIcon'; import MinusCircleIcon from './components/Icon/MinusCircleIcon/MinusCircleIcon'; import MinusCircleLightIcon from './components/Icon/MinusCircleLightIcon/MinusCircleLightIcon'; import MinusIcon from './components/Icon/MinusIcon/MinusIcon'; import NewWindowIcon from './components/Icon/NewWindowIcon/NewWindowIcon'; import NotchedTag from './components/NotchedTag/NotchedTag'; import OutwardArrowsIcon from './components/Icon/OutwardArrowsIcon/OutwardArrowsIcon'; import Overlay from './components/Overlay/Overlay'; import OverlayWrapper from './components/OverlayWrapper/OverlayWrapper'; import Panel from './components/Panel/Panel'; import PinIcon from './components/Icon/PinIcon/PinIcon'; import PlusIcon from './components/Icon/PlusIcon/PlusIcon'; import Point from './components/Point/Point'; import Points from './components/Points/Points'; import Portal from './components/Portal/Portal'; import ProgressBar from './components/ProgressBar/ProgressBar'; import QuestionMarkIcon from './components/Icon/QuestionMarkIcon/QuestionMarkIcon'; import RadioButton from './components/RadioButton/RadioButton'; import RadioButtonLabeled from './components/RadioButtonLabeled/RadioButtonLabeled'; import RefreshIcon from './components/Icon/RefreshIcon/RefreshIcon'; import ReportIcon from './components/Icon/ReportIcon/ReportIcon'; import ResizeIcon from './components/Icon/ResizeIcon/ResizeIcon'; import Resizer from './components/Resizer/Resizer'; import ResponsiveGrid from './components/ResponsiveGrid/ResponsiveGrid'; import RolloverIcon from './components/Icon/RolloverIcon/RolloverIcon'; import RunReportIcon from './components/Icon/RunReportIcon/RunReportIcon'; import SaveIcon from './components/Icon/SaveIcon/SaveIcon'; import ScrollTable from './components/ScrollTable/ScrollTable'; import SearchIcon from './components/Icon/SearchIcon/SearchIcon'; import Selection from './components/Selection/Selection'; import SeparatorIcon from './components/Icon/SeparatorIcon/SeparatorIcon'; import SettingsIcon from './components/Icon/SettingsIcon/SettingsIcon'; import ShareIcon from './components/Icon/ShareIcon/ShareIcon'; import ShoppingCartIcon from './components/Icon/ShoppingCartIcon/ShoppingCartIcon'; import SidePanel from './components/SidePanel/SidePanel'; import SimpleTableLoadingSkeleton from './components/LoadingSkeletons/SimpleTableLoadingSkeleton'; import SmallDataTableLoadingSkeleton from './components/LoadingSkeletons/SmallDataTableLoadingSkeleton'; import SplitHorizontal from './components/SplitHorizontal/SplitHorizontal'; import SplitVertical from './components/SplitVertical/SplitVertical'; import StarIcon from './components/Icon/StarIcon/StarIcon'; import StarOutlineIcon from './components/Icon/StarOutlineIcon/StarOutlineIcon'; import StickySection from './components/StickySection/StickySection'; import StopwatchIcon from './components/Icon/StopwatchIcon/StopwatchIcon'; import SuccessIcon from './components/Icon/SuccessIcon/SuccessIcon'; import SuccessLightIcon from './components/Icon/SuccessLightIcon/SuccessLightIcon'; import Switch from './components/Switch/Switch'; import SwitchIcon from './components/Icon/SwitchIcon/SwitchIcon'; import SwitchLabeled from './components/SwitchLabeled/SwitchLabeled'; import Table from './components/Table/Table'; import TableIcon from './components/Icon/TableIcon/TableIcon'; import TableLoadingSkeleton from './components/LoadingSkeletons/TableLoadingSkeleton'; import Tag from './components/Tag/Tag'; import TextField from './components/TextField/TextField'; import TextFieldPlain from './components/TextField/TextFieldPlain'; import TextFieldValidated from './components/TextFieldValidated/TextFieldValidated'; import TextIcon from './components/Icon/TextIcon/TextIcon'; import TicketIcon from './components/Icon/TicketIcon/TicketIcon'; import TimeSelect from './components/TimeSelect/TimeSelect'; import Typography from './components/Typography/Typography'; import Underline from './components/Underline/Underline'; import UnlinkedIcon from './components/Icon/UnlinkedIcon/UnlinkedIcon'; import UnlockedIcon from './components/Icon/UnlockedIcon/UnlockedIcon'; import UploadIcon from './components/Icon/UploadIcon/UploadIcon'; import UserIcon from './components/Icon/UserIcon/UserIcon'; import Validation from './components/Validation/Validation'; import VideoIcon from './components/Icon/VideoIcon/VideoIcon'; import VideoLiveIcon from './components/Icon/VideoLiveIcon/VideoLiveIcon'; import VideoLongIcon from './components/Icon/VideoLongIcon/VideoLongIcon'; import VideoOnDemandIcon from './components/Icon/VideoOnDemandIcon/VideoOnDemandIcon'; import VideoShortIcon from './components/Icon/VideoShortIcon/VideoShortIcon'; import ViewIcon from './components/Icon/ViewIcon/ViewIcon'; import ViewTableIcon from './components/Icon/ViewTableIcon/ViewTableIcon'; import WarningIcon from './components/Icon/WarningIcon/WarningIcon'; import WarningLightIcon from './components/Icon/WarningLightIcon/WarningLightIcon'; import WrenchIcon from './components/Icon/WrenchIcon/WrenchIcon'; import CardLoadingSkeleton from './components/LoadingSkeletons/CardLoadingSkeleton'; // utils import * as componentTypes from './util/component-types'; import * as domHelpers from './util/dom-helpers'; import * as stateManagement from './util/state-management'; import * as styleHelpers from './util/style-helpers'; import * as redux from './util/redux'; import * as chartConstants from './constants/charts'; import * as formatters from './util/formatters'; import * as logger from './util/logger'; import * as d3Scale from 'd3-scale'; import * as d3Time from 'd3-time'; export { componentTypes, domHelpers, redux, stateManagement, styleHelpers, chartConstants, formatters, logger, d3Scale, d3Time, }; export { Accordion, AccordionDumb, AddURLIcon, AddColumnIcon, AnalyzeDataIcon, ArrowIcon, AsteriskIcon, AttachIcon, AudioIcon, Autocomplete, AutocompleteDumb, Axis, AxisLabel, BackUpArrowIcon, Badge, Banner, Bar, BarChart, BarChartIcon, BarChartLoadingSkeleton, Bars, BellIcon, BookIcon, Breadcrumb, Button, ButtonGroup, ButtonGroupDumb, CalculatorIcon, CalendarIcon, CardLoadingSkeleton, ChatIcon, Checkbox, CheckboxLabeled, CheckIcon, ChevronIcon, ClockIcon, CodeIcon, Collapsible, ComplexTableLoadingSkeleton, ContextMenu, CloseIcon, CrownIcon, DangerIcon, DangerLightIcon, DataTable, DateSelect, DateSelectDumb, DeleteIcon, Dialog, DotsIcon, DoubleChevronIcon, DownloadIcon, DragCaptureZone, DraggableLineChart, DraggableList, DropMenu, DropMenuDumb, DuplicateIcon, EditIcon, EligibilityIcon, EligibilityLightIcon, EmptyStateWrapper, EnvelopeIcon, EqualsIcon, Expander, ExpanderDumb, ExpanderPanel, ExpanderPanelDumb, FileIcon, FilterIcon, FlagIcon, FolderIcon, FourSquaresIcon, GetMaximumIcon, GlobeIcon, Grid, GroupLoadingSkeleton, HamburgerMenuIcon, HeaderLoadingSkeleton, HelpIcon, HideIcon, HomeIcon, HostedIcon, Icon, IconSelect, ImageIcon, InfoIcon, InfoLightIcon, InheritedSettingsIcon, Legend, LightbulbIcon, Line, LineChart, LineChartLoadingSkeleton, Lines, LinkedIcon, LoadingIcon, LoadingIndicator, LoadingMessage, LockedIcon, MaximizeIcon, MegaphoneIcon, MinimizeIcon, MinusCircleIcon, MinusCircleLightIcon, MinusIcon, NewWindowIcon, NotchedTag, OutwardArrowsIcon, Overlay, OverlayWrapper, Paginator, PaginatorDumb, Panel, PieChart, PieChartDumb, PinIcon, PlusIcon, Point, Points, Portal, ProgressBar, QuestionMarkIcon, RadioButton, RadioButtonLabeled, RadioGroup, RadioGroupDumb, RefreshIcon, ReportIcon, ResizeIcon, Resizer, ResponsiveGrid, RolloverIcon, RunReportIcon, SaveIcon, ScrollTable, SearchableMultiSelect, SearchableMultiSelectDumb, SearchableSingleSelect, SearchableSingleSelectDumb, SearchableSelect, SearchableSelectDumb, SearchField, SearchFieldDumb, SearchIcon, Selection, SeparatorIcon, SettingsIcon, ShareIcon, ShoppingCartIcon, SidePanel, Sidebar, SidebarDumb, SingleLineLoadingSkeleton, SingleSelect, SingleSelectDumb, SplitButton, SplitButtonDumb, SimpleTableLoadingSkeleton, SmallDataTableLoadingSkeleton, SplitHorizontal, SplitVertical, StarIcon, StarOutlineIcon, StickySection, StopwatchIcon, Submarine, SubmarineDumb, SuccessIcon, SuccessLightIcon, Switch, SwitchIcon, SwitchLabeled, Table, TableLoadingSkeleton, TableIcon, Tabs, TabsDumb, Tag, TextIcon, TextField, TextFieldPlain, TextFieldValidated, TicketIcon, ToolTip, ToolTipDumb, TimeSelect, Typography, Underline, UnlinkedIcon, UnlockedIcon, UploadIcon, UserIcon, Validation, VerticalListMenu, VerticalListMenuDumb, VerticalTabs, VerticalTabsDumb, VideoIcon, VideoLiveIcon, VideoLongIcon, VideoOnDemandIcon, VideoShortIcon, ViewIcon, ViewTableIcon, WarningIcon, WarningLightIcon, WrenchIcon, }; // Export types export * from './components/Banner/Banner'; export * from './components/Tabs/Tabs'; export * from './components/SearchField/SearchField';
the_stack
import EditorUI = require("ui/EditorUI"); import PlayMode = require("ui/playmode/PlayMode"); import EditorLicense = require("./EditorLicense"); import EditorEvents = require("./EditorEvents"); import Preferences = require("./Preferences"); class AtomicEditor extends Atomic.ScriptObject { project: ToolCore.Project; editorLicense: EditorLicense; playMode: PlayMode; static instance: AtomicEditor; projectCloseRequested: boolean; exitRequested: boolean; constructor() { super(); // limit the framerate to limit CPU usage Atomic.getEngine().maxFps = 60; Atomic.getEngine().autoExit = false; AtomicEditor.instance = this; Preferences.getInstance().read(); this.initUI(); this.editorLicense = new EditorLicense(); EditorUI.initialize(this); this.playMode = new PlayMode(); Atomic.getResourceCache().autoReloadResources = true; this.subscribeToEvent(Editor.EditorLoadProjectEvent((data) => this.handleEditorLoadProject(data))); this.subscribeToEvent(Editor.EditorCloseProjectEvent((data) => this.handleEditorCloseProject(data))); this.subscribeToEvent(Editor.ProjectUnloadedNotificationEvent((data) => { Atomic.graphics.windowTitle = "AtomicEditor"; this.handleProjectUnloaded(data); })); this.subscribeToEvent(Atomic.ScriptEvent(EditorEvents.IPCPlayerWindowChangedEventType, (data: AtomicApp.IPCPlayerWindowChangedEvent) => { var playerWindow = Preferences.getInstance().playerWindow; //if player window is maximized, then we want keep the window size from the previous state if (data.maximized) { playerWindow.x = data.posX; playerWindow.y = data.posY; playerWindow.monitor = data.monitor; playerWindow.maximized = true; } else { playerWindow = {x: data.posX, y: data.posY, width: data.width, height: data.height, monitor: data.monitor, maximized: data.maximized}; } Preferences.getInstance().savePlayerWindowData(playerWindow); })); this.subscribeToEvent(Atomic.ScreenModeEvent((data) => this.saveWindowPreferences())); this.subscribeToEvent(Atomic.WindowPosEvent((data) => this.saveWindowPreferences())); this.subscribeToEvent(Atomic.ExitRequestedEvent((data) => this.handleExitRequested(data))); this.subscribeToEvent(ToolCore.ProjectLoadedEvent((data) => { Atomic.graphics.windowTitle = "AtomicEditor - " + data.projectPath; Preferences.getInstance().registerRecentProject(data.projectPath); })); this.subscribeToEvent(Editor.EditorResourceCloseCanceledEvent((data) => { //if user canceled closing the resource, then user has changes that he doesn't want to lose //so cancel exit/project close request and unsubscribe from event to avoid closing all the editors again this.exitRequested = false; this.projectCloseRequested = false; this.unsubscribeFromEvent(Editor.EditorResourceCloseEventType); })); this.parseArguments(); } initUI() { var uiData = Preferences.getInstance().uiData; var ui = Atomic.ui; ui.loadSkin(uiData.skinPath + "/skin.tb.txt", uiData.defaultSkinPath + "/skin.tb.txt"); ui.addFont(uiData.fontFile, uiData.fontName); ui.addFont("AtomicEditor/resources/MesloLGS-Regular.ttf", "Monaco"); ui.setDefaultFont(uiData.fontName, uiData.fontSize); } saveWindowPreferences(): boolean { var graphics = Atomic.getGraphics(); if (!graphics) return false; var pos = graphics.getWindowPosition(); var width = graphics.getWidth(); var height = graphics.getHeight(); var monitor = graphics.getCurrentMonitor(); var editorWindowData = Preferences.getInstance().editorWindow; if (graphics.getMaximized()) { editorWindowData.x = pos[0]; editorWindowData.y = pos[1]; editorWindowData.maximized = true; editorWindowData.monitor = monitor; } else { editorWindowData = {x: pos[0], y: pos[1], width: width, height: height, monitor: monitor, maximized: false}; } Preferences.getInstance().saveEditorWindowData(editorWindowData); return true; } /** * Return a preference value or the provided default from the user settings file * @param {string} extensionName name of the extension the preference lives under * @param {string} preferenceName name of the preference to retrieve * @param {number | boolean | string} defaultValue value to return if pref doesn't exist * @return {number|boolean|string} */ getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number; getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string; getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean; getUserPreference(extensionName: string, preferenceName: string, defaultValue?: any): any { return Preferences.getInstance().getUserPreference(extensionName, preferenceName, defaultValue); } /** * Sets a user preference value in the project user settings file * @param {string} extensionName name of the extension the preference lives under * @param {string} preferenceName name of the preference to set * @param {number | boolean | string} value value to set */ setUserPreference(extensionName: string, preferenceName: string, value: number | boolean | string) { Preferences.getInstance().setUserPreference(extensionName, preferenceName, value); WebView.WebBrowserHost.setGlobalStringProperty("HOST_Preferences", "ProjectPreferences", JSON.stringify(Preferences.getInstance().cachedProjectPreferences, null, 2 )); const eventData: Editor.UserPreferencesChangedNotificationEvent = { projectPreferences: JSON.stringify(Preferences.getInstance().cachedProjectPreferences), applicationPreferences: JSON.stringify(Preferences.getInstance().cachedApplicationPreferences) }; this.sendEvent(Editor.UserPreferencesChangedNotificationEventData(eventData)); } /** * Return a preference value or the provided default from the global user settings file * @param {string} groupName name of the section the preference lives under * @param {string} preferenceName name of the preference to retrieve * @param {number | boolean | string} defaultValue value to return if pref doesn't exist * @return {number|boolean|string} */ getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number; getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string; getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean; getApplicationPreference(groupName: string, preferenceName: string, defaultValue?: any): any { return Preferences.getInstance().getApplicationPreference(groupName, preferenceName, defaultValue); } /** * Sets a user preference value in the global application settings file * @param {string} groupName name of the section the preference lives under * @param {string} preferenceName name of the preference to set * @param {number | boolean | string} value value to set */ setApplicationPreference(groupName: string, preferenceName: string, value: number | boolean | string) { Preferences.getInstance().setApplicationPreference(groupName, preferenceName, value); WebView.WebBrowserHost.setGlobalStringProperty("HOST_Preferences", "ApplicationPreferences", JSON.stringify(Preferences.getInstance().cachedApplicationPreferences, null, 2 )); const eventData: Editor.UserPreferencesChangedNotificationEvent = { projectPreferences: JSON.stringify(Preferences.getInstance().cachedProjectPreferences), applicationPreferences: JSON.stringify(Preferences.getInstance().cachedApplicationPreferences) }; this.sendEvent(Editor.UserPreferencesChangedNotificationEventData(eventData)); } /** * Sets a group of user preference values in the user settings file located in the project. Elements in the * group will merge in with existing group preferences. Use this method if setting a bunch of settings * at once. * @param {string} settingsGroup name of the group the preference lives under * @param {string} groupPreferenceValues an object literal containing all of the preferences for the group. */ setUserPreferenceGroup(settingsGroup: string, groupPreferenceValues: Object) { Preferences.getInstance().setUserPreferenceGroup(settingsGroup, groupPreferenceValues); WebView.WebBrowserHost.setGlobalStringProperty("HOST_Preferences", "ProjectPreferences", JSON.stringify(Preferences.getInstance().cachedProjectPreferences, null, 2 )); const eventData: Editor.UserPreferencesChangedNotificationEvent = { projectPreferences: JSON.stringify(Preferences.getInstance().cachedProjectPreferences), applicationPreferences: JSON.stringify(Preferences.getInstance().cachedApplicationPreferences) }; this.sendEvent(Editor.UserPreferencesChangedNotificationEventData(eventData)); } handleEditorLoadProject(event: Editor.LoadProjectNotificationEvent): boolean { var system = ToolCore.getToolSystem(); if (system.project) { this.sendEvent(Editor.EditorModalEventData({ type: Editor.EDITOR_MODALERROR, title: "Project already loaded", message: "Project already loaded" })); return false; } const loaded = system.loadProject(event.path); if (loaded) { Preferences.getInstance().loadUserPrefs(); WebView.WebBrowserHost.setGlobalStringProperty("HOST_Preferences", "ProjectPreferences", JSON.stringify(Preferences.getInstance().cachedProjectPreferences, null, 2 )); WebView.WebBrowserHost.setGlobalStringProperty("HOST_Preferences", "ApplicationPreferences", JSON.stringify(Preferences.getInstance().cachedApplicationPreferences, null, 2 )); this.sendEvent(Editor.LoadProjectNotificationEventData(event)); } return loaded; } closeAllResourceEditors() { var editor = EditorUI.getCurrentResourceEditor(); if (!editor) { if (this.exitRequested) { this.exit(); } else if (this.projectCloseRequested) { this.closeProject(); } return; } //wait when we close resource editor to check another resource editor for unsaved changes and close it this.subscribeToEvent(Editor.EditorResourceCloseEvent((data) => { this.closeAllResourceEditors(); })); editor.requestClose(); } handleEditorCloseProject(event: Editor.ProjectUnloadedNotificationEvent) { this.projectCloseRequested = true; this.sendEvent(Editor.ProjectUnloadedNotificationEventData()); this.closeAllResourceEditors(); } closeProject() { this.sendEvent(EditorEvents.IPCPlayerExitRequestEventType); var system = ToolCore.getToolSystem(); if (system.project) { system.closeProject(); this.sendEvent(Editor.EditorProjectClosedEventType); this.projectCloseRequested = false; this.unsubscribeFromEvent(Editor.EditorResourceCloseEventType); } } handleProjectUnloaded(event) { this.sendEvent(Editor.EditorActiveSceneEditorChangeEventData({ sceneEditor: null })); } parseArguments() { var args = Atomic.getArguments(); var idx = 0; while (idx < args.length) { if (args[idx] == "--project") { this.sendEvent(Editor.EditorLoadProjectEventData({ path: args[idx + 1] })); } idx++; } } // event handling handleExitRequested(data) { if (this.exitRequested) return; this.exitRequested = true; this.closeAllResourceEditors(); } exit() { //Preferences.getInstance().write(); EditorUI.shutdown(); Atomic.getEngine().exit(); } } export default AtomicEditor;
the_stack
import CreateDom from "@/lib/main-entrance/CreateDom"; // 导入截图所需样式 import "@/assets/scss/screen-short.scss"; import InitData from "@/lib/main-entrance/InitData"; import { cutOutBoxBorder, drawCutOutBoxReturnType, movePositionType, positionInfoType, screenShotType, zoomCutOutBoxReturnType } from "@/lib/type/ComponentType"; import { drawMasking } from "@/lib/split-methods/DrawMasking"; import { fixedData, nonNegativeData } from "@/lib/common-methords/FixedData"; import { drawPencil, initPencil } from "@/lib/split-methods/DrawPencil"; import { drawText } from "@/lib/split-methods/DrawText"; import { drawRectangle } from "@/lib/split-methods/DrawRectangle"; import { drawCircle } from "@/lib/split-methods/DrawCircle"; import { drawLineArrow } from "@/lib/split-methods/DrawLineArrow"; import { drawMosaic } from "@/lib/split-methods/DrawMosaic"; import { drawCutOutBox } from "@/lib/split-methods/DrawCutOutBox"; import { zoomCutOutBoxPosition } from "@/lib/common-methords/ZoomCutOutBoxPosition"; import { saveBorderArrInfo } from "@/lib/common-methords/SaveBorderArrInfo"; import { calculateToolLocation } from "@/lib/split-methods/CalculateToolLocation"; import html2canvas from "html2canvas"; import PlugInParameters from "@/lib/main-entrance/PlugInParameters"; import { getDrawBoundaryStatus } from "@/lib/split-methods/BoundaryJudgment"; import KeyboardEventHandle from "@/lib/split-methods/KeyboardEventHandle"; import { setPlugInParameters } from "@/lib/split-methods/SetPlugInParameters"; import { drawCrossImg } from "@/lib/split-methods/drawCrossImg"; export default class ScreenShort { // 当前实例的响应式data数据 private readonly data: InitData; // video容器用于存放屏幕MediaStream流 private readonly videoController: HTMLVideoElement; // 截图区域canvas容器 private readonly screenShotContainer: HTMLCanvasElement | null; // 截图工具栏dom private readonly toolController: HTMLDivElement | null; // 截图图片存放容器 private screenShortImageController: HTMLCanvasElement; // 截图区域画布 private screenShortCanvas: CanvasRenderingContext2D | undefined; // 文本区域dom private readonly textInputController: HTMLDivElement | null; // 截图工具栏画笔选项dom private optionController: HTMLDivElement | null; private optionIcoController: HTMLDivElement | null; private cutBoxSizeContainer: HTMLDivElement | null; // 图形位置参数 private drawGraphPosition: positionInfoType = { startX: 0, startY: 0, width: 0, height: 0 }; // 临时图形位置参数 private tempGraphPosition: positionInfoType = { startX: 0, startY: 0, width: 0, height: 0 }; // 裁剪框边框节点坐标事件 private cutOutBoxBorderArr: Array<cutOutBoxBorder> = []; // 当前操作的边框节点 private borderOption: number | null = null; // 点击裁剪框时的鼠标坐标 private movePosition: movePositionType = { moveStartX: 0, moveStartY: 0 }; // 鼠标点击状态 private clickFlag = false; // 鼠标拖动状态 private dragFlag = false; // 单击截取屏启用状态 private clickCutFullScreen = false; // 全屏截取状态 private getFullScreenStatus = false; // 上一个裁剪框坐标信息 private drawGraphPrevX = 0; private drawGraphPrevY = 0; private fontSize = 17; // 最大可撤销次数 private maxUndoNum = 15; // 马赛克涂抹区域大小 private degreeOfBlur = 5; // 截图容器位置信息 private position: { top: number; left: number } = { left: 0, top: 0 }; private imgSrc: string | null = null; private loadCrossImg = false; private drawStatus = false; // 文本输入框位置 private textInputPosition: { mouseX: number; mouseY: number } = { mouseX: 0, mouseY: 0 }; constructor(options: screenShotType) { // 提取options中的有用参数设置到全局参数中 setPlugInParameters(options); // 创建截图所需dom并设置回调函数 new CreateDom(options); // 创建并获取webrtc模式所需要的辅助dom this.videoController = document.createElement("video"); this.videoController.autoplay = true; this.screenShortImageController = document.createElement("canvas"); // 实例化响应式data this.data = new InitData(); // 单击截取全屏启用状态,默认为false if (options?.clickCutFullScreen === true) { this.clickCutFullScreen = true; } // 判断调用者是否传了截图进来 if (options?.imgSrc != null) { this.imgSrc = options.imgSrc; } // 是否加载跨域图片 if (options?.loadCrossImg === true) { this.loadCrossImg = true; } // 设置截图容器的位置信息 if (options?.position != null) { if (options.position?.top != null) { this.position.top = options.position.top; } if (options.position?.left != null) { this.position.left = options.position.left; } } // 获取截图区域canvas容器(获取的同时也会为InitData中的全局变量赋值) this.screenShotContainer = this.data.getScreenShotContainer() as HTMLCanvasElement | null; this.toolController = this.data.getToolController() as HTMLDivElement | null; this.textInputController = this.data.getTextInputController() as HTMLDivElement | null; this.optionController = this.data.getOptionController() as HTMLDivElement | null; this.optionIcoController = this.data.getOptionIcoController() as HTMLDivElement | null; this.cutBoxSizeContainer = this.data.getCutBoxSizeContainer() as HTMLDivElement | null; // 加载截图组件 this.load(options?.triggerCallback, options?.cancelCallback); if ( this.toolController == null || this.screenShotContainer == null || this.optionIcoController == null || this.optionController == null || this.cutBoxSizeContainer == null || this.textInputController == null ) { return; } // 调整层级 if (options?.level) { this.screenShotContainer.style.zIndex = `${options.level}`; this.toolController.style.zIndex = `${options.level + 1}`; this.textInputController.style.zIndex = `${options.level + 1}`; this.optionIcoController.style.zIndex = `${options.level + 1}`; this.optionController.style.zIndex = `${options.level + 1}`; this.cutBoxSizeContainer.style.zIndex = `${options.level + 1}`; } // 创建键盘事件监听 new KeyboardEventHandle(this.screenShotContainer, this.toolController); } // 获取截图区域canvas容器 public getCanvasController(): HTMLCanvasElement | null { return this.screenShotContainer; } // 加载截图组件 private load( triggerCallback: Function | undefined, cancelCallback: Function | undefined ) { const plugInParameters = new PlugInParameters(); const canvasSize = plugInParameters.getCanvasSize(); // 设置截图区域canvas宽高 this.data.setScreenShortInfo(window.innerWidth, window.innerHeight); // 设置截图容器位置 this.data.setScreenShotPosition(this.position.left, this.position.top); // 设置截图图片存放容器宽高 this.screenShortImageController.width = window.innerWidth; this.screenShortImageController.height = window.innerHeight; // 用户有传宽高则使用用户传进来的 if (canvasSize.canvasWidth !== 0 && canvasSize.canvasHeight !== 0) { this.data.setScreenShortInfo( canvasSize.canvasWidth, canvasSize.canvasHeight ); this.screenShortImageController.width = canvasSize.canvasWidth; this.screenShortImageController.height = canvasSize.canvasHeight; } // 获取截图区域画canvas容器画布 const context = this.screenShotContainer?.getContext("2d"); if (context == null) return; // 启用webrtc截屏时则修改容器宽高 if (plugInParameters.getWebRtcStatus()) { // 设置为屏幕宽高 this.data.setScreenShortInfo(window.screen.width, window.screen.height); // 设置为屏幕宽高 this.screenShortImageController.width = window.screen.width; this.screenShortImageController.height = window.screen.height; // 用户有传宽高则使用用户传进来的 if (canvasSize.canvasWidth !== 0 && canvasSize.canvasHeight !== 0) { this.data.setScreenShortInfo( canvasSize.canvasWidth, canvasSize.canvasHeight ); this.screenShortImageController.width = canvasSize.canvasWidth; this.screenShortImageController.height = canvasSize.canvasHeight; } } // 显示截图区域容器 this.data.showScreenShortPanel(); if (!plugInParameters.getWebRtcStatus()) { // 判断用户是否自己传入截屏图片 if (this.imgSrc != null) { const imgContainer = new Image(); imgContainer.src = this.imgSrc; imgContainer.crossOrigin = "Anonymous"; imgContainer.onload = () => { // 装载截图的dom为null则退出 if (this.screenShotContainer == null) return; // 将用户传递的图片绘制到图片容器里 this.screenShortImageController .getContext("2d") ?.drawImage( imgContainer, 0, 0, this.screenShortImageController.width, this.screenShortImageController.height ); // 初始化截图容器 this.initScreenShot( triggerCallback, context, this.screenShortImageController ); }; return; } // html2canvas截屏 html2canvas(document.body, { onclone: this.loadCrossImg ? drawCrossImg : undefined }) .then(canvas => { // 装载截图的dom为null则退出 if (this.screenShotContainer == null) return; // 存储html2canvas截取的内容 this.screenShortImageController = canvas; // 初始化截图容器 this.initScreenShot(triggerCallback, context, canvas); }) .catch(err => { if (triggerCallback != null) { // 获取页面元素成功,执行回调函数 triggerCallback({ code: -1, msg: err }); } }); return; } // 截取整个屏幕 this.screenShot(cancelCallback); } // 开始捕捉屏幕 private startCapture = async (cancelCallback: Function | undefined) => { let captureStream = null; try { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore // 捕获屏幕 captureStream = await navigator.mediaDevices.getDisplayMedia(); // 将MediaStream输出至video标签 this.videoController.srcObject = captureStream; } catch (err) { if (cancelCallback != null) { cancelCallback({ code: -1, msg: "浏览器不支持webrtc或者用户未授权" }); } // 销毁截图组件 this.data.destroyDOM(); throw `浏览器不支持webrtc或者用户未授权( ${err} )`; } return captureStream; }; // 停止捕捉屏幕 private stopCapture = () => { const srcObject = this.videoController.srcObject; if (srcObject && "getTracks" in srcObject) { const tracks = srcObject.getTracks(); tracks.forEach(track => track.stop()); this.videoController.srcObject = null; } }; // 截屏 private screenShot = (cancelCallback: Function | undefined) => { // 开始捕捉屏幕 this.startCapture(cancelCallback).then(() => { setTimeout(() => { // 获取截图区域canvas容器画布 const context = this.screenShotContainer?.getContext("2d"); if (context == null || this.screenShotContainer == null) return; // 赋值截图区域canvas画布 this.screenShortCanvas = context; const plugInParameters = new PlugInParameters(); const canvasSize = plugInParameters.getCanvasSize(); let containerWidth = this.screenShortImageController?.width; let containerHeight = this.screenShortImageController?.height; // 用户有传宽高时,则使用用户的 if (canvasSize.canvasWidth !== 0 && canvasSize.canvasHeight !== 0) { containerWidth = canvasSize.canvasWidth; containerHeight = canvasSize.canvasHeight; } // 将获取到的屏幕截图绘制到图片容器里 this.screenShortImageController .getContext("2d") ?.drawImage( this.videoController, 0, 0, containerWidth, containerHeight ); // 初始化截图容器 this.initScreenShot( undefined, context, this.screenShortImageController ); // 停止捕捉屏幕 this.stopCapture(); }, 500); }); }; // 鼠标按下事件 private mouseDownEvent = (event: MouseEvent) => { // 当前操作的是撤销 if (this.data.getToolName() == "undo") return; this.data.setDragging(true); this.drawStatus = false; // 重置工具栏超出状态 this.data.setToolPositionStatus(false); this.clickFlag = true; const mouseX = nonNegativeData(event.offsetX); const mouseY = nonNegativeData(event.offsetY); // 如果当前操作的是截图工具栏 if (this.data.getToolClickStatus()) { // 记录当前鼠标开始坐标 this.drawGraphPosition.startX = mouseX; this.drawGraphPosition.startY = mouseY; } // 当前操作的是画笔 if (this.data.getToolName() == "brush" && this.screenShortCanvas) { // 初始化画笔 initPencil(this.screenShortCanvas, mouseX, mouseY); } // 当前操作的文本 if ( this.data.getToolName() == "text" && this.textInputController && this.screenShotContainer && this.screenShortCanvas ) { // 修改鼠标样式 this.screenShotContainer.style.cursor = "text"; // 显示文本输入区域 this.data.setTextStatus(true); // 判断输入框位置是否变化 if ( this.textInputPosition.mouseX != 0 && this.textInputPosition.mouseY != 0 && this.textInputPosition.mouseX != mouseX && this.textInputPosition.mouseY != mouseY ) { drawText( this.textInputController.innerText, this.textInputPosition.mouseX, this.textInputPosition.mouseY, this.data.getSelectedColor(), this.fontSize, this.screenShortCanvas ); // 输入框内容不为空时则隐藏 if (this.textInputController.innerText !== "") { // 隐藏输入框 this.data.setTextStatus(false); } // 清空文本输入区域的内容 this.textInputController.innerHTML = ""; // 保存绘制记录 this.addHistory(); } // 计算文本框显示位置, 需要加上截图容器的位置信息 const textMouseX = mouseX - 15 + this.position.left; const textMouseY = mouseY - 15 + this.position.top; // 修改文本区域位置 this.textInputController.style.left = textMouseX + "px"; this.textInputController.style.top = textMouseY + "px"; setTimeout(() => { // 获取焦点 if (this.textInputController) { this.textInputController.focus(); // 记录当前输入框位置 this.textInputPosition = { mouseX: mouseX, mouseY: mouseY }; } }); } // 如果操作的是裁剪框 if (this.borderOption) { // 设置为拖动状态 this.data.setDraggingTrim(true); // 记录移动时的起始点坐标 this.movePosition.moveStartX = mouseX; this.movePosition.moveStartY = mouseY; } else { // 保存当前裁剪框的坐标 this.drawGraphPrevX = this.drawGraphPosition.startX; this.drawGraphPrevY = this.drawGraphPosition.startY; // 绘制裁剪框,记录当前鼠标开始坐标 this.drawGraphPosition.startX = mouseX; this.drawGraphPosition.startY = mouseY; } }; // 鼠标移动事件 private mouseMoveEvent = (event: MouseEvent) => { if ( this.screenShortCanvas == null || this.screenShotContainer == null || this.data.getToolName() == "undo" ) { return; } // 工具栏未选择且鼠标处于按下状态时 if (!this.data.getToolClickStatus() && this.data.getDragging()) { // 修改拖动状态为true; this.dragFlag = true; // 隐藏截图工具栏 this.data.setToolStatus(false); // 隐藏裁剪框尺寸显示容器 this.data.setCutBoxSizeStatus(false); } this.clickFlag = false; // 获取当前绘制中的工具位置信息 const { startX, startY, width, height } = this.drawGraphPosition; // 获取当前鼠标坐标 const currentX = nonNegativeData(event.offsetX); const currentY = nonNegativeData(event.offsetY); // 绘制中工具的临时宽高 const tempWidth = currentX - startX; const tempHeight = currentY - startY; // 工具栏绘制 if (this.data.getToolClickStatus() && this.data.getDragging()) { // 获取裁剪框位置信息 const cutBoxPosition = this.data.getCutOutBoxPosition(); // 绘制中工具的起始x、y坐标不能小于裁剪框的起始坐标 // 绘制中工具的起始x、y坐标不能大于裁剪框的结束标作 // 当前鼠标的x坐标不能小于裁剪框起始x坐标,不能大于裁剪框的结束坐标 // 当前鼠标的y坐标不能小于裁剪框起始y坐标,不能大于裁剪框的结束坐标 if ( !getDrawBoundaryStatus(startX, startY, cutBoxPosition) || !getDrawBoundaryStatus(currentX, currentY, cutBoxPosition) ) return; // 当前操作的不是马赛克则显示最后一次画布绘制时的状态 if (this.data.getToolName() != "mosaicPen") { this.showLastHistory(); this.drawStatus = true; } switch (this.data.getToolName()) { case "square": drawRectangle( startX, startY, tempWidth, tempHeight, this.data.getSelectedColor(), this.data.getPenSize(), this.screenShortCanvas, this.screenShotContainer, this.screenShortImageController ); break; case "round": drawCircle( this.screenShortCanvas, currentX, currentY, startX, startY, this.data.getPenSize(), this.data.getSelectedColor() ); break; case "right-top": drawLineArrow( this.screenShortCanvas, startX, startY, currentX, currentY, 30, 10, this.data.getPenSize(), this.data.getSelectedColor() ); break; case "brush": // 画笔绘制 drawPencil( this.screenShortCanvas, currentX, currentY, this.data.getPenSize(), this.data.getSelectedColor() ); break; case "mosaicPen": // 绘制马赛克,为了确保鼠标位置在绘制区域中间,所以对x、y坐标进行-10处理 drawMosaic( currentX - 10, currentY - 10, this.data.getPenSize(), this.degreeOfBlur, this.screenShortCanvas ); break; default: break; } return; } // 执行裁剪框操作函数 this.operatingCutOutBox( currentX, currentY, startX, startY, width, height, this.screenShortCanvas ); // 如果鼠标未点击或者当前操作的是裁剪框都return if (!this.data.getDragging() || this.data.getDraggingTrim()) return; // 绘制裁剪框 this.tempGraphPosition = drawCutOutBox( startX, startY, tempWidth, tempHeight, this.screenShortCanvas, this.data.getBorderSize(), this.screenShotContainer, this.screenShortImageController ) as drawCutOutBoxReturnType; }; // 鼠标抬起事件 private mouseUpEvent = () => { // 当前操作的是撤销 if (this.data.getToolName() == "undo") return; // 绘制结束 this.data.setDragging(false); this.data.setDraggingTrim(false); // 截图容器判空 if (this.screenShortCanvas == null || this.screenShotContainer == null) { return; } // 工具栏未点击且鼠标未拖动且单击截屏状态为false则复原裁剪框位置 if ( !this.data.getToolClickStatus() && !this.dragFlag && !this.clickCutFullScreen ) { // 复原裁剪框的坐标 this.drawGraphPosition.startX = this.drawGraphPrevX; this.drawGraphPosition.startY = this.drawGraphPrevY; return; } // 调用者尚未拖拽生成选区 // 鼠标尚未拖动 // 单击截取屏幕状态为true // 则截取整个屏幕 const cutBoxPosition = this.data.getCutOutBoxPosition(); if ( cutBoxPosition.width === 0 && cutBoxPosition.height === 0 && cutBoxPosition.startX === 0 && cutBoxPosition.startY === 0 && !this.dragFlag && this.clickCutFullScreen ) { const borderSize = this.data.getBorderSize(); this.getFullScreenStatus = true; // 设置裁剪框位置为全屏 this.tempGraphPosition = drawCutOutBox( 0, 0, this.screenShotContainer.width - borderSize / 2, this.screenShotContainer.height - borderSize / 2, this.screenShortCanvas, borderSize, this.screenShotContainer, this.screenShortImageController ) as drawCutOutBoxReturnType; } if (this.screenShotContainer == null || this.screenShortCanvas == null) { return; } // 工具栏已点击且进行了绘制 if (this.data.getToolClickStatus() && this.drawStatus) { // 保存绘制记录 this.addHistory(); return; } else if (this.data.getToolClickStatus() && !this.drawStatus) { // 工具栏点击了但尚未进行绘制 return; } // 保存绘制后的图形位置信息 this.drawGraphPosition = this.tempGraphPosition; // 如果工具栏未点击则保存裁剪框位置 if (!this.data.getToolClickStatus()) { const { startX, startY, width, height } = this.drawGraphPosition; this.data.setCutOutBoxPosition(startX, startY, width, height); } // 保存边框节点信息 this.cutOutBoxBorderArr = saveBorderArrInfo( this.data.getBorderSize(), this.drawGraphPosition ); if (this.screenShotContainer != null) { // 修改鼠标状态为拖动 this.screenShotContainer.style.cursor = "move"; // 显示截图工具栏 this.data.setToolStatus(true); // 显示裁剪框尺寸显示容器 this.data.setCutBoxSizeStatus(true); // 复原拖动状态 this.dragFlag = false; if (this.toolController != null) { // 计算截图工具栏位置 const toolLocation = calculateToolLocation( this.drawGraphPosition, this.toolController.offsetWidth ); const containerHeight = this.screenShotContainer.height; // 当前截取的是全屏,则修改工具栏的位置到截图容器最底部,防止超出 if (this.getFullScreenStatus) { toolLocation.mouseY -= 64; } // 工具栏的位置超出截图容器时,调整工具栏位置防止超出 if (toolLocation.mouseY > containerHeight - 64) { toolLocation.mouseY -= this.drawGraphPosition.height + 64; // 设置工具栏超出状态为true this.data.setToolPositionStatus(true); // 隐藏裁剪框尺寸显示容器 this.data.setCutBoxSizeStatus(false); } // 显示并设置截图工具栏位置 this.data.setToolInfo( toolLocation.mouseX + this.position.left, toolLocation.mouseY + this.position.top ); // 设置裁剪框尺寸显示容器位置 this.data.setCutBoxSizePosition( this.drawGraphPosition.startX, this.drawGraphPosition.startY - 35 ); // 渲染裁剪框尺寸 this.data.setCutBoxSize( this.drawGraphPosition.width, this.drawGraphPosition.height ); // 状态重置 this.getFullScreenStatus = false; } } }; /** * 操作裁剪框 * @param currentX 裁剪框当前x轴坐标 * @param currentY 裁剪框当前y轴坐标 * @param startX 鼠标x轴坐标 * @param startY 鼠标y轴坐标 * @param width 裁剪框宽度 * @param height 裁剪框高度 * @param context 需要进行绘制的canvas画布 * @private */ private operatingCutOutBox( currentX: number, currentY: number, startX: number, startY: number, width: number, height: number, context: CanvasRenderingContext2D ) { // canvas元素不存在 if (this.screenShotContainer == null) { return; } // 获取鼠标按下时的坐标 const { moveStartX, moveStartY } = this.movePosition; // 裁剪框边框节点事件存在且裁剪框未进行操作,则对鼠标样式进行修改 if (this.cutOutBoxBorderArr.length > 0 && !this.data.getDraggingTrim()) { // 标识鼠标是否在裁剪框内 let flag = false; // 判断鼠标位置 context.beginPath(); for (let i = 0; i < this.cutOutBoxBorderArr.length; i++) { context.rect( this.cutOutBoxBorderArr[i].x, this.cutOutBoxBorderArr[i].y, this.cutOutBoxBorderArr[i].width, this.cutOutBoxBorderArr[i].height ); // 当前坐标点处于8个可操作点上,修改鼠标指针样式 if (context.isPointInPath(currentX, currentY)) { switch (this.cutOutBoxBorderArr[i].index) { case 1: if (this.data.getToolClickStatus()) { this.screenShotContainer.style.cursor = "crosshair"; } else { this.screenShotContainer.style.cursor = "move"; } break; case 2: // 工具栏被点击则不改变指针样式 if (this.data.getToolClickStatus()) break; this.screenShotContainer.style.cursor = "ns-resize"; break; case 3: if (this.data.getToolClickStatus()) break; this.screenShotContainer.style.cursor = "ew-resize"; break; case 4: if (this.data.getToolClickStatus()) break; this.screenShotContainer.style.cursor = "nwse-resize"; break; case 5: if (this.data.getToolClickStatus()) break; this.screenShotContainer.style.cursor = "nesw-resize"; break; default: break; } this.borderOption = this.cutOutBoxBorderArr[i].option; flag = true; break; } } context.closePath(); if (!flag) { // 鼠标移出裁剪框重置鼠标样式 this.screenShotContainer.style.cursor = "default"; // 重置当前操作的边框节点为null this.borderOption = null; } } // 裁剪框正在被操作 if (this.data.getDraggingTrim()) { // 当前操作节点为1时则为移动裁剪框 if (this.borderOption === 1) { // 计算要移动的x轴坐标 const x = fixedData( currentX - (moveStartX - startX), width, this.screenShotContainer.width ); // 计算要移动的y轴坐标 const y = fixedData( currentY - (moveStartY - startY), height, this.screenShotContainer.height ); // 重新绘制裁剪框 this.tempGraphPosition = drawCutOutBox( x, y, width, height, context, this.data.getBorderSize(), this.screenShotContainer as HTMLCanvasElement, this.screenShortImageController ) as drawCutOutBoxReturnType; } else { // 裁剪框其他8个点的拖拽事件 const { tempStartX, tempStartY, tempWidth, tempHeight } = zoomCutOutBoxPosition( currentX, currentY, startX, startY, width, height, this.borderOption as number ) as zoomCutOutBoxReturnType; // 绘制裁剪框 this.tempGraphPosition = drawCutOutBox( tempStartX, tempStartY, tempWidth, tempHeight, context, this.data.getBorderSize(), this.screenShotContainer as HTMLCanvasElement, this.screenShortImageController ) as drawCutOutBoxReturnType; } } } /** * 显示最新的画布状态 * @private */ private showLastHistory() { if (this.screenShortCanvas != null) { const context = this.screenShortCanvas; if (this.data.getHistory().length <= 0) { this.addHistory(); } context.putImageData( this.data.getHistory()[this.data.getHistory().length - 1]["data"], 0, 0 ); } } /** * 初始化截图容器 * @param triggerCallback * @param context * @param screenShotContainer * @private */ private initScreenShot( triggerCallback: Function | undefined, context: CanvasRenderingContext2D, screenShotContainer: HTMLCanvasElement ) { if (triggerCallback != null) { // 加载成功,执行回调函数 triggerCallback({ code: 0, msg: "截图加载完成" }); } // 赋值截图区域canvas画布 this.screenShortCanvas = context; // 存储屏幕截图 this.data.setScreenShortImageController(screenShotContainer); // 绘制蒙层 drawMasking(context, screenShotContainer); // 添加监听 this.screenShotContainer?.addEventListener( "mousedown", this.mouseDownEvent ); this.screenShotContainer?.addEventListener( "mousemove", this.mouseMoveEvent ); this.screenShotContainer?.addEventListener("mouseup", this.mouseUpEvent); } /** * 保存当前画布状态 * @private */ private addHistory() { if (this.screenShortCanvas != null && this.screenShotContainer != null) { // 获取canvas画布与容器 const context = this.screenShortCanvas; const controller = this.screenShotContainer; if (this.data.getHistory().length > this.maxUndoNum) { // 删除最早的一条画布记录 this.data.shiftHistory(); } // 保存当前画布状态 this.data.pushHistory({ data: context.getImageData(0, 0, controller.width, controller.height) }); // 启用撤销按钮 this.data.setUndoStatus(true); } } }
the_stack
import { publish, tap } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { CesiumService } from '../../../../angular-cesium/services/cesium/cesium.service'; import { MapEventsManagerService } from '../../../../angular-cesium/services/map-events-mananger/map-events-manager'; import { BehaviorSubject, Observable, Subject } from 'rxjs'; import { CesiumEvent } from '../../../../angular-cesium/services/map-events-mananger/consts/cesium-event.enum'; import { PickOptions } from '../../../../angular-cesium/services/map-events-mananger/consts/pickOptions.enum'; import { RectangleEditUpdate } from '../../../models/rectangle-edit-update'; import { EditModes } from '../../../models/edit-mode.enum'; import { EditActions } from '../../../models/edit-actions.enum'; import { DisposableObservable } from '../../../../angular-cesium/services/map-events-mananger/disposable-observable'; import { CoordinateConverter } from '../../../../angular-cesium/services/coordinate-converter/coordinate-converter.service'; import { EditPoint } from '../../../models/edit-point'; import { CameraService } from '../../../../angular-cesium/services/camera/camera.service'; import { Cartesian3 } from '../../../../angular-cesium/models/cartesian3'; import { RectanglesManagerService } from './rectangles-manager.service'; import { RectangleEditorObservable } from '../../../models/rectangle-editor-observable'; import { EditableRectangle } from '../../../models/editable-rectangle'; import { RectangleEditOptions } from '../../../models/rectangle-edit-options'; import { PointProps } from '../../../models/point-edit-options'; import { LabelProps } from '../../../models/label-props'; import { generateKey } from '../../utils'; export const DEFAULT_RECTANGLE_OPTIONS: RectangleEditOptions = { addPointEvent: CesiumEvent.LEFT_CLICK, dragPointEvent: CesiumEvent.LEFT_CLICK_DRAG, dragShapeEvent: CesiumEvent.LEFT_CLICK_DRAG, allowDrag: true, pointProps: { color: Cesium.Color.WHITE, outlineColor: Cesium.Color.BLACK.withAlpha(0.2), outlineWidth: 1, pixelSize: 13, virtualPointPixelSize: 8, show: true, showVirtual: true, disableDepthTestDistance: Number.POSITIVE_INFINITY, }, rectangleProps: { height: 0, extrudedHeight: 0, material: Cesium.Color.CORNFLOWERBLUE.withAlpha(0.4), fill: true, classificationType: Cesium.ClassificationType.BOTH, outline: true, outlineColor: Cesium.Color.WHITE, zIndex: 0, }, clampHeightTo3D: false, clampHeightTo3DOptions: { clampToTerrain: false, }, }; /** * Service for creating editable rectangles * * You must provide `RectanglesEditorService` yourself. * RectanglesEditorService works together with `<rectangles-editor>` component. Therefor you need to create `<rectangles-editor>` * for each `RectanglesEditorService`, And of course somewhere under `<ac-map>`/ * * + `create` for starting a creation of the shape over the map. Returns a extension of `RectangleEditorObservable`. * + `edit` for editing shape over the map starting from a given positions. Returns an extension of `RectangleEditorObservable`. * + To stop editing call `dsipose()` from the `RectangleEditorObservable` you get back from `create()` \ `edit()`. * * **Labels over editted shapes** * Angular Cesium allows you to draw labels over a shape that is being edited with one of the editors. * To add label drawing logic to your editor use the function `setLabelsRenderFn()` that is defined on the * `RectangleEditorObservable` that is returned from calling `create()` \ `edit()` of one of the editor services. * `setLabelsRenderFn()` - receives a callback that is called every time the shape is redrawn * (except when the shape is being dragged). The callback is called with the last shape state and with an array of the current labels. * The callback should return type `LabelProps[]`. * You can also use `updateLabels()` to pass an array of labels of type `LabelProps[]` to be drawn. * * usage: * ```typescript * // Start creating rectangle * const editing$ = rectanglesEditorService.create(); * this.editing$.subscribe(editResult => { * console.log(editResult.positions); * }); * * // Or edit rectangle from existing rectangle positions * const editing$ = this.rectanglesEditorService.edit(initialPos); * * ``` */ @Injectable() export class RectanglesEditorService { private mapEventsManager: MapEventsManagerService; private updateSubject = new Subject<RectangleEditUpdate>(); private updatePublisher = publish<RectangleEditUpdate>()(this.updateSubject); // TODO maybe not needed private coordinateConverter: CoordinateConverter; private cameraService: CameraService; private rectanglesManager: RectanglesManagerService; private observablesMap = new Map<string, DisposableObservable<any>[]>(); private cesiumScene: any; init(mapEventsManager: MapEventsManagerService, coordinateConverter: CoordinateConverter, cameraService: CameraService, rectanglesManager: RectanglesManagerService, cesiumViewer: CesiumService, ) { this.mapEventsManager = mapEventsManager; this.coordinateConverter = coordinateConverter; this.cameraService = cameraService; this.rectanglesManager = rectanglesManager; this.updatePublisher.connect(); this.cesiumScene = cesiumViewer.getScene(); } onUpdate(): Observable<RectangleEditUpdate> { return this.updatePublisher; } create(options = DEFAULT_RECTANGLE_OPTIONS, priority = 100): RectangleEditorObservable { const positions: Cartesian3[] = []; const id = generateKey(); const rectangleOptions = this.setOptions(options); const clientEditSubject = new BehaviorSubject<RectangleEditUpdate>({ id, editAction: null, editMode: EditModes.CREATE }); let finishedCreate = false; this.updateSubject.next({ id, positions, editMode: EditModes.CREATE, editAction: EditActions.INIT, rectangleOptions: rectangleOptions, }); const finishCreation = () => { const changeMode = { id, editMode: EditModes.CREATE, editAction: EditActions.CHANGE_TO_EDIT, }; this.updateSubject.next(changeMode); clientEditSubject.next(changeMode); if (this.observablesMap.has(id)) { this.observablesMap.get(id).forEach(registration => registration.dispose()); } this.observablesMap.delete(id); this.editRectangle(id, positions, priority, clientEditSubject, rectangleOptions, editorObservable); finishedCreate = true; return finishedCreate; }; const mouseMoveRegistration = this.mapEventsManager.register({ event: CesiumEvent.MOUSE_MOVE, pick: PickOptions.NO_PICK, pickConfig: options.pickConfiguration, priority, }); const addPointRegistration = this.mapEventsManager.register({ event: rectangleOptions.addPointEvent, pick: PickOptions.NO_PICK, pickConfig: options.pickConfiguration, priority, }); this.observablesMap.set(id, [mouseMoveRegistration, addPointRegistration ]); const editorObservable = this.createEditorObservable(clientEditSubject, id, finishCreation); mouseMoveRegistration.subscribe(({ movement: { endPosition } }) => { const position = this.coordinateConverter.screenToCartesian3(endPosition); if (position) { this.updateSubject.next({ id, positions: this.getPositions(id), editMode: EditModes.CREATE, updatedPosition: position, editAction: EditActions.MOUSE_MOVE, }); } }); addPointRegistration.subscribe(({ movement: { endPosition } }) => { if (finishedCreate) { return; } const position = this.coordinateConverter.screenToCartesian3(endPosition); if (!position) { return; } const allPositions = this.getPositions(id); const isFirstPoint = this.getPositions(id).length === 0; const updateValue = { id, positions: allPositions, editMode: EditModes.CREATE, updatedPosition: position, editAction: EditActions.ADD_POINT, }; this.updateSubject.next(updateValue); clientEditSubject.next({ ...updateValue, positions: this.getPositions(id), points: this.getPoints(id), }); if (!isFirstPoint) { finishedCreate = finishCreation(); } }); return editorObservable; } edit(positions: Cartesian3[], options = DEFAULT_RECTANGLE_OPTIONS, priority = 100): RectangleEditorObservable { if (positions.length !== 2) { throw new Error('Rectangles editor error edit(): rectangle should have at least 2 positions'); } const id = generateKey(); const rectangleOptions = this.setOptions(options); const editSubject = new BehaviorSubject<RectangleEditUpdate>({ id, editAction: null, editMode: EditModes.EDIT }); const update = { id, positions: positions, editMode: EditModes.EDIT, editAction: EditActions.INIT, rectangleOptions: rectangleOptions, }; this.updateSubject.next(update); editSubject.next({ ...update, positions: this.getPositions(id), points: this.getPoints(id), }); return this.editRectangle( id, positions, priority, editSubject, rectangleOptions ); } private editRectangle(id: string, positions: Cartesian3[], priority: number, editSubject: Subject<RectangleEditUpdate>, options: RectangleEditOptions, editObservable?: RectangleEditorObservable): RectangleEditorObservable { const pointDragRegistration = this.mapEventsManager.register({ event: options.dragPointEvent, entityType: EditPoint, pick: PickOptions.PICK_FIRST, pickConfig: options.pickConfiguration, priority, pickFilter: entity => id === entity.editedEntityId, }); let shapeDragRegistration; if (options.allowDrag) { shapeDragRegistration = this.mapEventsManager.register({ event: options.dragShapeEvent, entityType: EditableRectangle, pick: PickOptions.PICK_FIRST, pickConfig: options.pickConfiguration, priority, pickFilter: entity => id === entity.id, }); } pointDragRegistration.pipe( tap(({ movement: { drop } }) => this.rectanglesManager.get(id).enableEdit && this.cameraService.enableInputs(drop))) .subscribe(({ movement: { endPosition, drop }, entities }) => { const position = this.coordinateConverter.screenToCartesian3(endPosition); if (!position) { return; } const point: EditPoint = entities[0]; const update = { id, positions: this.getPositions(id), editMode: EditModes.EDIT, updatedPosition: position, updatedPoint: point, editAction: drop ? EditActions.DRAG_POINT_FINISH : EditActions.DRAG_POINT, }; this.updateSubject.next(update); editSubject.next({ ...update, positions: this.getPositions(id), points: this.getPoints(id), }); }); if (shapeDragRegistration) { shapeDragRegistration .pipe(tap(({ movement: { drop } }) => this.rectanglesManager.get(id).enableEdit && this.cameraService.enableInputs(drop))) .subscribe(({ movement: { startPosition, endPosition, drop }, entities }) => { const endDragPosition = this.coordinateConverter.screenToCartesian3(endPosition); const startDragPosition = this.coordinateConverter.screenToCartesian3(startPosition); if (!endDragPosition) { return; } const update = { id, positions: this.getPositions(id), editMode: EditModes.EDIT, updatedPosition: endDragPosition, draggedPosition: startDragPosition, editAction: drop ? EditActions.DRAG_SHAPE_FINISH : EditActions.DRAG_SHAPE, }; this.updateSubject.next(update); editSubject.next({ ...update, positions: this.getPositions(id), points: this.getPoints(id), }); }); } const observables = [pointDragRegistration]; if (shapeDragRegistration) { observables.push(shapeDragRegistration); } this.observablesMap.set(id, observables); return editObservable || this.createEditorObservable(editSubject, id); } private setOptions(options: RectangleEditOptions) { const defaultClone = JSON.parse(JSON.stringify(DEFAULT_RECTANGLE_OPTIONS)); const rectangleOptions: RectangleEditOptions = Object.assign(defaultClone, options); rectangleOptions.pointProps = Object.assign({}, DEFAULT_RECTANGLE_OPTIONS.pointProps, options.pointProps); rectangleOptions.rectangleProps = Object.assign({}, DEFAULT_RECTANGLE_OPTIONS.rectangleProps, options.rectangleProps); if (options.clampHeightTo3D) { if (!this.cesiumScene.pickPositionSupported || !this.cesiumScene.clampToHeightSupported) { throw new Error(`Cesium pickPosition and clampToHeight must be supported to use clampHeightTo3D`); } if (this.cesiumScene.pickTranslucentDepth) { console.warn(`Cesium scene.pickTranslucentDepth must be false in order to make the editors work properly on 3D`); } if (rectangleOptions.pointProps.color.alpha === 1 || rectangleOptions.pointProps.outlineColor.alpha === 1) { console.warn('Point color and outline color must have alpha in order to make the editor work properly on 3D'); } rectangleOptions.pointProps.heightReference = rectangleOptions.clampHeightTo3DOptions.clampToTerrain ? Cesium.HeightReference.CLAMP_TO_GROUND : Cesium.HeightReference.RELATIVE_TO_GROUND; rectangleOptions.pointProps.disableDepthTestDistance = Number.POSITIVE_INFINITY; } return rectangleOptions; } private createEditorObservable(observableToExtend: any, id: string, finishCreation?: () => boolean): RectangleEditorObservable { observableToExtend.dispose = () => { const observables = this.observablesMap.get(id); if (observables) { observables.forEach(obs => obs.dispose()); } this.observablesMap.delete(id); this.updateSubject.next({ id, editMode: EditModes.CREATE_OR_EDIT, editAction: EditActions.DISPOSE, }); }; observableToExtend.enable = () => { this.updateSubject.next({ id, positions: this.getPositions(id), editMode: EditModes.EDIT, editAction: EditActions.ENABLE, }); }; observableToExtend.disable = () => { this.updateSubject.next({ id, positions: this.getPositions(id), editMode: EditModes.EDIT, editAction: EditActions.DISABLE, }); }; observableToExtend.setManually = (firstPosition: Cartesian3, secondPosition: Cartesian3, firstPointProp?: PointProps, secondPointProp?: PointProps) => { const firstP = new EditPoint(id, firstPosition, firstPointProp ? firstPointProp : DEFAULT_RECTANGLE_OPTIONS.pointProps); const secP = new EditPoint(id, secondPosition, secondPointProp ? secondPointProp : DEFAULT_RECTANGLE_OPTIONS.pointProps); const rectangle = this.rectanglesManager.get(id); rectangle.setPointsManually([firstP, secP]); this.updateSubject.next({ id, editMode: EditModes.CREATE_OR_EDIT, editAction: EditActions.SET_MANUALLY, }); }; observableToExtend.setLabelsRenderFn = (callback: any) => { this.updateSubject.next({ id, editMode: EditModes.CREATE_OR_EDIT, editAction: EditActions.SET_EDIT_LABELS_RENDER_CALLBACK, labelsRenderFn: callback, }); }; observableToExtend.updateLabels = (labels: LabelProps[]) => { this.updateSubject.next({ id, editMode: EditModes.CREATE_OR_EDIT, editAction: EditActions.UPDATE_EDIT_LABELS, updateLabels: labels, }); }; observableToExtend.finishCreation = () => { if (!finishCreation) { throw new Error('Rectangles editor error edit(): cannot call finishCreation() on edit'); } return finishCreation(); }; observableToExtend.getCurrentPoints = () => this.getPoints(id); observableToExtend.getEditValue = () => observableToExtend.getValue(); observableToExtend.getLabels = (): LabelProps[] => this.rectanglesManager.get(id).labels; return observableToExtend as RectangleEditorObservable; } private getPositions(id: any) { const rectangle = this.rectanglesManager.get(id); return rectangle.getRealPositions(); } private getPoints(id: any) { const rectangle = this.rectanglesManager.get(id); return rectangle.getRealPoints(); } }
the_stack
import * as axios from "axios"; import * as prettyBytes from "pretty-bytes"; import { spawn, Thread, Worker, Pool } from "threads"; import { handleEvalScript } from "@fromjs/core"; import { writeFileSync, fstat, existsSync } from "fs"; import * as path from "path"; let instrumenterFilePath = "instrumentCode.js"; if (!existsSync(path.resolve(__dirname, instrumenterFilePath))) { // this happens in jest instrumenterFilePath = "dist/instrumentCode.js"; } function getFileKey(url, body) { const hasha = require("hasha"); const hash = hasha(body, "hex").slice(0, 8); return ( url.replace(/\//g, "_").replace(/[^a-zA-Z\-_\.0-9]/g, "") + "_" + (url.includes(":5555") ? "eval" : hash) ); } function rewriteHtml(html, { bePort, initialHtmlLogIndex }) { const originalHtml = html; // Not accurate because there could be an attribute attribute value like ">", should work // most of the time const openingBodyTag = html.match(/<body.*?>/); const openingHeadTag = html.match(/<head.*?>/); let bodyStartIndex; if (openingBodyTag) { bodyStartIndex = html.search(openingBodyTag[0]) + openingBodyTag[0].length; } let insertionIndex = 0; if (openingHeadTag) { insertionIndex = html.search(openingHeadTag[0]) + openingHeadTag[0].length; } else if (openingBodyTag) { insertionIndex = bodyStartIndex; } const insertions: any[] = []; if (openingBodyTag) { const hasScriptTagInBody = html.slice(bodyStartIndex).includes("<script"); if (!hasScriptTagInBody) { // insert script tag just so that HTML origin mapping is done const closingBodyTagIndex = html.search(/<\/body/); if (closingBodyTagIndex !== -1) { insertions.push({ index: closingBodyTagIndex, text: `<script data-fromjs-remove-before-initial-html-mapping src="http://localhost:${bePort}/fromJSInternal/empty.js"></script>`, }); } } } // Note: we don't want to have any empty text between the text, since that won't be removed // alongside the data-fromjs-remove-before-initial-html-mapping tags! var insertedHtml = `<script data-fromjs-dont-instrument data-fromjs-remove-before-initial-html-mapping>window.__fromJSInitialPageHtmlLogIndex = ${initialHtmlLogIndex};window.__fromJSInitialPageHtml = decodeURI("${encodeURI( originalHtml )}")</script>` + `<script src="http://localhost:${bePort}/jsFiles/babel-standalone.js" data-fromjs-remove-before-initial-html-mapping></script>` + `<script src="http://localhost:${bePort}/jsFiles/compileInBrowser.js" data-fromjs-remove-before-initial-html-mapping></script>`; insertions.push({ index: insertionIndex, text: insertedHtml, }); return { insertions, }; } export class RequestHandler { _shouldBlock: any; _accessToken: string; _backendPort: number; _storeLocs: any; _shouldInstrument: any; _sessionDirectory: string; _onCodeProcessed: any; _files: any; _pool: any; _backendOriginWithoutPort: string; constructor({ shouldBlock, accessToken, backendPort, storeLocs, shouldInstrument, onCodeProcessed, sessionDirectory, files, backendOriginWithoutPort, }) { this._shouldBlock = shouldBlock; this._accessToken = accessToken; this._backendPort = backendPort; this._storeLocs = storeLocs; this._shouldInstrument = shouldInstrument; // this._cache = {}; this._sessionDirectory = sessionDirectory; this._onCodeProcessed = onCodeProcessed; this._backendOriginWithoutPort = backendOriginWithoutPort; this._files = files; this._pool = Pool(() => spawn(new Worker(instrumenterFilePath)), 4); // files.forEach(f => { // ["", "?dontprocess", ".map"].forEach(postfix => { // let path = this._sessionDirectory + "/files/" + f.fileKey + postfix; // if (existsSync(path)) { // this._cache[f.url + postfix] = readFileSync(path, "utf-8"); // } // }); // }); } _cache = {}; _afterCodeProcessed({ url, fileKey, raw, instrumented, map, details }) { writeFileSync(this._sessionDirectory + "/files/" + fileKey, instrumented); writeFileSync( this._sessionDirectory + "/files/" + fileKey + "?dontprocess", raw ); writeFileSync( this._sessionDirectory + "/files/" + fileKey + ".map", JSON.stringify(map, null, 2) ); // ["", "?dontprocess", ".map"].forEach(postfix => { // let path = this._sessionDirectory + "/files/" + fileKey + postfix; // if (existsSync(path)) { // this._cache[url + postfix] = readFileSync(path, "utf-8"); // } // }); this._onCodeProcessed({ url, fileKey, details }); } async handleRequest({ url, method, headers, postData }) { if (this._shouldBlock({ url })) { return { status: 401, headers: {}, body: Buffer.from(""), fileKey: "blocked", }; } let timeLogKey = "handleRequest_" + url; console.time(timeLogKey); function logTimeEnd() { console.timeEnd(timeLogKey); } let isDontProcess = url.includes("?dontprocess"); let isMap = url.includes(".map"); url = url.replace("?dontprocess", "").replace(".map", ""); let file = this._files.find((f) => f.url == url)!; if (file) { let postfix = ""; if (isDontProcess) { postfix = "?dontprocess"; } if (isMap) { postfix = ".map"; } console.log(file); let path = this._sessionDirectory + "/files/" + file.fileKey + postfix; const ret = { body: require("fs").readFileSync(path, "utf-8"), headers: {}, status: 200, }; logTimeEnd(); return ret; } console.time("Making network request " + url); //@ts-ignore let { status, data, headers: responseHeaders } = await axios({ url, method: method, headers: headers, validateStatus: (status) => true, // prevent e.g parse json transformResponse: (data) => data, data: postData, }); console.timeEnd("Making network request " + url); const hasha = require("hasha"); const hash = hasha(data, "hex").slice(0, 8); let isJS = url.endsWith(".js"); var isHtml = !isJS && !url.endsWith(".png") && !url.endsWith(".jpg") && !url.endsWith(".woff2") && headers.Accept && headers.Accept.includes("text/html"); if (this._shouldInstrument({ url })) { if (isJS) { const { code, map, locs } = await this._requestProcessCode( data.toString(), url ); data = code; console.log("Code len", code.length); console.log("updated data", code.slice(0, 100)); } else if (isHtml) { console.log("ishtml"); let initialHtmlLogIndex = 990000000000000 + Math.round(Math.random() * 10000000000); let rawHtml = data.toString(); const { insertions } = rewriteHtml(rawHtml, { bePort: this._backendPort, initialHtmlLogIndex, }); data = await this._compileHtmlInlineScriptTags( data, initialHtmlLogIndex, insertions ); this._afterCodeProcessed({ url, fileKey: getFileKey(url, rawHtml), raw: rawHtml, instrumented: data, details: {}, map: null, }); // Remove integrity hashes, since the browser will prevent loading // the instrumented HTML otherwise data = data.replace(/ integrity="[\S]+"/g, ""); } } responseHeaders["content-length"] = data.length; logTimeEnd(); return { status, body: Buffer.from(data), headers: responseHeaders, }; } async _requestProcessCode(body, url, details = {}) { let fileKey = getFileKey(url, body); const babelPluginOptions = { accessToken: this._accessToken, backendPort: this._backendPort, backendOriginWithoutPort: this._backendOriginWithoutPort, }; console.log({ babelPluginOptions }); const RUN_IN_SAME_PROCESS = false; let r; if (RUN_IN_SAME_PROCESS) { console.log("Running compilation in proxy process for debugging"); var compile = require("./" + instrumenterFilePath); r = await compile({ body, url, babelPluginOptions }); } else { await this._pool.queue(async (compilerProcess) => { const inProgressTimeout = setTimeout(() => { console.log( "Instrumenting: " + url + " (" + prettyBytes(body.length) + ")" ); }, 5000); const response = await compilerProcess.instrument({ body, url, babelPluginOptions, }); clearTimeout(inProgressTimeout); if (response.error) { console.log("got response with error"); throw response.error; } // console.log("timeTakenMs", response.timeTakenMs); if (response.timeTakenMs > 2000) { const sizeBeforeString = prettyBytes(response.sizeBefore); const sizeAfterString = prettyBytes(response.sizeAfter); console.log( `Instrumented ${url} took ${response.timeTakenMs}ms, ${sizeBeforeString} => ${sizeAfterString}` ); } r = response; r.details = details; return r; }); // .on("message", function(response) { // console.log({ response }); // resolve(response); // compilerProcess.kill(); // clearTimeout(inProgressTimeout); // }) // .on("error", error => { // console.log("worker error", error); // clearTimeout(inProgressTimeout); // }); } this._storeLocs(r.locs); this._afterCodeProcessed({ url, fileKey, raw: body, instrumented: r.code, map: r.map, details: r.details, }); // this.cacheUrl(url, { // headers: {}, // body: instrumentedCode // }); // this.cacheUrl(url + "?dontprocess", { // headers: {}, // body: code // }); // this.cacheUrl(url + ".map", { // headers: {}, // body: map // }); return r; } async _compileHtmlInlineScriptTags(body, initialHtmlLogIndex, insertions) { // disable content security policy so worker blob can be loaded body = body.replace(/http-equiv="Content-Security-Policy"/g, ""); var MagicString = require("magic-string"); var magicHtml = new MagicString(body); const parse5 = require("parse5"); const doc = parse5.parse(body, { sourceCodeLocationInfo: true }); const walk = require("walk-parse5"); const inlineScriptTags: any[] = []; walk(doc, async (node) => { // Optionally kill traversal if (node.tagName === "script") { if ( node.attrs.find((attr) => attr.name === "data-fromjs-dont-instrument") ) { return; } const hasSrcAttribute = !!node.attrs.find( (attr) => attr.name === "src" ); const typeAttribute = node.attrs.find((attr) => attr.name === "type"); const typeIsJS = !typeAttribute || ["application/javascript", "text/javascript"].includes( typeAttribute.value ); const isInlineScriptTag = !hasSrcAttribute && typeIsJS; if (isInlineScriptTag) { inlineScriptTags.push(node); } } }); await Promise.all( inlineScriptTags.map(async (node) => { const code = node.childNodes[0].value; const compRes = <any>await this.instrumentForEval(code, { type: "scriptTag", sourceOperationLog: initialHtmlLogIndex, sourceOffset: node.childNodes[0].sourceCodeLocation.startOffset, }); node.compiledCode = compRes.instrumentedCode; }) ); console.log("has compiled"); inlineScriptTags.forEach((node) => { const textLoc = node.childNodes[0].sourceCodeLocation; magicHtml.overwrite( textLoc.startOffset, textLoc.endOffset, node.compiledCode ); }); for (const insertion of insertions) { magicHtml.appendLeft(insertion.index, insertion.text); } return magicHtml.toString(); } async processCode(body, url, details = {}) { // var cacheKey = body + url; // if (this.processCodeCache[cacheKey]) { // return Promise.resolve(this.processCodeCache[cacheKey]); // } let response = await this._requestProcessCode(body, url, details); var { code, map, locs, timeTakenMs, sizeBefore, sizeAfter } = <any>response; // console.log("req process code done", url); if (timeTakenMs > 2000) { const sizeBeforeString = prettyBytes(sizeBefore); const sizeAfterString = prettyBytes(sizeAfter); console.log( `Instrumented ${url} took ${timeTakenMs}ms, ${sizeBeforeString} => ${sizeAfterString}` ); } var result = { code, map }; // this.setProcessCodeCache(body, url, result); return result; } instrumentForEval(code, details) { return new Promise(async (resolve, reject) => { const compile = (code, url, done, details) => { this.processCode(code, url, details).then(done).catch(reject); }; handleEvalScript( code, compile, details, ({ url, instrumentedCode, code, map }) => { resolve({ instrumentedCode, }); }, (err) => { reject(err); } ); }); } }
the_stack
import { getFlow, getStep, getSteps, isApiProviderFlow, isEndStep, isStartStep, requiresInputDescribeDataShape, requiresOutputDescribeDataShape, WEBHOOK_INCOMING_ACTION_ID, WithIntegrationHelpers, } from '@syndesis/api'; import * as H from '@syndesis/history'; import { Integration, StepKind } from '@syndesis/models'; import { IntegrationEditorLayout } from '@syndesis/ui'; import { WithRouteData } from '@syndesis/utils'; import * as React from 'react'; import { PageTitle } from '../../../../../shared'; import { IEditorSidebarProps } from '../EditorSidebar'; import { DataShapeDirection, IConfigureActionRouteParams, IConfigureActionRouteState, IDescribeDataShapeRouteParams, IDescribeDataShapeRouteState, IPageWithEditorBreadcrumb, } from '../interfaces'; import { actionsFromFlow, collectErrorKeysFromActions, toUIStep, toUIStepCollection, } from '../utils'; import { IOnUpdatedIntegrationProps, WithConfigurationForm, } from './WithConfigurationForm'; export interface IConfigureActionPageProps extends IPageWithEditorBreadcrumb { backHref: ( p: IConfigureActionRouteParams, s: IConfigureActionRouteState ) => H.LocationDescriptor; cancelHref: ( p: IConfigureActionRouteParams, s: IConfigureActionRouteState ) => H.LocationDescriptor; mode: 'adding' | 'editing'; nextPageHref: ( p: IConfigureActionRouteParams, s: IConfigureActionRouteState ) => H.LocationDescriptorObject; sidebar: (props: IEditorSidebarProps) => React.ReactNode; postConfigureHref: ( requiresDataShape: boolean, integration: Integration, p: IConfigureActionRouteParams | IDescribeDataShapeRouteParams, s: IConfigureActionRouteState | IDescribeDataShapeRouteState ) => H.LocationDescriptorObject; } /** * This page shows the configuration form for a given action. * * Submitting the form will update an *existing* integration step in * the [position specified in the params]{@link IConfigureActionRouteParams#position} * of the first flow, set up as specified by the form values. * * This component expects some [url params]{@link IConfigureActionRouteParams} * and [state]{@link IConfigureActionRouteState} to be properly set in * the route object. * * **Warning:** this component will throw an exception if the route state is * undefined. */ export class ConfigureActionPage extends React.Component< IConfigureActionPageProps > { public render() { return ( <WithIntegrationHelpers> {({ addConnection, updateConnection }) => ( <WithRouteData< IConfigureActionRouteParams, IConfigureActionRouteState >> {(params, state, { history }) => { const pageAsNumber = parseInt(params.page, 10); const positionAsNumber = parseInt(params.position, 10); const oldStepConfig = getStep( state.updatedIntegration || state.integration, params.flowId, positionAsNumber ); const flow = getFlow( state.updatedIntegration || state.integration, params.flowId )!; /** * Webhooks are treated differently because the `actions` that * are used to extract `errorKeys` are located in the `connector`, * whereas they are usually in the `flow` and have be * extracted beforehand. */ const isWebHook = params.actionId === WEBHOOK_INCOMING_ACTION_ID; const getFlowActions = actionsFromFlow( flow.steps!, positionAsNumber ); const actions = isWebHook ? state.connection!.connector!.actions : getFlowActions; const errorKeys = collectErrorKeysFromActions(actions); /** * It's possible for this to be mismatched if we come into * this controller after deleting a start or end connection, * in this case we should just discard all information from * the old step. */ const useOldStepConfig = this.props.mode === 'editing' && oldStepConfig && oldStepConfig!.connection && oldStepConfig!.connection!.connectorId === state.connection.connectorId && oldStepConfig!.action && oldStepConfig!.action.id === params.actionId; /** * configured properties will be set in the route state for * configuration pages higher than 0. If it's not set, its value * depends on the mode: for `adding` there is no initial value, * for `editing` we can fetch it from the old step config object. */ const configuredProperties = state.configuredProperties || (this.props.mode === 'editing' && useOldStepConfig ? oldStepConfig!.configuredProperties : {}); /** * First, get the flow, and then check if API provider to determine * whether or not to allow the user to press back on the Configure * Action page. */ const allowBack = !isApiProviderFlow(flow!); const onUpdatedIntegration = async ({ action, moreConfigurationSteps, values, }: IOnUpdatedIntegrationProps) => { const updatedConfiguredProperties = { ...configuredProperties, ...values, }; const updatedIntegration = await (this.props.mode === 'adding' && pageAsNumber === 0 ? addConnection : updateConnection)( state.updatedIntegration || state.integration, state.connection, action, params.flowId, positionAsNumber, updatedConfiguredProperties ); if (moreConfigurationSteps) { history.push( this.props.nextPageHref( { ...params, page: `${pageAsNumber + 1}`, }, { ...state, configuredProperties: updatedConfiguredProperties, updatedIntegration, } ) ); } else { const stepKind = getStep( updatedIntegration, params.flowId, positionAsNumber ) as StepKind; const gotoDescribeData = (direction: DataShapeDirection) => { history.push( this.props.postConfigureHref( true, updatedIntegration!, { ...params, direction, }, { connection: state.connection, integration: state.integration, step: stepKind, updatedIntegration, } ) ); }; const gotoDefaultNextPage = () => { history.push( this.props.postConfigureHref( false, updatedIntegration!, params, { ...state, updatedIntegration, } ) ); }; const descriptor = stepKind.action!.descriptor!; if ( isStartStep( state.integration, params.flowId, positionAsNumber ) ) { if (requiresOutputDescribeDataShape(descriptor)) { gotoDescribeData(DataShapeDirection.OUTPUT); } else { gotoDefaultNextPage(); } } else if ( isEndStep( state.integration, params.flowId, positionAsNumber ) ) { if (requiresInputDescribeDataShape(descriptor)) { gotoDescribeData(DataShapeDirection.INPUT); } else { gotoDefaultNextPage(); } } else { if (requiresInputDescribeDataShape(descriptor)) { gotoDescribeData(DataShapeDirection.INPUT); } else if (requiresOutputDescribeDataShape(descriptor)) { gotoDescribeData(DataShapeDirection.OUTPUT); } else { gotoDefaultNextPage(); } } } }; return ( <> <PageTitle title={'Configure the action'} /> <IntegrationEditorLayout title={'Configure the action'} description={ 'Fill in the required information for the selected action.' } toolbar={this.props.getBreadcrumb( 'Configure the action', params, state )} sidebar={this.props.sidebar({ activeIndex: positionAsNumber, activeStep: { ...toUIStep(state.connection), }, steps: toUIStepCollection( getSteps(state.integration, params.flowId) ), })} content={ <WithConfigurationForm key={`${positionAsNumber}:${params.actionId}:${pageAsNumber}`} connection={state.connection} actionId={params.actionId} configurationPage={pageAsNumber} errorKeys={errorKeys} initialValue={configuredProperties} isBackAllowed={allowBack} oldAction={ useOldStepConfig && oldStepConfig!.action ? oldStepConfig!.action! : undefined } onUpdatedIntegration={onUpdatedIntegration} chooseActionHref={this.props.backHref(params, state)} /> } cancelHref={this.props.cancelHref(params, state)} /> </> ); }} </WithRouteData> )} </WithIntegrationHelpers> ); } }
the_stack
interface ThirdPartyEmbeddedContent { isThirdPartyTracking: boolean; source?: string; sourceDomain?: string; } interface AudioAtomBlockElement { _type: 'model.dotcomrendering.pageElements.AudioAtomBlockElement'; elementId: string; id: string; kicker: string; title?: string; trackUrl: string; duration: number; coverUrl: string; role?: RoleType; } interface AudioBlockElement { _type: 'model.dotcomrendering.pageElements.AudioBlockElement'; elementId: string; } interface BlockquoteBlockElement { _type: 'model.dotcomrendering.pageElements.BlockquoteBlockElement'; elementId: string; html: string; quoted?: boolean; } interface CaptionBlockElement { _type: 'model.dotcomrendering.pageElements.CaptionBlockElement'; elementId: string; captionText?: string; padCaption?: boolean; credit?: string; displayCredit?: boolean; shouldLimitWidth?: boolean; isOverlayed?: boolean; } interface CalloutBlockElement { _type: 'model.dotcomrendering.pageElements.CalloutBlockElement'; elementId: string; id: string; calloutsUrl: string; activeFrom: number; displayOnSensitive: boolean; formId: number; title: string; description: string; tagName: string; formFields: CampaignFieldType[]; role?: RoleType; } interface ChartAtomBlockElement { _type: 'model.dotcomrendering.pageElements.ChartAtomBlockElement'; elementId: string; id: string; url: string; html: string; css?: string; js?: string; role?: RoleType; placeholderUrl?: string; } interface QuizAtomBlockElement { _type: 'model.dotcomrendering.pageElements.QuizAtomBlockElement'; elementId: string; quizType: 'personality' | 'knowledge'; id: string; questions: QuestionType[]; resultBuckets: ResultBucketsType[]; resultGroups: { id: string; title: string; shareText: string; minScore: number; }[]; } interface CodeBlockElement { _type: 'model.dotcomrendering.pageElements.CodeBlockElement'; elementId: string; html: string; isMandatory: boolean; language?: string; } interface CommentBlockElement { _type: 'model.dotcomrendering.pageElements.CommentBlockElement'; elementId: string; body: string; avatarURL: string; profileURL: string; profileName: string; permalink: string; dateTime: string; role?: RoleType; } interface ContentAtomBlockElement { _type: 'model.dotcomrendering.pageElements.ContentAtomBlockElement'; elementId: string; atomId: string; } interface DisclaimerBlockElement { _type: 'model.dotcomrendering.pageElements.DisclaimerBlockElement'; elementId: string; html: string; role?: RoleType; } interface DividerBlockElement { _type: 'model.dotcomrendering.pageElements.DividerBlockElement'; size?: 'full' | 'partial'; spaceAbove?: 'tight' | 'loose'; } interface DocumentBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.DocumentBlockElement'; elementId: string; embedUrl: string; height: number; width: number; title?: string; role?: RoleType; } interface EmbedBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.EmbedBlockElement'; elementId: string; safe?: boolean; role?: RoleType; alt?: string; height?: number; width?: number; html: string; isMandatory: boolean; caption?: string; } interface ExplainerAtomBlockElement { _type: 'model.dotcomrendering.pageElements.ExplainerAtomBlockElement'; elementId: string; id: string; title: string; body: string; role?: RoleType; } interface GenericAtomBlockElement { _type: 'model.dotcomrendering.pageElements.GenericAtomBlockElement'; url: string; placeholderUrl?: string; id?: string; html?: string; css?: string; js?: string; elementId: string; } interface GuideAtomBlockElement { _type: 'model.dotcomrendering.pageElements.GuideAtomBlockElement'; elementId: string; id: string; label: string; title: string; img?: string; html: string; credit: string; role?: RoleType; } interface GuVideoBlockElement { _type: 'model.dotcomrendering.pageElements.GuVideoBlockElement'; elementId: string; assets: VideoAssets[]; caption: string; html: string; source: string; role?: RoleType; imageMedia?: { allImages: Image[] }; originalUrl?: string; url?: string; } interface HighlightBlockElement { _type: 'model.dotcomrendering.pageElements.HighlightBlockElement'; elementId: string; html: string; } interface ImageBlockElement { _type: 'model.dotcomrendering.pageElements.ImageBlockElement'; elementId: string; media: { allImages: Image[] }; data: { alt?: string; credit?: string; caption?: string; copyright?: string; }; imageSources: ImageSource[]; displayCredit?: boolean; role: RoleType; title?: string; starRating?: number; isAvatar?: boolean; } interface InstagramBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.InstagramBlockElement'; elementId: string; html: string; url: string; hasCaption: boolean; role?: RoleType; } interface InteractiveAtomBlockElement { _type: 'model.dotcomrendering.pageElements.InteractiveAtomBlockElement'; elementId: string; url: string; id: string; js?: string; html?: string; css?: string; placeholderUrl?: string; role?: RoleType; } // Can't guarantee anything in interactiveBlockElement :shrug: interface InteractiveBlockElement { _type: 'model.dotcomrendering.pageElements.InteractiveBlockElement'; elementId: string; url?: string; isMandatory?: boolean; scriptUrl?: string; alt?: string; role?: RoleType; caption?: string; } interface ItemLinkBlockElement { _type: 'model.dotcomrendering.pageElements.ItemLinkBlockElement'; elementId: string; html: string; } interface MapBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.MapBlockElement'; elementId: string; embedUrl: string; originalUrl: string; title: string; height: number; width: number; caption?: string; role?: RoleType; } interface MediaAtomBlockElement { _type: 'model.dotcomrendering.pageElements.MediaAtomBlockElement'; elementId: string; id: string; assets: VideoAssets[]; posterImage?: { url: string; width: number; }[]; title?: string; duration?: number; } interface MultiImageBlockElement { _type: 'model.dotcomrendering.pageElements.MultiImageBlockElement'; elementId: string; images: ImageBlockElement[]; caption?: string; role?: RoleType; } interface NumberedTitleBlockElement { _type: 'model.dotcomrendering.pageElements.NumberedTitleBlockElement'; elementId: string; position: number; html: string; format: CAPIFormat; } interface InteractiveContentsBlockElement { _type: 'model.dotcomrendering.pageElements.InteractiveContentsBlockElement'; elementId: string; subheadingLinks: SubheadingBlockElement[]; endDocumentElementId?: string; } interface ProfileAtomBlockElement { _type: 'model.dotcomrendering.pageElements.ProfileAtomBlockElement'; elementId: string; id: string; label: string; title: string; img?: string; html: string; credit: string; role?: RoleType; } interface PullquoteBlockElement { _type: 'model.dotcomrendering.pageElements.PullquoteBlockElement'; elementId: string; html?: string; role: string; attribution?: string; isThirdPartyTracking?: boolean; } interface QABlockElement { _type: 'model.dotcomrendering.pageElements.QABlockElement'; elementId: string; id: string; title: string; img?: string; html: string; credit: string; role?: RoleType; } interface RichLinkBlockElement { _type: 'model.dotcomrendering.pageElements.RichLinkBlockElement'; elementId: string; url: string; text: string; prefix: string; role?: Weighting; } interface SoundcloudBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.SoundcloudBlockElement'; elementId: string; html: string; id: string; isTrack: boolean; isMandatory: boolean; role?: RoleType; } interface SpotifyBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.SpotifyBlockElement'; elementId: string; embedUrl?: string; title?: string; height?: number; width?: number; caption?: string; role?: RoleType; } interface StarRatingBlockElement { _type: 'model.dotcomrendering.pageElements.StarRatingBlockElement'; elementId: string; rating: number; size: RatingSizeType; } interface SubheadingBlockElement { _type: 'model.dotcomrendering.pageElements.SubheadingBlockElement'; elementId: string; html: string; } interface TableBlockElement { _type: 'model.dotcomrendering.pageElements.TableBlockElement'; elementId: string; isMandatory: boolean; html: string; role?: RoleType; } interface TextBlockElement { _type: 'model.dotcomrendering.pageElements.TextBlockElement'; elementId: string; dropCap?: boolean; html: string; } interface TimelineBlockElement { _type: 'model.dotcomrendering.pageElements.TimelineBlockElement'; elementId: string; id: string; title: string; description?: string; events: TimelineEvent[]; role?: RoleType; } interface TweetBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.TweetBlockElement'; elementId: string; html: string; url: string; id: string; hasMedia: boolean; role?: RoleType; } interface VineBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.VineBlockElement'; elementId: string; url: string; height: number; width: number; originalUrl: string; title: string; } interface VideoBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.VideoBlockElement'; elementId: string; role?: RoleType; } interface VideoFacebookBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.VideoFacebookBlockElement'; elementId: string; url: string; height: number; width: number; caption?: string; embedUrl?: string; role?: RoleType; } interface VideoVimeoBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.VideoVimeoBlockElement'; elementId: string; embedUrl?: string; url: string; height: number; width: number; caption?: string; credit?: string; title?: string; originalUrl?: string; role?: RoleType; } interface VideoYoutubeBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.VideoYoutubeBlockElement'; elementId: string; embedUrl?: string; url: string; originalUrl: string; height: number; width: number; caption?: string; credit?: string; title?: string; role?: RoleType; } interface YoutubeBlockElement { _type: 'model.dotcomrendering.pageElements.YoutubeBlockElement'; elementId: string; assetId: string; mediaTitle: string; id: string; channelId?: string; duration?: number; posterImage?: { url: string; width: number; }[]; expired: boolean; overrideImage?: string; altText?: string; role?: RoleType; } interface WitnessTypeDataBase { authorUsername: string; authorGuardianProfileUrl: string; originalUrl: string; source: string; title: string; url: string; dateCreated: string; apiUrl: string; authorName: string; witnessEmbedType: string; html?: string; authorWitnessProfileUrl: string; } interface WitnessTypeDataImage extends WitnessTypeDataBase { _type: 'model.dotcomrendering.pageElements.WitnessTypeDataImage'; type: 'image'; alt: string; caption: string; mediaId: string; photographer: string; } interface WitnessTypeDataVideo extends WitnessTypeDataBase { _type: 'model.dotcomrendering.pageElements.WitnessTypeDataVideo'; type: 'video'; description: string; youtubeHtml: string; youtubeDescription: string; youtubeUrl: string; width: number; youtubeSource: string; youtubeAuthorName: string; height: number; youtubeTitle: string; } interface WitnessTypeDataText extends WitnessTypeDataBase { _type: 'model.dotcomrendering.pageElements.WitnessTypeDataText'; type: 'text'; description: string; authorUsername: string; originalUrl: string; source: string; title: string; url: string; dateCreated: string; apiUrl: string; authorName: string; witnessEmbedType: string; authorWitnessProfileUrl: string; } interface WitnessAssetType { type: 'Image'; mimeType: 'image/jpeg'; file: string; typeData: { name: string; }; } interface WitnessTypeBlockElement extends ThirdPartyEmbeddedContent { _type: 'model.dotcomrendering.pageElements.WitnessBlockElement'; elementId: string; assets: WitnessAssetType[]; isThirdPartyTracking: boolean; witnessTypeData: | WitnessTypeDataImage | WitnessTypeDataVideo | WitnessTypeDataText; } type CAPIElement = | AudioAtomBlockElement | AudioBlockElement | BlockquoteBlockElement | CaptionBlockElement | CalloutBlockElement | ChartAtomBlockElement | CodeBlockElement | CommentBlockElement | ContentAtomBlockElement | DisclaimerBlockElement | DividerBlockElement | DocumentBlockElement | EmbedBlockElement | ExplainerAtomBlockElement | GenericAtomBlockElement | GuideAtomBlockElement | GuVideoBlockElement | HighlightBlockElement | ImageBlockElement | InstagramBlockElement | InteractiveAtomBlockElement | InteractiveContentsBlockElement | InteractiveBlockElement | ItemLinkBlockElement | MapBlockElement | MediaAtomBlockElement | MultiImageBlockElement | NumberedTitleBlockElement | ProfileAtomBlockElement | PullquoteBlockElement | QABlockElement | QuizAtomBlockElement | RichLinkBlockElement | SoundcloudBlockElement | SpotifyBlockElement | StarRatingBlockElement | SubheadingBlockElement | TableBlockElement | TextBlockElement | TimelineBlockElement | TweetBlockElement | VideoBlockElement | VideoFacebookBlockElement | VideoVimeoBlockElement | VideoYoutubeBlockElement | VineBlockElement | YoutubeBlockElement | WitnessTypeBlockElement; // ------------------------------------- // Misc // ------------------------------------- type Weighting = | 'inline' | 'thumbnail' | 'supporting' | 'showcase' | 'halfwidth' | 'immersive' | 'richLink'; // Note, 'richLink' is used internally but does not exist upstream. // aka weighting. RoleType affects how an image is placed. It is called weighting // in Composer but role in CAPI. We respect CAPI so we maintain this nomenclature // in DCR type RoleType = | 'immersive' | 'supporting' | 'showcase' | 'inline' | 'thumbnail' | 'halfWidth'; interface ImageSource { weighting: Weighting; srcSet: SrcSetItem[]; } interface SrcSetItem { src: string; width: number; } interface Image { index: number; fields: { height: string; width: string; isMaster?: string; source?: string; caption?: string; }; mediaType: string; mimeType: string; url: string; } interface VideoAssets { url: string; mimeType: string; fields?: { source?: string; embeddable?: string; height?: string; width?: string; caption?: string; }; } interface TimelineEvent { title: string; date: string; unixDate: number; body?: string; toDate?: string; toUnixDate?: number; } interface Switches { [key: string]: boolean; } type RatingSizeType = 'large' | 'medium' | 'small'; // ------------------------------------- // Callout Campaign // ------------------------------------- type CampaignFieldType = | CampaignFieldText | CampaignFieldTextArea | CampaignFieldFile | CampaignFieldRadio | CampaignFieldCheckbox | CampaignFieldSelect; interface CampaignField { id: string; name: string; description?: string; required: boolean; textSize?: number; hideLabel: boolean; label: string; } interface CampaignFieldText extends CampaignField { type: 'text'; } interface CampaignFieldTextArea extends CampaignField { type: 'textarea'; } interface CampaignFieldFile extends CampaignField { type: 'file'; } interface CampaignFieldRadio extends CampaignField { type: 'radio'; options: { label: string; value: string; }[]; } interface CampaignFieldCheckbox extends CampaignField { type: 'checkbox'; options: { label: string; value: string; }[]; } interface CampaignFieldSelect extends CampaignField { type: 'select'; options: { label: string; value: string; }[]; } // ------------------------------------- // Quiz // ------------------------------------- type AnswerType = { id: string; text: string; revealText?: string; isCorrect: boolean; answerBuckets: string[]; }; type QuizAtomResultBucketType = { id: string; title: string; description: string; }; type QuestionType = { id: string; text: string; answers: AnswerType[]; imageUrl?: string; }; type ResultBucketsType = { id: string; title: string; description: string; };
the_stack
import { InstanceFactory } from "./instancefactory"; import { AopProxy } from "./aopproxy"; import { NoomiError } from "../tools/errorfactory"; import { TransactionManager } from "../database/transactionmanager"; import { Util } from "../tools/util"; /** * Aop通知类型 */ interface IAopAdvice{ /** * 切点 */ pointcutId?:string; /** * 实例名或实例对象 */ instance?:any; /** * 类名 */ className?:string; /** * 通知类型 (before,after,after-return,after-throw,around) */ type:string; /** * 对应的切面方法 */ method:string; } /** * Aop切面类型 */ interface IAopAspect{ /** * 实例名 */ instance?:string; /** * 切点数组 */ pointcuts:Array<AopPointcut>; /** * 通知数组 */ advices:Array<IAopAdvice>; } /** * 切点数据对象 */ interface IPointcut{ /** * 类名 */ className:string; /** * 切点id */ id:string; /** * 表达式串 */ expressions?:Array<string>; } /** * @exclude * aop文件配置对象 */ interface IAopCfg{ files:Array<string>; //引入文件 pointcuts:Array<IPointcut>; //切点集合 aspects:Array<IAopAspect>; //切面集合 } /** * aop 切点类 */ class AopPointcut{ /** * 切点id */ id:string; /** * 表达式数组(正则表达式) */ expressions:Array<RegExp> = []; /** * 通知数组 */ advices:Array<IAopAdvice> = []; /** * 构造器 * @param id 切点id(唯一) * @param expressions 该切点对应的表达式数组,表达式为正则表达式串 */ constructor(id:string,expressions:Array<string>){ this.id = id; if(expressions){ this.addExpression(expressions); } } /** * 匹配方法是否满足表达式 * @param instanceName 实例名 * @param methodName 待检测方法 * @returns 匹配返回true,否则返回false */ match(instanceName:string,methodName:string):boolean{ for(let exp of this.expressions){ if(exp.test(instanceName + '.' + methodName)){ return true; } } return false; } /** * 给切点添加通知 * @param advice 通知对象 */ addAdvice(advice:IAopAdvice):void{ this.advices.push(advice); } /** * 添加表达式串 * @param expr 表达式串或数组 */ addExpression(expr:string|string[]){ if(!Array.isArray(expr)){ expr = [expr]; } expr.forEach((item)=>{ if(typeof item !== 'string'){ throw new NoomiError("2001"); } this.expressions.push(Util.toReg(item)); }); } } /** * Aop工厂 * 用于管理所有切面、切点 */ class AopFactory{ /** * 切面map,用于存储所有切面 */ static aspects:Map<string,IAopAspect> = new Map(); /** * 切点map,用于存储所有切点 */ static pointcuts:Map<string,AopPointcut> = new Map(); /** * 已代理方法map,键为instanctName.methodName,避免重复代理 * @since 0.4.4 */ static proxyMethodMap:Map<string,boolean> = new Map(); /** * 注册切面map,键为className,值为 * { * isAspect:true, //避免用了pointcut,但是未使用Aspect注解 * pointCutId1:{expressions:Array<string>,advices:{type:类型,method:方法名}}, * ... * } */ private static registAspectMap:Map<string,any> = new Map(); /** * 注册切面 * @param className 切面类名 * @since 1.0.0 */ public static registAspect(className:string){ if(!this.registAspectMap.has(className)){ return; } this.registAspectMap.get(className).isAspect = true; } /** * 注册切点 * @param cfg pointcut配置 * @since 1.0.0 */ public static registPointcut(cfg:IPointcut){ let pc = this.getRegistPointcut(cfg.className,cfg.id,true); if(cfg.expressions){ pc.expressions = pc.expressions.concat(cfg.expressions); } } /** * 注册advice * @param cfg advice配置 * @since 1.0.0 */ public static registAdvice(cfg:IAopAdvice){ if(!this.registAspectMap.has(cfg.className)){ return; } let pc = this.registAspectMap.get(cfg.className)[cfg.pointcutId]; if(!pc){ return; } delete cfg.className; pc.advices.push(cfg); } /** * 从registAspectMap中获取注册的pointcut配置 * @param className 类名 * @param pointcutId 切点id * @param create 如果不存在,是否创建,如果为true,则创建,默认false * @returns pointcut配置项 * @since 1.0.0 */ private static getRegistPointcut(className:string,pointcutId:string,create?:boolean):any{ let pc; if(this.registAspectMap.has(className)){ let obj = this.registAspectMap.get(className); pc = obj[pointcutId]; }else if(create){ this.registAspectMap.set(className,{}); } if(!pc && create){ //新建pointcut配置项 let obj = this.registAspectMap.get(className); pc = { advices:[], expressions:[] }; obj[pointcutId] = pc; } return pc; } /** * 处理实例切面 * 把注册的切面添加到切面列表 * @param instanceName 实例名 * @param className 类名 * @since 1.0.0 */ public static handleInstanceAspect(instanceName:string,className:string){ if(!this.registAspectMap.has(className)){ return; } let cfg = this.registAspectMap.get(className); if(!cfg.isAspect){ //非aspect,不处理 return; } delete cfg.isAspect; Object.keys(cfg).forEach(item=>{ let o = cfg[item]; //新建pointcut let pc = new AopPointcut(item,o.expressions); //加入切点集 this.pointcuts.set(item,pc); //为切点添加advice o.advices.forEach(item1=>{ //设置实例或实例名 item1.instance = instanceName; //添加advice pc.addAdvice(item1); }); }); this.aspects.set(instanceName,cfg); //删除已处理的class this.registAspectMap.delete(className); } /** * 为切点添加表达式 * @param className 切点类名 * @param pointcutId 切点id * @param expression 表达式或数组 */ public static addExpression(className:string,pointcutId:string,expression:string|Array<string>){ // let pc = this.getRegistPointcut(className,pointcutId,true); let pc = this.pointcuts.get(pointcutId); if(!pc){ return; } pc.addExpression(expression); } /** * 更新aop匹配的方法代理,为所有aop匹配的方法设置代理 */ public static updMethodProxy(){ if(!this.pointcuts || this.pointcuts.size === 0){ return; } //遍历pointcut let pc:AopPointcut; for(pc of this.pointcuts.values()){ let reg:RegExp; //遍历expression for(reg of pc.expressions){ this.addProxyByExpression(reg); } } } /** * 通过正则式给方法加代理 * @param expr 表达式正则式 */ private static addProxyByExpression(expr:RegExp){ //遍历instance factory设置aop代理 let insFac = InstanceFactory.getFactory(); for(let insName of insFac.keys()){ //先检测instanceName let instance = InstanceFactory.getInstance(insName); if(instance){ Object.getOwnPropertyNames(instance.__proto__).forEach(key=>{ //给方法设置代理,constructor 不需要代理 if(key === 'constructor' || typeof(instance[key]) !== 'function'){ return; } let method:string = insName + '.' + key; //已代理过,不再代理 if(this.proxyMethodMap.has(method)){ return; } //实例名+方法符合aop正则表达式 if(expr.test(method)){ instance[key] = AopProxy.invoke(insName,key,instance[key],instance); this.proxyMethodMap.set(method,true); } }); } } } /** * 获取切点 * @param instanceName 实例名 * @param methodName 方法名 * @returns 切点数组 */ public static getPointcut(instanceName:string,methodName:string):Array<AopPointcut>{ // 遍历iterator let a:Array<AopPointcut> = []; for(let p of this.pointcuts.values()){ if(p.match(instanceName,methodName)){ a.push(p); } } return a; } /** * 根据id获取切点 * @param pointcutId 切点id * @returns 切点对象 */ public static getPointcutById(pointcutId:string):AopPointcut{ return this.pointcuts.get(pointcutId); } /** * 获取advices * @param instanceName 实例名 * @param methodName 方法名 * @return { * before:[{instance:切面实例,method:切面方法},...] * after:[{instance:切面实例,method:切面方法},...] * return:[{instance:切面实例,method:切面方法},...] * throw:[{instance:切面实例,method:切面方法},...] * } */ public static getAdvices(instanceName:string,methodName:string):object{ let pointcuts:Array<AopPointcut> = this.getPointcut(instanceName,methodName); if(pointcuts.length === 0){ return null; } let beforeArr:Array<object> = []; let afterArr:Array<object> = []; let throwArr:Array<object> = []; let returnArr:Array<object> = []; let pointcut:AopPointcut; let hasTransaction:boolean = false; for(pointcut of pointcuts){ if(pointcut.id === TransactionManager.pointcutId){ hasTransaction = true; continue; } pointcut.advices.forEach(aop=>{ let ins:any = typeof aop.instance === 'string'? InstanceFactory.getInstance(aop.instance):aop.instance; switch(aop.type){ case 'before': beforeArr.push({ instance:ins, method:aop.method }); return; case 'after': afterArr.push({ instance:ins, method:aop.method }); return; case 'around': beforeArr.push({ instance:ins, method:aop.method }); afterArr.push({ instance:ins, method:aop.method }); return; case 'after-return': returnArr.push({ instance:ins, method:aop.method }); return; case 'after-throw': throwArr.push({ instance:ins, method:aop.method }); } }); } return { hasTransaction:hasTransaction, before:beforeArr, after:afterArr, throw:throwArr, return:returnArr } } } export{AopFactory,IAopAdvice,IAopAspect,AopPointcut,IAopCfg,IPointcut};
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormAnnotation_Information { interface tab_general_Sections { account_information: DevKit.Controls.Section; attachment_information: DevKit.Controls.Section; content_information: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Unique identifier of the user who created the note. */ CreatedBy: DevKit.Controls.Lookup; /** Date and time when the note was created. */ CreatedOn: DevKit.Controls.DateTime; filenameattachment: DevKit.Controls.ActionCards; /** File size of the note. */ FileSize: DevKit.Controls.Integer; /** Specifies whether the note is an attachment. */ IsDocument: DevKit.Controls.Boolean; /** Unique identifier of the user who last modified the note. */ ModifiedBy: DevKit.Controls.Lookup; /** Date and time when the note was last modified. */ ModifiedOn: DevKit.Controls.DateTime; notetext: DevKit.Controls.ActionCards; /** Unique identifier of the user or team who owns the note. */ OwnerId: DevKit.Controls.Lookup; regardingobject: DevKit.Controls.ActionCards; } } class FormAnnotation_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Annotation_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Annotation_Information */ Body: DevKit.FormAnnotation_Information.Body; } namespace FormNote_Quick_Create_Form { interface tab_general_Sections { notes_information: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Text of the note. */ NoteText: DevKit.Controls.String; /** Subject associated with the note. */ Subject: DevKit.Controls.String; } } class FormNote_Quick_Create_Form extends DevKit.IForm { /** * DynamicsCrm.DevKit form Note_Quick_Create_Form * @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 Note_Quick_Create_Form */ Body: DevKit.FormNote_Quick_Create_Form.Body; } class AnnotationApi { /** * DynamicsCrm.DevKit AnnotationApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the note. */ AnnotationId: DevKit.WebApi.GuidValue; /** Unique identifier of the user who created the note. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the note was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the annotation. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Contents of the note's attachment. */ DocumentBody: DevKit.WebApi.StringValue; /** File name of the note. */ FileName: DevKit.WebApi.StringValue; /** File pointer of the attachment. */ FilePointer: DevKit.WebApi.StringValueReadonly; /** File size of the note. */ FileSize: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Specifies whether the note is an attachment. */ IsDocument: DevKit.WebApi.BooleanValue; IsPrivate: DevKit.WebApi.BooleanValueReadonly; /** Language identifier for the note. */ LangId: DevKit.WebApi.StringValue; /** MIME type of the note's attachment. */ MimeType: DevKit.WebApi.StringValue; /** Unique identifier of the user who last modified the note. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the note was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the annotation. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Text of the note. */ NoteText: DevKit.WebApi.StringValue; /** Unique identifier of the object with which the note is associated. */ objectid_account: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_appointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_bookableresource: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_bookableresourcebooking: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_bookableresourcebookingheader: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_bookableresourcecategoryassn: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_bookableresourcecharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_bookableresourcegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_bulkoperation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_calendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_campaign: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_campaignactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_campaignresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ channelaccessprofile_annotations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ channelaccessprofileruleid: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_profileruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_commitment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_competitor: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_contract: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_contractdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_convertrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_duplicaterule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_email: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_emailserverprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_entitlement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_entitlementchannel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_entitlementtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_equipment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_goal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_incident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_incidentresolution: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_invoice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_kbarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_lead: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_letter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_list: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_mailbox: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_3dmodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_accountpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_actual: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementbookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementbookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_agreementsubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_aimodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_aiodimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_approval: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_bookingalertstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_bookingjournal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_bookingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_characteristicreqforteammember: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_contactpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_customerasset: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_dataexport: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_delegation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_estimate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_estimateline: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_expense: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_expensecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_expensereceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_fact: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_fieldservicesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_findworkevent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_incidenttype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_incidenttypeservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_incidenttypessetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_inspectionattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_inventoryjournal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_inventorytransfer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_invoicelinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_iotalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_iotdevice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_iotdevicecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_iotdevicecommand: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_journal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_journalline: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_liveconversation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_opportunitylineresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_opportunitylinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_opportunitylinetransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_opportunitylinetransactionclassificatio: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_opportunitypricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_orderlineresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_orderlinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_orderlinetransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_orderlinetransactionclassification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_orderpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_organizationalunit: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_payment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_paymentdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_paymentmethod: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_paymentterm: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_personalsoundsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_playbookinstance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_playbooktemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_postalbum: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_postalcode: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_priority: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_processnotes: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_productinventory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_project: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projectapproval: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projectparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projectparameterpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projectpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projecttask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projecttaskdependency: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projecttaskstatususer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projectteam: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projectteammembersignup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_projecttransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_purchaseorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_purchaseorderbill: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotebookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotebookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotebookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotelineresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotelinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotelinetransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotelinetransactionclassification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_quotepricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_requirementcharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_requirementresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_requirementresourcepreference: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_requirementstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_resourcecategorypricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_resourcepaytype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_resourcerequest: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_resourcerequirement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_resourcerequirementdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_resourceterritory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rma: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rmaproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rmareceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rmasubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rolecompetencyrequirement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rtv: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rtvproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_rtvsubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_servicetasktype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_shipvia: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_soundfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_soundnotificationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_taxcode: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_taxcodedetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_timeentry: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_timegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_timegroupdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_timeoffrequest: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transactioncategoryclassification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transactioncategoryhierarchyelement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transactioncategorypricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transactionconnection: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transactionorigin: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transactiontype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_transcript: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_warehouse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workhourtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workordercharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workorderincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workorderservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workorderservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_workordersubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_agentscriptaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_answer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_configuration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_customizationfiles: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_entityassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_entitysearch: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_form: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_languagemodule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_scriptlet: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_scripttasktrigger: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_search: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_sessioninformation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_toolbarbutton: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_toolbarstrip: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_tracesourcesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_uiievent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyusd_windowroute: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msfp_alert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msfp_question: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msfp_surveyresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_opportunity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_orderclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_phonecall: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_product: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_quote: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_quoteclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_resourcespec: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_routingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_routingruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_salesorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_service: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_sharepointdocument: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_sla: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_socialactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_uii_action: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_uii_hostedapplication: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_uii_nonhostedapplication: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_uii_option: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_uii_workflow: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_uii_workflowstep: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_uii_workflow_workflowstep_mapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_workflow: DevKit.WebApi.LookupValue; /** 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 of the business unit that owns the note. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the note. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the note. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Prefix of the file pointer in blob storage. */ Prefix: DevKit.WebApi.StringValueReadonly; /** workflow step id associated with the note. */ StepId: DevKit.WebApi.StringValue; /** Storage pointer. */ StoragePointer: DevKit.WebApi.StringValueReadonly; /** Subject associated with the note. */ Subject: DevKit.WebApi.StringValue; /** Version number of the note. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Annotation { enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information','Quick Create Form'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Attribute, ButtonElement, CanvasElement, DataListElement, Element, FieldSetElement, FormElement, FormFieldElement, FormValue, HrefElement, InputElement, KeygenElement, LabelElement, LegendElement, LinkElement, MapElement, MediaElement, MeterElement, NodeType, ObjectElement, OptionElement, OutputElement, ProgressElement, ScriptElement, SelectElement, Selection, StyleElement, TableCellElement, TableColElement, TableElement, TableRowElement, TableSectionElement, TextAreaElement, TitleElement, parseHTML, } from 'k6/html'; const handler = (index: number, element: Element) => {}; const tester = (index: number, element: Element) => true; const mapper = (index: number, element: Element) => null; let selection: Selection; let derived: Selection; let selections: Selection[]; let element: Element; let possibleElement: Element | undefined; let elements: Element[]; let formValues: FormValue[]; let attribute: Attribute; let possibleAttribute: Attribute | undefined; let attributesMap: { [name: string]: Attribute }; let possibleType: NodeType | undefined; let possibleForm: FormElement | undefined; let labels: LabelElement[]; let options: OptionElement[]; let cells: TableCellElement[]; // parseHTML parseHTML(); // $ExpectError parseHTML(5); // $ExpectError selection = parseHTML('<html></html>'); parseHTML('<html></html>', 5); // $ExpectError // Selection selection = parseHTML('<html></html>'); selection.attr('name'); // $ExpectType string | undefined derived = selection.children('.item'); derived = selection.closest('li'); derived = selection.contents(); selection.data('email'); // $ExpectType string | undefined selection.each(handler); // $ExpectType void derived = selection.eq(7); derived = selection.filter('.item'); derived = selection.filter(tester); derived = selection.filter(selection); derived = selection.find('.item'); derived = selection.first(); element = selection.get(7); derived = selection.has('.item'); selection.html(); // $ExpectType string | undefined selection.is('.item'); // $ExpectType boolean selection.is(tester); // $ExpectType boolean selection.is(selection); // $ExpectType boolean derived = selection.last(); selection.map(mapper); // $ExpectType unknown[] derived = selection.next('span'); derived = selection.nextAll('span'); derived = selection.nextUntil('span'); derived = selection.not('.item'); derived = selection.not(tester); derived = selection.parent('.item'); derived = selection.parents('.item'); derived = selection.parentsUntil('.item'); derived = selection.prev('.item'); derived = selection.prevAll('.item'); derived = selection.prevUntil('.item'); selection.serialize(); // $ExpectType string formValues = selection.serializeArray(); selection.serializeObject(); // $ExpectType { [name: string]: string; } selection.size(); // $ExpectType number derived = selection.slice(0); derived = selection.slice(7, 9); selection.text(); // $ExpectType string selections = selection.toArray(); selection.val(); // $ExpectType string | undefined // Attribute declare function makeAttribute(): Attribute; attribute = makeAttribute(); attribute.name; // $ExpectType string element = attribute.ownerElement; attribute.value; // $ExpectType string attribute.localName(); // $ExpectType string attribute.namespaceURI(); // $ExpectType string attribute.prefix(); // $ExpectType string // Element declare function makeElement(): Element; element = makeElement(); attributesMap = element.attributes(); element.childElementCount(); // $ExpectType number elements = element.childNodes(); elements = element.children(); element.classList(); // $ExpectType string[] element.className(); // $ExpectType string | undefined element.contains(element); // $ExpectType boolean possibleElement = element.firstChild(); possibleElement = element.firstElementChild(); element.getAttribute('name'); // $ExpectType string | undefined possibleAttribute = element.getAttributeNode('name'); elements = element.getElementsByClassName('item'); elements = element.getElementsByTagName('li'); element.hasAttribute('name'); // $ExpectType boolean element.hasAttributes(); // $ExpectType boolean element.hasChildNodes(); // $ExpectType boolean element.id(); // $ExpectType string element.innerHTML(); // $ExpectType string | undefined element.isDefaultNamespace(); // $ExpectType boolean element.isEqualNode(element); // $ExpectType boolean element.isSameNode(element); // $ExpectType boolean element.lang(); // $ExpectType string | undefined possibleElement = element.lastChild(); element.matches('.item'); // $ExepctType boolean element.namespaceURI(); // $ExpectType string possibleElement = element.nextElementSibling(); possibleElement = element.nextSibling(); element.nodeName(); // $ExpectType string possibleType = element.nodeType(); element.nodeValue(); // $ExpectType string | undefined possibleElement = element.ownerDocument(); possibleElement = element.parentElement(); possibleElement = element.parentNode(); possibleElement = element.previousElementSibling(); possibleElement = element.previousSibling(); possibleElement = element.querySelector('.item'); elements = element.querySelectorAll('.item'); element.textContent(); // $ExpectType string element.toString(); // $ExpectType string // ButtonElement declare function makeButtonElement(): ButtonElement; const button: ButtonElement = makeButtonElement(); button.value(); // $ExpectType string // CanvasElement declare function makeCanvasElement(): CanvasElement; const canvas: CanvasElement = makeCanvasElement(); canvas.height(); // $ExpectType number canvas.width(); // $ExpectType number // DataListElement declare function makeDataListElement(): DataListElement; const dataList: DataListElement = makeDataListElement(); options = dataList.options(); // FieldSetElement declare function makeFieldSetElement(): FieldSetElement; const fieldSet: FieldSetElement = makeFieldSetElement(); elements = fieldSet.elements(); possibleForm = fieldSet.form(); fieldSet.type(); // $ExpectType string fieldSet.validity(); // $ExpectType undefined // FormElement declare function makeFormElement(): FormElement; const form: FormElement = makeFormElement(); elements = form.elements(); form.length(); // $ExpectType number form.method(); // $ExpectType string // FormFieldElement declare function makeFormFieldElement(): FormFieldElement; const field: FormFieldElement = makeFormFieldElement(); possibleForm = field.form(); field.formAction(); // $ExpectType string field.formEnctype(); // $ExpectType string field.formMethod(); // $ExpectType string field.formNoValidate(); // $ExpectType boolean field.formTarget(); // $ExpectType string labels = field.labels(); field.name(); // $ExpectType string // HrefElement declare function makeHrefElement(): HrefElement; const href: HrefElement = makeHrefElement(); href.hash(); // $ExpectType string href.host(); // $ExpectType string href.hostname(); // $ExpectType string href.origin(); // $ExpectType string href.password(); // $ExpectType string href.pathname(); // $ExpectType string href.port(); // $ExpectType string href.protocol(); // $ExpectType string href.relList(); // $ExpectType string[] href.search(); // $ExpectType string href.text(); // $ExpectType string href.username(); // $ExpectType string // InputElement declare function makeInputElement(): InputElement; const input: InputElement = makeInputElement(); possibleForm = input.form(); // KeygenElement declare function makeKeygenElement(): KeygenElement; const keygen: KeygenElement = makeKeygenElement(); possibleForm = keygen.form(); labels = keygen.labels(); // LabelElement declare function makeLabelElement(): LabelElement; const label: LabelElement = makeLabelElement(); possibleElement = label.control(); possibleForm = label.form(); // LegendElement declare function makeLegendElement(): LegendElement; const legend: LegendElement = makeLegendElement(); possibleForm = legend.form(); // LinkElement declare function makeLinkElement(): LinkElement; const link: LinkElement = makeLinkElement(); link.relList(); // $ExpectType string[] // MapElement declare function makeMapElement(): MapElement; const map: MapElement = makeMapElement(); elements = map.areas(); elements = map.images(); // MediaElement declare function makeMediaElement(): MediaElement; const media: MediaElement = makeMediaElement(); elements = media.textTracks(); // MeterElement declare function makeMeterElement(): MeterElement; const meter: MeterElement = makeMeterElement(); labels = meter.labels(); // ObjectElement declare function makeObjectElement(): ObjectElement; const object: ObjectElement = makeObjectElement(); possibleForm = object.form(); // OptionElement declare function makeOptionElement(): OptionElement; const option: OptionElement = makeOptionElement(); option.disabled(); // $ExpectType boolean possibleForm = option.form(); option.index(); // $ExpectType number option.label(); // $ExpectType string option.text(); // $ExpectType string option.value(); // $ExpectType string // OutputElement declare function makeOutputElement(): OutputElement; const output: OutputElement = makeOutputElement(); output.defaultValue(); // $ExpectValue string possibleForm = output.form(); labels = output.labels(); output.value(); // $ExpectType string // ProgressElement declare function makeProgressElement(): ProgressElement; const progress: ProgressElement = makeProgressElement(); labels = progress.labels(); progress.max(); // $ExpectType number progress.position(); // $ExpectType number progress.value(); // $ExpectType number // ScriptElement declare function makeScriptElement(): ScriptElement; const script: ScriptElement = makeScriptElement(); script.text(); // $ExpectType string // SelectElement declare function makeSelectElement(): SelectElement; const select: SelectElement = makeSelectElement(); possibleForm = select.form(); labels = select.labels(); select.length(); // $ExpectType number options = select.options(); select.selectedIndex(); // $ExpectType number options = select.selectedOptions(); select.size(); // $ExpectType number select.type(); // $ExpectType string select.value(); // $ExpectType string // StyleElement declare function makeStyleElement(): StyleElement; const style: StyleElement = makeStyleElement(); style.type(); // $ExpectType string // TableCellElement declare function makeTableCellElement(): TableCellElement; const cell: TableCellElement = makeTableCellElement(); cell.cellIndex(); // $ExpectType number // TableColElement declare function makeTableColElement(): TableColElement; const col: TableColElement = makeTableColElement(); col.span(); // $ExpectType number // TableElement declare function makeTableElement(): TableElement; const table: TableElement = makeTableElement(); possibleElement = table.caption(); elements = table.rows(); elements = table.tBodies(); possibleElement = table.tFoot(); possibleElement = table.tHead(); // TableRowElement declare function makeTableRowElement(): TableRowElement; const row: TableRowElement = makeTableRowElement(); cells = row.cells(); row.rowIndex(); // $ExpectType number row.sectionRowIndex(); // $ExpectType number // TableSectionElement declare function makeTableSectionElement(): TableSectionElement; const section: TableSectionElement = makeTableSectionElement(); elements = section.rows(); // TextAreaElement declare function makeTextAreaElement(): TextAreaElement; const textArea: TextAreaElement = makeTextAreaElement(); possibleForm = textArea.form(); labels = textArea.labels(); textArea.length(); // $ExpectType number // TitleElement declare function makeTitleElement(): TitleElement; const title: TitleElement = makeTitleElement(); title.text(); // $ExpectType string
the_stack
import { join } from 'path' import { readFileSync, statSync } from 'fs' import matter from 'gray-matter' import dateFns from 'date-fns' import _ from 'lodash' import pathToRegexp from 'path-to-regexp' import yaml from 'js-yaml' import { slugify, logger } from '../utils' // import { logger } from '../utils' import { Nuxtent } from '../../types' import Anchor from 'markdown-it-anchor' import Token from 'markdown-it/lib/token' const permalinkCompiler = pathToRegexp.compile /** * Creates a slug * @param {string} fileName The file name * @returns {string} the slugified string */ const getSlug = (fileName: string): string => { const onlyName = fileName .replace(/(\.comp)?(\.[0-9a-z]+)$/, '') // remove any ext .replace(/!?(\d{4}-\d{2}-\d{2}-)/, '') // remove date and hypen return slugify(onlyName).toLowerCase() } /** * Converts the date of the post into object * @param {string} date The date * @returns {{year: string, month: string, day: string}} The date object */ const splitDate = ( date: string ): { year: string; month: string; day: string } => { const [year, month, day] = date.split('-') return { day, month, year, } } declare interface IPrivateFileMeta extends Nuxtent.Database.FileMeta { filePath: string } const isDev = process.env.NODE_ENV !== 'production' export default class Page { /** * Gets the meta but hides the file path */ get meta(): Nuxtent.Database.FileMeta { const cleanedMeta = Object.assign({}, this.__meta) // Never expose the filePath delete cleanedMeta.filePath return cleanedMeta } /** * Gets the path of the file */ get path() { // If there is no page defined in the configuration return the permalink if (!this.config.page) { return this.permalink } // If is dev or isn't cached make it if (isDev || !this.cached.path) { const nestedPath = /([^_][a-zA-z]*?)\/[^a-z_]*/ const matchedPath = this.config.page.match(nestedPath) if (matchedPath && matchedPath[1] !== 'index') { this.cached.path = join(matchedPath[1], this.permalink).replace( /\\|\/\//, '/' ) } else { this.cached.path = this.permalink.replace(/\\|\/\//, '/') } } return this.cached.path } /** * Gets the valid permalink for this page */ get permalink() { if (isDev || !this.cached.permalink) { const date = this.date.toString() const { section, fileName } = this.meta const slug = getSlug(fileName) const { year, month, day } = splitDate(date) const params = { section, slug, date, year, month, day } const toPermalink = permalinkCompiler(this.config.permalink) let permalink = join( '/', toPermalink(params).replace(/%2F/gi, '/') // make url encoded slash pretty ) // Handle permalinks for subdirectory indexes if (permalink.length > 6 && permalink.substr(-6) === '/index') { permalink = permalink.substr(0, permalink.length - 6) } this.cached.permalink = permalink.replace(/\\|\\\\/g, '/') } return this.cached.permalink } /** * Gets all the attributes */ get attributes() { if (typeof this.config.data === 'object') { return { ...this._rawData.attributes, ...this.config.data } } return this._rawData.attributes } /** * Gets the body contents for the object */ get body(): Nuxtent.Page.Body { if ( isDev || this.cached.body === null || (typeof this.cached.body === 'string' && this.cached.body.length === 0) || (typeof this.cached.body === 'object' && !this.cached.body.relativePath) ) { const { dirName, section, fileName, filePath } = this.__meta if (fileName.search(/\.comp\.md$/) > -1) { let relativePath = '.' + join(dirName, section, fileName) relativePath = relativePath.replace(/\\/, '/') // normalize windows path if (!relativePath) { logger.error('Path not found for ' + this._rawData.fileName) } this.cached.body = { content: this._rawData.body.content, relativePath, // component body compiled by loader and imported separately } } else if (fileName.search(/\.md$/) > -1) { if (this.config.markdown.plugins.toc) { // Inject callback in markdown-it-anchor plugin const tocPlugin = this.config.markdown.plugins .toc as Nuxtent.Config.MarkdownItPluginArray tocPlugin[1].callback = this.tocParserCallback } // markdown to html if (this.config.markdown.parser) { if (!this._rawData.body.content) { logger.warn(`Empty content on ${this.path}`) } this.cached.body = this.config.markdown.parser.render( this._rawData.body.content || '' ) } else { logger.error(`The ${this.config.permalink} markdown config is wrong`) } } else if (fileName.endsWith('.html')) { this.cached.body = this._rawData.body.content || '' } else if (fileName.search(/\.(yaml|yml)$/) > -1) { const source = readFileSync(filePath).toString() const body = yaml.load(source) this.cached.body = body } else { logger.error('This file is not supported ' + this.__meta.fileName) } } if (this.cached.body === null) { throw new Error('Unexpected result on get body') } return this.cached.body } get date() { if (isDev || !this.cached.date) { const { filePath, fileName, section } = this.__meta if (this.config.isPost) { const fileDate = fileName.match(/!?(\d{4}-\d{2}-\d{2})/) // YYYY-MM-DD if (!fileDate) { throw new Error( `File "${fileName}" on ${section} Needs a date in YYYY-MM-DD-filename.md!` ) } this.cached.date = fileDate[0] } else { const stats = statSync(filePath) this.cached.date = dateFns.format(stats.ctime, 'YYYY-MM-DD') } } return this.cached.date } get _rawData(): Nuxtent.Page.RawData { if (isDev || !this.cached.data.fileName) { const source = readFileSync(this.__meta.filePath).toString() const fileName = this.__meta.fileName this.cached.data.fileName = fileName if (fileName.search(/\.(md|html)$/) !== -1) { // { data: attributes, content: body } = matter(source) const result = matter(source, { excerpt: !!this.config.excerpt, }) this.cached.data.attributes = result.data if (!!this.config.excerpt) { this.cached.data.attributes.excerpt = fileName.endsWith('md') && this.config.markdown.parser && result.excerpt ? this.config.markdown.parser.render(result.excerpt) : result.excerpt } this.cached.data.body.content = result.content } else if (fileName.search(/\.(yaml|yml)$/) !== -1) { this.cached.data.body.content = yaml.load(source) } else if (fileName.endsWith('.json')) { this.cached.data.body.content = JSON.parse(source) } else { logger.warn(`The file ${fileName} is not compatible with nuxtent`) } } return this.cached.data } set toc(entry: Nuxtent.Page.PageToc | null) { if (!this.config.toc || !entry) { return } if (typeof this.cached.toc === 'undefined') { this.cached.toc = {} } if (typeof this.cached.toc[this.permalink] === 'undefined') { this.cached.toc[this.permalink] = { items: {}, slug: entry.slug, topLevel: Infinity, } } if ( !entry.slug || typeof this.cached.toc[this.permalink].items[entry.slug] !== 'undefined' ) { return } const tocEntry = { level: entry.tag ? parseInt(entry.tag.substr(1), 10) : 1, link: '#' + entry.slug, title: entry.title, } if (tocEntry.level < this.cached.toc[this.permalink].topLevel) { this.cached.toc[this.permalink].topLevel = tocEntry.level } if ( typeof this.cached.toc[this.permalink].items[entry.slug] === 'undefined' ) { this.cached.toc[this.permalink].items[entry.slug] = tocEntry } } get toc(): Nuxtent.Page.PageToc | null { if (!this.config.toc || !this.cached.toc) { return null } return this.cached.toc[this.permalink] } private cached: Nuxtent.Page.PageData = { attributes: {}, body: null, data: { attributes: {}, body: {}, }, date: null, path: null, permalink: null, } private __meta: IPrivateFileMeta private config: Nuxtent.Config.Content private propsSet: Set<Nuxtent.Page.PageProp | string> = new Set([ 'meta', 'date', 'path', 'permalink', 'breadcrumbs', 'attributes', 'body', ]) get breadcrumbs() { if (Array.isArray(this.cached.breadcrumbs)) { return this.cached.breadcrumbs } return [] } set breadcrumbs(crumbs: Nuxtent.Page.Breadcrumbs[]) { this.cached.breadcrumbs = crumbs } /** * Creates an instance of Page. * @param meta The metadata for the page file * @param contentConfig The content configuration * * @memberOf Page */ constructor(meta: IPrivateFileMeta, contentConfig: Nuxtent.Config.Content) { this.__meta = meta this.config = contentConfig if (contentConfig.toc !== false) { this.propsSet.add('toc') } } /** * @description Creates an instance of the page * * @param [params={}] Params * @param [params.exclude] The props exclution list * @returns {Object} The page content * * @memberOf Page */ public create(params: Nuxtent.Query): Nuxtent.Page.PublicPage { const excludes = params.exclude || [] const props = Array.from(this.propsSet) excludes.forEach(prop => { if (props.includes(prop)) { props.splice(props.indexOf(prop), 1) } }) const data: Nuxtent.Page.PublicPage = { attributes: {}, body: '', date: null, path: null, permalink: '', } props.forEach(prop => { if (prop === 'attributes') { Object.assign(data, this[prop]) // @ts-ignore } else if (this[prop] !== undefined) { // @ts-ignore data[prop] = this[prop] } }) return data } /** * @description Callback for the toc * * @param token The token object from markdownIt * @param token.attrs The attributes for the token ej. class * @param token.tag The tag for the token * @param info Title and slug * @param info.title The title text of the anchor * @param info.slug The slug for the anchor * @returns {void} * * @memberOf Page */ private tocParserCallback(token: Token, info: Anchor.AnchorInfo) { let addToToc = true if (typeof token.attrs !== 'undefined') { const classValue = token.attrGet('class') if (classValue && classValue.includes('notoc')) { addToToc = true } } if (addToToc) { this.toc = { items: {}, slug: info.slug, tag: token.tag, title: info.title, topLevel: 0, } } } }
the_stack
import { FetchFn } from '.'; import { Matcher } from '../types'; import { labelMatchersToString } from '../parser'; import LRUCache from 'lru-cache'; export interface MetricMetadata { type: string; help: string; } export interface PrometheusClient { labelNames(metricName?: string): Promise<string[]>; // labelValues return a list of the value associated to the given labelName. // In case a metric is provided, then the list of values is then associated to the couple <MetricName, LabelName> labelValues(labelName: string, metricName?: string, matchers?: Matcher[]): Promise<string[]>; metricMetadata(): Promise<Record<string, MetricMetadata[]>>; series(metricName: string, matchers?: Matcher[], labelName?: string): Promise<Map<string, string>[]>; // metricNames returns a list of suggestions for the metric name given the `prefix`. // Note that the returned list can be a superset of those suggestions for the prefix (i.e., including ones without the // prefix), as codemirror will filter these out when displaying suggestions to the user. metricNames(prefix?: string): Promise<string[]>; } export interface CacheConfig { // maxAge is the maximum amount of time that a cached completion item is valid before it needs to be refreshed. // It is in milliseconds. Default value: 300 000 (5min) maxAge?: number; // the cache can be initialized with a list of metrics initialMetricList?: string[]; } export interface PrometheusConfig { url: string; lookbackInterval?: number; // eslint-disable-next-line @typescript-eslint/no-explicit-any httpErrorHandler?: (error: any) => void; fetchFn?: FetchFn; // cache will allow user to change the configuration of the cached Prometheus client (which is used by default) cache?: CacheConfig; httpMethod?: 'POST' | 'GET'; apiPrefix?: string; } interface APIResponse<T> { status: 'success' | 'error'; data?: T; error?: string; warnings?: string[]; } // These are status codes where the Prometheus API still returns a valid JSON body, // with an error encoded within the JSON. const badRequest = 400; const unprocessableEntity = 422; const serviceUnavailable = 503; // HTTPPrometheusClient is the HTTP client that should be used to get some information from the different endpoint provided by prometheus. export class HTTPPrometheusClient implements PrometheusClient { private readonly lookbackInterval = 60 * 60 * 1000 * 12; //12 hours private readonly url: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any private readonly errorHandler?: (error: any) => void; private readonly httpMethod: 'POST' | 'GET' = 'POST'; private readonly apiPrefix: string = '/api/v1'; // For some reason, just assigning via "= fetch" here does not end up executing fetch correctly // when calling it, thus the indirection via another function wrapper. private readonly fetchFn: FetchFn = (input: RequestInfo, init?: RequestInit): Promise<Response> => fetch(input, init); constructor(config: PrometheusConfig) { this.url = config.url; this.errorHandler = config.httpErrorHandler; if (config.lookbackInterval) { this.lookbackInterval = config.lookbackInterval; } if (config.fetchFn) { this.fetchFn = config.fetchFn; } if (config.httpMethod) { this.httpMethod = config.httpMethod; } if (config.apiPrefix) { this.apiPrefix = config.apiPrefix; } } labelNames(metricName?: string): Promise<string[]> { const end = new Date(); const start = new Date(end.getTime() - this.lookbackInterval); if (metricName === undefined || metricName === '') { const request = this.buildRequest( this.labelsEndpoint(), new URLSearchParams({ start: start.toISOString(), end: end.toISOString(), }) ); // See https://prometheus.io/docs/prometheus/latest/querying/api/#getting-label-names return this.fetchAPI<string[]>(request.uri, { method: this.httpMethod, body: request.body, }).catch((error) => { if (this.errorHandler) { this.errorHandler(error); } return []; }); } return this.series(metricName).then((series) => { const labelNames = new Set<string>(); for (const labelSet of series) { for (const [key] of Object.entries(labelSet)) { if (key === '__name__') { continue; } labelNames.add(key); } } return Array.from(labelNames); }); } // labelValues return a list of the value associated to the given labelName. // In case a metric is provided, then the list of values is then associated to the couple <MetricName, LabelName> labelValues(labelName: string, metricName?: string, matchers?: Matcher[]): Promise<string[]> { const end = new Date(); const start = new Date(end.getTime() - this.lookbackInterval); if (!metricName || metricName.length === 0) { const params: URLSearchParams = new URLSearchParams({ start: start.toISOString(), end: end.toISOString(), }); // See https://prometheus.io/docs/prometheus/latest/querying/api/#querying-label-values return this.fetchAPI<string[]>(`${this.labelValuesEndpoint().replace(/:name/gi, labelName)}?${params}`).catch((error) => { if (this.errorHandler) { this.errorHandler(error); } return []; }); } return this.series(metricName, matchers, labelName).then((series) => { const labelValues = new Set<string>(); for (const labelSet of series) { for (const [key, value] of Object.entries(labelSet)) { if (key === '__name__') { continue; } if (key === labelName) { labelValues.add(value); } } } return Array.from(labelValues); }); } metricMetadata(): Promise<Record<string, MetricMetadata[]>> { return this.fetchAPI<Record<string, MetricMetadata[]>>(this.metricMetadataEndpoint()).catch((error) => { if (this.errorHandler) { this.errorHandler(error); } return {}; }); } series(metricName: string, matchers?: Matcher[], labelName?: string): Promise<Map<string, string>[]> { const end = new Date(); const start = new Date(end.getTime() - this.lookbackInterval); const request = this.buildRequest( this.seriesEndpoint(), new URLSearchParams({ start: start.toISOString(), end: end.toISOString(), 'match[]': labelMatchersToString(metricName, matchers, labelName), }) ); // See https://prometheus.io/docs/prometheus/latest/querying/api/#finding-series-by-label-matchers return this.fetchAPI<Map<string, string>[]>(request.uri, { method: this.httpMethod, body: request.body, }).catch((error) => { if (this.errorHandler) { this.errorHandler(error); } return []; }); } metricNames(): Promise<string[]> { return this.labelValues('__name__'); } private fetchAPI<T>(resource: string, init?: RequestInit): Promise<T> { return this.fetchFn(this.url + resource, init) .then((res) => { if (!res.ok && ![badRequest, unprocessableEntity, serviceUnavailable].includes(res.status)) { throw new Error(res.statusText); } return res; }) .then((res) => res.json()) .then((apiRes: APIResponse<T>) => { if (apiRes.status === 'error') { throw new Error(apiRes.error !== undefined ? apiRes.error : 'missing "error" field in response JSON'); } if (apiRes.data === undefined) { throw new Error('missing "data" field in response JSON'); } return apiRes.data; }); } private buildRequest(endpoint: string, params: URLSearchParams) { let uri = endpoint; let body: URLSearchParams | null = params; if (this.httpMethod === 'GET') { uri = `${uri}?${params}`; body = null; } return { uri, body }; } private labelsEndpoint(): string { return `${this.apiPrefix}/labels`; } private labelValuesEndpoint(): string { return `${this.apiPrefix}/label/:name/values`; } private seriesEndpoint(): string { return `${this.apiPrefix}/series`; } private metricMetadataEndpoint(): string { return `${this.apiPrefix}/metadata`; } } class Cache { // completeAssociation is the association between a metric name, a label name and the possible label values private readonly completeAssociation: LRUCache<string, Map<string, Set<string>>>; // metricMetadata is the association between a metric name and the associated metadata private metricMetadata: Record<string, MetricMetadata[]>; private labelValues: LRUCache<string, string[]>; private labelNames: string[]; constructor(config?: CacheConfig) { const maxAge = config && config.maxAge ? config.maxAge : 5 * 60 * 1000; this.completeAssociation = new LRUCache<string, Map<string, Set<string>>>(maxAge); this.metricMetadata = {}; this.labelValues = new LRUCache<string, string[]>(maxAge); this.labelNames = []; if (config?.initialMetricList) { this.setLabelValues('__name__', config.initialMetricList); } } setAssociations(metricName: string, series: Map<string, string>[]): void { series.forEach((labelSet: Map<string, string>) => { let currentAssociation = this.completeAssociation.get(metricName); if (!currentAssociation) { currentAssociation = new Map<string, Set<string>>(); this.completeAssociation.set(metricName, currentAssociation); } for (const [key, value] of Object.entries(labelSet)) { if (key === '__name__') { continue; } const labelValues = currentAssociation.get(key); if (labelValues === undefined) { currentAssociation.set(key, new Set<string>([value])); } else { labelValues.add(value); } } }); } setMetricMetadata(metadata: Record<string, MetricMetadata[]>): void { this.metricMetadata = metadata; } getMetricMetadata(): Record<string, MetricMetadata[]> { return this.metricMetadata; } setLabelNames(labelNames: string[]): void { this.labelNames = labelNames; } getLabelNames(metricName?: string): string[] { if (!metricName || metricName.length === 0) { return this.labelNames; } const labelSet = this.completeAssociation.get(metricName); return labelSet ? Array.from(labelSet.keys()) : []; } setLabelValues(labelName: string, labelValues: string[]): void { this.labelValues.set(labelName, labelValues); } getLabelValues(labelName: string, metricName?: string): string[] { if (!metricName || metricName.length === 0) { const result = this.labelValues.get(labelName); return result ? result : []; } const labelSet = this.completeAssociation.get(metricName); if (labelSet) { const labelValues = labelSet.get(labelName); return labelValues ? Array.from(labelValues) : []; } return []; } } export class CachedPrometheusClient implements PrometheusClient { private readonly cache: Cache; private readonly client: PrometheusClient; constructor(client: PrometheusClient, config?: CacheConfig) { this.client = client; this.cache = new Cache(config); } labelNames(metricName?: string): Promise<string[]> { const cachedLabel = this.cache.getLabelNames(metricName); if (cachedLabel && cachedLabel.length > 0) { return Promise.resolve(cachedLabel); } if (metricName === undefined || metricName === '') { return this.client.labelNames().then((labelNames) => { this.cache.setLabelNames(labelNames); return labelNames; }); } return this.series(metricName).then(() => { return this.cache.getLabelNames(metricName); }); } labelValues(labelName: string, metricName?: string): Promise<string[]> { const cachedLabel = this.cache.getLabelValues(labelName, metricName); if (cachedLabel && cachedLabel.length > 0) { return Promise.resolve(cachedLabel); } if (metricName === undefined || metricName === '') { return this.client.labelValues(labelName).then((labelValues) => { this.cache.setLabelValues(labelName, labelValues); return labelValues; }); } return this.series(metricName).then(() => { return this.cache.getLabelValues(labelName, metricName); }); } metricMetadata(): Promise<Record<string, MetricMetadata[]>> { const cachedMetadata = this.cache.getMetricMetadata(); if (cachedMetadata && Object.keys(cachedMetadata).length > 0) { return Promise.resolve(cachedMetadata); } return this.client.metricMetadata().then((metadata) => { this.cache.setMetricMetadata(metadata); return this.cache.getMetricMetadata(); }); } series(metricName: string): Promise<Map<string, string>[]> { return this.client.series(metricName).then((series) => { this.cache.setAssociations(metricName, series); return series; }); } metricNames(): Promise<string[]> { return this.labelValues('__name__'); } }
the_stack
import { commands, window, WorkspaceFolder, workspace, Uri, debug, DebugConfiguration, DebugSessionOptions, env, ConfigurationTarget, } from "vscode"; import { join, dirname } from "path"; import { logError, OUTPUT_CHANNEL } from "./channel"; import * as roboCommands from "./robocorpCommands"; import * as vscode from "vscode"; import * as pythonExtIntegration from "./pythonExtIntegration"; import { QuickPickItemWithAction, sortCaptions, QuickPickItemRobotTask, showSelectOneQuickPick, showSelectOneStrQuickPick, } from "./ask"; import { refreshCloudTreeView } from "./views"; import { feedback } from "./rcc"; export async function cloudLogin(): Promise<boolean> { let loggedIn: boolean; do { let credentials: string = await window.showInputBox({ "password": true, "prompt": "Please provide the access credentials - Confirm without entering any text to open https://cloud.robocorp.com/settings/access-credentials where credentials may be obtained - ", "ignoreFocusOut": true, }); if (credentials == undefined) { return false; } if (!credentials) { env.openExternal(Uri.parse("https://cloud.robocorp.com/settings/access-credentials")); continue; } let commandResult: ActionResult<any> = await commands.executeCommand( roboCommands.ROBOCORP_CLOUD_LOGIN_INTERNAL, { "credentials": credentials, } ); if (!commandResult) { loggedIn = false; } else { loggedIn = commandResult.success; } if (!loggedIn) { let retry = "Retry with new credentials"; let selectedItem = await window.showWarningMessage( "Unable to log in with the provided credentials.", { "modal": true }, retry ); if (!selectedItem) { return false; } } } while (!loggedIn); return true; } export async function cloudLogout(): Promise<void> { let loggedOut: ActionResult<boolean>; let isLoginNeededActionResult: ActionResult<boolean> = await commands.executeCommand( roboCommands.ROBOCORP_IS_LOGIN_NEEDED_INTERNAL ); if (!isLoginNeededActionResult) { window.showInformationMessage("Error getting information if already linked in."); return; } if (isLoginNeededActionResult.result) { window.showInformationMessage( "Unable to unlink and remove credentials from Control Room. Current Control Room credentials are not valid." ); refreshCloudTreeView(); return; } let YES = "Unlink"; const result = await window.showWarningMessage( `Are you sure you want to unlink and remove credentials from Control Room?`, { "modal": true }, YES ); if (result !== YES) { return; } loggedOut = await commands.executeCommand(roboCommands.ROBOCORP_CLOUD_LOGOUT_INTERNAL); if (!loggedOut) { window.showInformationMessage("Error unlinking and removing Control Room credentials."); return; } if (!loggedOut.success) { window.showInformationMessage("Unable to unlink and remove Control Room credentials."); return; } window.showInformationMessage("Control Room credentials successfully unlinked and removed."); } /** * Note that callers need to check both whether it was successful as well as if the interpreter was resolved. */ export async function resolveInterpreter(targetRobot: string): Promise<ActionResult<InterpreterInfo | undefined>> { // Note: this may also activate robotframework-lsp if it's still not activated // (so, it cannot be used during startup as there'd be a cyclic dependency). try { let interpreter: InterpreterInfo | undefined = await commands.executeCommand( "robot.resolveInterpreter", targetRobot ); return { "success": true, "message": "", "result": interpreter }; } catch (error) { // We couldn't resolve with the robotframework language server command, fallback to the robocorp code command. try { let result: ActionResult<InterpreterInfo | undefined> = await commands.executeCommand( roboCommands.ROBOCORP_RESOLVE_INTERPRETER, { "target_robot": targetRobot, } ); return result; } catch (error) { logError("Error resolving interpreter.", error); return { "success": false, "message": "Unable to resolve interpreter.", "result": undefined }; } } } export async function listAndAskRobotSelection( selectionMessage: string, noRobotErrorMessage: string ): Promise<LocalRobotMetadataInfo> { let actionResult: ActionResult<LocalRobotMetadataInfo[]> = await commands.executeCommand( roboCommands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL ); if (!actionResult.success) { window.showInformationMessage("Error listing robots: " + actionResult.message); return; } let robotsInfo: LocalRobotMetadataInfo[] = actionResult.result; if (!robotsInfo || robotsInfo.length == 0) { window.showInformationMessage(noRobotErrorMessage); return; } let robot: LocalRobotMetadataInfo = await askRobotSelection(robotsInfo, selectionMessage); if (!robot) { return; } return robot; } export async function askRobotSelection( robotsInfo: LocalRobotMetadataInfo[], message: string ): Promise<LocalRobotMetadataInfo> { let robot: LocalRobotMetadataInfo; if (robotsInfo.length > 1) { let captions: QuickPickItemWithAction[] = new Array(); for (let i = 0; i < robotsInfo.length; i++) { const element: LocalRobotMetadataInfo = robotsInfo[i]; let caption: QuickPickItemWithAction = { "label": element.name, "description": element.directory, "action": element, }; captions.push(caption); } let selectedItem: QuickPickItemWithAction = await showSelectOneQuickPick(captions, message); if (!selectedItem) { return; } robot = selectedItem.action; } else { robot = robotsInfo[0]; } return robot; } async function askAndCreateNewRobotAtWorkspace(wsInfo: WorkspaceInfo, directory: string) { let robotName: string = await window.showInputBox({ "prompt": "Please provide the name for the new Robot.", "ignoreFocusOut": true, }); if (!robotName) { return; } let actionResult: ActionResult<any> = await commands.executeCommand( roboCommands.ROBOCORP_UPLOAD_TO_NEW_ROBOT_INTERNAL, { "workspaceId": wsInfo.workspaceId, "directory": directory, "robotName": robotName, } ); if (!actionResult.success) { let msg: string = "Error uploading to new Robot: " + actionResult.message; OUTPUT_CHANNEL.appendLine(msg); window.showErrorMessage(msg); } else { window.showInformationMessage("Successfully submitted new Robot " + robotName + " to the Control Room."); } } export async function setPythonInterpreterFromRobotYaml() { let actionResult: ActionResult<LocalRobotMetadataInfo[]> = await commands.executeCommand( roboCommands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL ); if (!actionResult.success) { window.showInformationMessage("Error listing existing robots: " + actionResult.message); return; } let robotsInfo: LocalRobotMetadataInfo[] = actionResult.result; if (!robotsInfo || robotsInfo.length == 0) { window.showInformationMessage( "Unable to set Python extension interpreter (no Robot detected in the Workspace)." ); return; } let robot: LocalRobotMetadataInfo = await askRobotSelection( robotsInfo, "Please select the Robot from which the python executable should be used." ); if (!robot) { return; } try { let result: ActionResult<InterpreterInfo | undefined> = await resolveInterpreter(robot.filePath); if (!result.success) { window.showWarningMessage("Error resolving interpreter info: " + result.message); return; } let interpreter: InterpreterInfo = result.result; if (!interpreter || !interpreter.pythonExe) { window.showWarningMessage("Unable to obtain interpreter information from: " + robot.filePath); return; } // Note: if we got here we have a robot in the workspace. let selectedItem = await showSelectOneStrQuickPick( ["Workspace Settings", "Global Settings"], "Please select where the python.pythonPath configuration should be set." ); if (!selectedItem) { return; } let configurationTarget: ConfigurationTarget = undefined; if (selectedItem == "Global Settings") { configurationTarget = ConfigurationTarget.Global; } else if (selectedItem == "Workspace Settings") { configurationTarget = ConfigurationTarget.Workspace; } else { window.showWarningMessage("Invalid configuration target: " + selectedItem); return; } OUTPUT_CHANNEL.appendLine( "Setting the python executable path for vscode-python to be:\n" + interpreter.pythonExe ); let config = workspace.getConfiguration("python"); await config.update("pythonPath", interpreter.pythonExe, configurationTarget); let resource = Uri.file(dirname(robot.filePath)); let pythonExecutableConfigured = await pythonExtIntegration.getPythonExecutable(resource); if (pythonExecutableConfigured == "config") { window.showInformationMessage("Successfully set python executable path for vscode-python."); } else if (!pythonExecutableConfigured) { window.showInformationMessage( "Unable to verify if vscode-python executable was properly set. See OUTPUT -> Robocorp Code for more info." ); } else { if (pythonExecutableConfigured != interpreter.pythonExe) { let opt1 = "Copy python path to clipboard and call vscode-python command to set interpreter"; let opt2 = "Open more info/instructions to opt-out of the pythonDeprecadePythonPath experiment"; let selectedItem = await window.showQuickPick([opt1, opt2, "Cancel"], { "canPickMany": false, "placeHolder": "Unable to set the interpreter (due to pythonDeprecatePythonPath experiment). How to proceed?", "ignoreFocusOut": true, }); if (selectedItem == opt1) { await vscode.env.clipboard.writeText(interpreter.pythonExe); let result = await window.showInformationMessage( 'Copied python executable path to the clipboard. Press OK to proceed and then paste the path after choosing the option to "Enter interpreter path..."', "OK", "Cancel" ); if (result == "OK") { await commands.executeCommand("python.setInterpreter"); } } else if (selectedItem == opt2) { env.openExternal( Uri.parse( "https://github.com/microsoft/vscode-python/wiki/AB-Experiments#pythondeprecatepythonpath" ) ); } } else { window.showInformationMessage("Successfully set python executable path for vscode-python."); } } } catch (error) { logError("Error setting python.pythonPath configuration.", error); window.showWarningMessage("Error setting python.pythonPath configuration: " + error.message); return; } } export async function rccConfigurationDiagnostics() { let actionResult: ActionResult<LocalRobotMetadataInfo[]> = await commands.executeCommand( roboCommands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL ); if (!actionResult.success) { window.showInformationMessage("Error listing robots: " + actionResult.message); return; } let robotsInfo: LocalRobotMetadataInfo[] = actionResult.result; if (!robotsInfo || robotsInfo.length == 0) { window.showInformationMessage( "No Robot detected in the Workspace. If a robot.yaml is available, open it for more information." ); return; } let robot = await askRobotSelection(robotsInfo, "Please select the Robot to analyze."); if (!robot) { return; } let diagnosticsActionResult: ActionResult<string> = await commands.executeCommand( roboCommands.ROBOCORP_CONFIGURATION_DIAGNOSTICS_INTERNAL, { "robotYaml": robot.filePath } ); if (!diagnosticsActionResult.success) { window.showErrorMessage("Error computing diagnostics for Robot: " + diagnosticsActionResult.message); return; } OUTPUT_CHANNEL.appendLine(diagnosticsActionResult.result); workspace.openTextDocument({ "content": diagnosticsActionResult.result }).then((document) => { window.showTextDocument(document); }); } export async function uploadRobot(robot?: LocalRobotMetadataInfo) { // Start this in parallel while we ask the user for info. let isLoginNeededPromise: Thenable<ActionResult<boolean>> = commands.executeCommand( roboCommands.ROBOCORP_IS_LOGIN_NEEDED_INTERNAL ); let currentUri: Uri; if (window.activeTextEditor && window.activeTextEditor.document) { currentUri = window.activeTextEditor.document.uri; } let actionResult: ActionResult<LocalRobotMetadataInfo[]> = await commands.executeCommand( roboCommands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL ); if (!actionResult.success) { window.showInformationMessage("Error submitting Robot to the Control Room: " + actionResult.message); return; } let robotsInfo: LocalRobotMetadataInfo[] = actionResult.result; if (!robotsInfo || robotsInfo.length == 0) { window.showInformationMessage( "Unable to submit Robot to the Control Room (no Robot detected in the Workspace)." ); return; } let isLoginNeededActionResult: ActionResult<boolean> = await isLoginNeededPromise; if (!isLoginNeededActionResult) { window.showInformationMessage("Error getting if login is needed."); return; } if (isLoginNeededActionResult.result) { let loggedIn: boolean = await cloudLogin(); if (!loggedIn) { return; } } if (!robot) { robot = await askRobotSelection(robotsInfo, "Please select the Robot to upload to the Control Room."); if (!robot) { return; } } let refresh = false; SELECT_OR_REFRESH: do { // We ask for the information on the existing workspaces information. // Note that this may be cached from the last time it was asked, // so, we have an option to refresh it (and ask again). let actionResult: ListWorkspacesActionResult = await commands.executeCommand( roboCommands.ROBOCORP_CLOUD_LIST_WORKSPACES_INTERNAL, { "refresh": refresh } ); if (!actionResult.success) { window.showErrorMessage("Error listing Control Room workspaces: " + actionResult.message); return; } let workspaceInfo: WorkspaceInfo[] = actionResult.result; if (!workspaceInfo || workspaceInfo.length == 0) { window.showErrorMessage("A Control Room Workspace must be created to submit a Robot to the Control Room."); return; } // Now, if there are only a few items or a single workspace, // just show it all, otherwise do a pre-selectedItem with the workspace. let workspaceIdFilter: string = undefined; if (workspaceInfo.length > 1) { // Ok, there are many workspaces, let's provide a pre-filter for it. let captions: QuickPickItemWithAction[] = new Array(); for (let i = 0; i < workspaceInfo.length; i++) { const wsInfo: WorkspaceInfo = workspaceInfo[i]; let caption: QuickPickItemWithAction = { "label": "$(folder) " + wsInfo.workspaceName, "action": { "filterWorkspaceId": wsInfo.workspaceId }, }; captions.push(caption); } sortCaptions(captions); let caption: QuickPickItemWithAction = { "label": "$(refresh) * Refresh list", "description": "Expected Workspace is not appearing.", "sortKey": "09999", // last item "action": { "refresh": true }, }; captions.push(caption); let selectedItem: QuickPickItemWithAction = await showSelectOneQuickPick( captions, "Please select Workspace to upload: " + robot.name + " (" + robot.directory + ")" + "." ); if (!selectedItem) { return; } if (selectedItem.action.refresh) { refresh = true; continue SELECT_OR_REFRESH; } else { workspaceIdFilter = selectedItem.action.filterWorkspaceId; } } // ------------------------------------------------------- // Select Robot/New Robot/Refresh // ------------------------------------------------------- let captions: QuickPickItemWithAction[] = new Array(); for (let i = 0; i < workspaceInfo.length; i++) { const wsInfo: WorkspaceInfo = workspaceInfo[i]; if (workspaceIdFilter) { if (workspaceIdFilter != wsInfo.workspaceId) { continue; } } for (let j = 0; j < wsInfo.packages.length; j++) { const robotInfo = wsInfo.packages[j]; // i.e.: Show the Robots with the same name with more priority in the list. let sortKey = "b" + robotInfo.name; if (robotInfo.name == robot.name) { sortKey = "a" + robotInfo.name; } let caption: QuickPickItemWithAction = { "label": "$(file) " + robotInfo.name, "description": "(Workspace: " + wsInfo.workspaceName + ")", "sortKey": sortKey, "action": { "existingRobotPackage": robotInfo }, }; captions.push(caption); } let caption: QuickPickItemWithAction = { "label": "$(new-folder) + Create new Robot", "description": "(Workspace: " + wsInfo.workspaceName + ")", "sortKey": "c" + wsInfo.workspaceName, // right before last item. "action": { "newRobotPackageAtWorkspace": wsInfo }, }; captions.push(caption); } let caption: QuickPickItemWithAction = { "label": "$(refresh) * Refresh list", "description": "Expected Workspace or Robot is not appearing.", "sortKey": "d", // last item "action": { "refresh": true }, }; captions.push(caption); sortCaptions(captions); let selectedItem: QuickPickItemWithAction = await showSelectOneQuickPick( captions, "Please select target Robot to upload: " + robot.name + " (" + robot.directory + ")." ); if (!selectedItem) { return; } let action = selectedItem.action; if (action.refresh) { refresh = true; continue SELECT_OR_REFRESH; } if (action.newRobotPackageAtWorkspace) { // No confirmation in this case let wsInfo: WorkspaceInfo = action.newRobotPackageAtWorkspace; await askAndCreateNewRobotAtWorkspace(wsInfo, robot.directory); return; } if (action.existingRobotPackage) { let yesOverride: string = "Yes (override existing Robot)"; let noChooseDifferentTarget: string = "No (choose different target)"; let cancel: string = "Cancel"; let robotInfo: PackageInfo = action.existingRobotPackage; let selectedItem = await window.showWarningMessage( "Upload of the contents of " + robot.directory + " to: " + robotInfo.name + " (" + robotInfo.workspaceName + ")", ...[yesOverride, noChooseDifferentTarget, cancel] ); // robot.language-server.python if (selectedItem == noChooseDifferentTarget) { refresh = false; continue SELECT_OR_REFRESH; } if (selectedItem == cancel) { return; } // selectedItem == yesOverride. let actionResult: ActionResult<any> = await commands.executeCommand( roboCommands.ROBOCORP_UPLOAD_TO_EXISTING_ROBOT_INTERNAL, { "workspaceId": robotInfo.workspaceId, "robotId": robotInfo.id, "directory": robot.directory } ); if (!actionResult.success) { let msg: string = "Error uploading to existing Robot: " + actionResult.message; OUTPUT_CHANNEL.appendLine(msg); window.showErrorMessage(msg); } else { window.showInformationMessage("Successfully submitted Robot " + robot.name + " to the cloud."); } return; } } while (true); } export async function askAndRunRobotRCC(noDebug: boolean) { let textEditor = window.activeTextEditor; let fileName: string | undefined = undefined; if (textEditor) { fileName = textEditor.document.fileName; } const RUN_IN_RCC_LRU_CACHE_NAME = "RUN_IN_RCC_LRU_CACHE"; let runLRU: string[] = await commands.executeCommand(roboCommands.ROBOCORP_LOAD_FROM_DISK_LRU, { "name": RUN_IN_RCC_LRU_CACHE_NAME, }); let actionResult: ActionResult<LocalRobotMetadataInfo[]> = await commands.executeCommand( roboCommands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL ); if (!actionResult.success) { window.showErrorMessage("Error listing Robots: " + actionResult.message); return; } let robotsInfo: LocalRobotMetadataInfo[] = actionResult.result; if (!robotsInfo || robotsInfo.length == 0) { window.showInformationMessage("Unable to run Robot (no Robot detected in the Workspace)."); return; } let items: QuickPickItemRobotTask[] = new Array(); for (let robotInfo of robotsInfo) { let yamlContents = robotInfo.yamlContents; let tasks = yamlContents["tasks"]; if (tasks) { let taskNames: string[] = Object.keys(tasks); for (let taskName of taskNames) { let keyInLRU: string = robotInfo.name + " - " + taskName + " - " + robotInfo.filePath; let item: QuickPickItemRobotTask = { "label": "Run robot: " + robotInfo.name + " Task: " + taskName, "description": robotInfo.filePath, "robotYaml": robotInfo.filePath, "taskName": taskName, "keyInLRU": keyInLRU, }; if (runLRU && runLRU.length > 0 && keyInLRU == runLRU[0]) { // Note that although we have an LRU we just consider the last one for now. items.splice(0, 0, item); } else { items.push(item); } } } } if (!items) { window.showInformationMessage("Unable to run Robot (no Robot detected in the Workspace)."); return; } let selectedItem: QuickPickItemRobotTask; if (items.length == 1) { selectedItem = items[0]; } else { selectedItem = await window.showQuickPick(items, { "canPickMany": false, "placeHolder": "Please select the Robot and Task to run.", "ignoreFocusOut": true, }); } if (!selectedItem) { return; } await commands.executeCommand(roboCommands.ROBOCORP_SAVE_IN_DISK_LRU, { "name": RUN_IN_RCC_LRU_CACHE_NAME, "entry": selectedItem.keyInLRU, "lru_size": 3, }); runRobotRCC(noDebug, selectedItem.robotYaml, selectedItem.taskName); } export async function runRobotRCC(noDebug: boolean, robotYaml: string, taskName: string) { let debugConfiguration: DebugConfiguration = { "name": "Config", "type": "robocorp-code", "request": "launch", "robot": robotYaml, "task": taskName, "args": [], "noDebug": noDebug, }; let debugSessionOptions: DebugSessionOptions = {}; debug.startDebugging(undefined, debugConfiguration, debugSessionOptions); } export async function createRobot() { // Unfortunately vscode does not have a good way to request multiple inputs at once, // so, for now we're asking each at a separate step. let actionResult: ActionResult<RobotTemplate[]> = await commands.executeCommand( roboCommands.ROBOCORP_LIST_ROBOT_TEMPLATES_INTERNAL ); if (!actionResult.success) { window.showErrorMessage("Unable to list Robot templates: " + actionResult.message); return; } let availableTemplates: RobotTemplate[] = actionResult.result; if (availableTemplates) { let wsFolders: ReadonlyArray<WorkspaceFolder> = workspace.workspaceFolders; if (!wsFolders) { window.showErrorMessage("Unable to create Robot (no workspace folder is currently opened)."); return; } let selectedItem = await window.showQuickPick( availableTemplates.map((robotTemplate) => robotTemplate.description), { "canPickMany": false, "placeHolder": "Please select the template for the Robot.", "ignoreFocusOut": true, } ); const selectedRobotTemplate = availableTemplates.find( (robotTemplate) => robotTemplate.description === selectedItem ); OUTPUT_CHANNEL.appendLine("Selected: " + selectedRobotTemplate?.description); let ws: WorkspaceFolder; if (!selectedRobotTemplate) { // Operation cancelled. return; } if (wsFolders.length == 1) { ws = wsFolders[0]; } else { ws = await window.showWorkspaceFolderPick({ "placeHolder": "Please select the folder to create the Robot.", "ignoreFocusOut": true, }); } if (!ws) { // Operation cancelled. return; } let name: string = await window.showInputBox({ "value": "Example", "prompt": "Please provide the name for the Robot folder name.", "ignoreFocusOut": true, }); if (!name) { // Operation cancelled. return; } OUTPUT_CHANNEL.appendLine("Creating Robot at: " + ws.uri.fsPath); let createRobotResult: ActionResult<any> = await commands.executeCommand( roboCommands.ROBOCORP_CREATE_ROBOT_INTERNAL, { "directory": ws.uri.fsPath, "template": selectedRobotTemplate.name, "name": name } ); if (createRobotResult.success) { try { commands.executeCommand("workbench.files.action.refreshFilesExplorer"); } catch (error) { logError("Error refreshing file explorer.", error); } window.showInformationMessage("Robot successfully created in:\n" + join(ws.uri.fsPath, name)); } else { OUTPUT_CHANNEL.appendLine("Error creating Robot at: " + +ws.uri.fsPath); window.showErrorMessage(createRobotResult.message); } } } export async function updateLaunchEnvironment(args): Promise<{ [key: string]: string } | "cancelled"> { let robot = args["targetRobot"]; let environment: { [key: string]: string } = args["env"]; if (!robot) { throw new Error("robot argument is required."); } if (environment === undefined) { throw new Error("env argument is required."); } let condaPrefix = environment["CONDA_PREFIX"]; if (!condaPrefix) { OUTPUT_CHANNEL.appendLine( "Unable to update launch environment for work items because CONDA_PREFIX is not available in the environment:\n" + JSON.stringify(environment) ); return environment; } let work_items_action_result: ActionResultWorkItems = await commands.executeCommand( roboCommands.ROBOCORP_LIST_WORK_ITEMS_INTERNAL, { "robot": robot, "increment_output": true } ); if (!work_items_action_result || !work_items_action_result.success) { return environment; } let result: WorkItemsInfo = work_items_action_result.result; if (!result) { return environment; } // Let's verify that the library is available and has the version we expect. let libraryVersionInfoActionResult: LibraryVersionInfoDict; try { libraryVersionInfoActionResult = await commands.executeCommand( roboCommands.ROBOCORP_VERIFY_LIBRARY_VERSION_INTERNAL, { "conda_prefix": condaPrefix, "library": "rpaframework", "version": "11.3", } ); } catch (error) { logError("Error updating launch environment.", error); return environment; } if (!libraryVersionInfoActionResult["success"]) { OUTPUT_CHANNEL.appendLine( "Launch environment for work items not updated. Reason: " + libraryVersionInfoActionResult.message ); return environment; } // If we have found the robot, we should have the result and thus we should always set the // RPA_OUTPUT_WORKITEM_PATH (even if we don't have any input, we'll set to where we want // to save items). let newEnv: { [key: string]: string } = { ...environment }; newEnv["RPA_OUTPUT_WORKITEM_PATH"] = result.new_output_workitem_path; newEnv["RPA_WORKITEMS_ADAPTER"] = "RPA.Robocorp.WorkItems.FileAdapter"; const input_work_items = result.input_work_items; const output_work_items = result.output_work_items; if (input_work_items.length > 0 || output_work_items.length > 0) { // If we have any input for this Robot, present it to the user. let items: QuickPickItemWithAction[] = []; // Note: just use the action as a 'data'. let noWorkItemLabel = "<No work item as input>"; items.push({ "label": "<No work item as input>", "action": undefined, }); for (const it of input_work_items) { items.push({ "label": it.name, "detail": "Input", "action": it.json_path, }); } for (const it of output_work_items) { items.push({ "label": it.name, "detail": "Output", "action": it.json_path, }); } let selectedItem = await showSelectOneQuickPick( items, "Please select the work item input to be used by RPA.Robocorp.WorkItems." ); if (!selectedItem) { return "cancelled"; } if (selectedItem.label === noWorkItemLabel) { return newEnv; } // No need to await. feedback("vscode.workitem.input.selected"); newEnv["RPA_INPUT_WORKITEM_PATH"] = selectedItem.action; } return newEnv; }
the_stack
import { writeJSON } from 'fs-extra'; import { resolve } from 'path'; import writePackage from 'write-pkg'; import { reifyDependencies } from '#package'; import { assertPresetterRC, bootstrapPreset, bootstrapContent, getContext, getDestinationMap, getPresetAssets, getPresetterRC, getScripts, setupPreset, unsetPreset, updatePresetterRC, } from '#preset'; import { linkFiles, unlinkFiles, writeFiles } from '#io'; import type { ResolvedPresetContext } from '#types'; jest.mock('console', () => ({ __esModule: true, info: jest.fn(), })); jest.mock( 'fs-extra', () => ({ __esModule: true, pathExists: jest.fn(async (path: string): Promise<boolean> => { // ensure that the paths below is compatible with windows const { posix, relative, resolve, sep } = jest.requireActual('path'); const posixPath = relative(resolve('/'), path).split(sep).join(posix.sep); switch (posixPath) { case `missing-preset/.presetterrc`: case `project/.presetterrc`: case 'link/rewritten/by/project': return true; default: return false; } }), writeJSON: jest.fn(), }), { virtual: true }, ); jest.mock('path', () => ({ __esModule: true, ...jest.requireActual<object>('path'), resolve: jest.fn((...pathSegments: string[]): string => { const { relative, resolve } = jest.requireActual<any>('path'); const relativePath = relative( resolve(__dirname, '..'), resolve(...pathSegments), ); return resolve('/', relativePath); }), })); jest.mock( 'preset', () => ({ __esModule: true, default: async () => ({ // an empty preset }), }), { virtual: true }, ); jest.mock( 'extension-preset', () => ({ __esModule: true, default: async () => ({ extends: ['no-symlink-preset', 'symlink-only-preset'], }), }), { virtual: true }, ); jest.mock( 'no-symlink-preset', () => ({ __esModule: true, default: async () => ({ template: { 'path/to/file': '/path/to/template', }, scripts: '/path/to/no-symlink-preset/scripts.yaml', }), }), { virtual: true }, ); jest.mock( 'symlink-only-preset', () => ({ __esModule: true, default: async () => ({ template: { 'link/pointed/to/preset': '/path/to/template', 'link/pointed/to/other': '/path/to/template', 'link/rewritten/by/project': '/path/to/template', }, scripts: '/path/to/symlink-only-preset/scripts.yaml', }), }), { virtual: true }, ); jest.mock('read-pkg', () => ({ __esModule: true, default: jest .fn() .mockReturnValueOnce({ devDependencies: { other: '*', }, }) .mockReturnValueOnce({ devDependencies: { other: '*', presetter: '*', preset1: '*', preset2: '*', }, }), })); jest.mock('resolve-pkg', () => ({ __esModule: true, default: (name: string): string => name, })); jest.mock('write-pkg', () => ({ __esModule: true, default: jest.fn(), })); // file name of the configuration file, null for missing file jest.mock('#io', () => ({ __esModule: true, loadDynamic: jest.fn(), linkFiles: jest.fn(), loadFile: jest.fn((path: string) => { // ensure that the paths below is compatible with windows const { posix, relative, resolve, sep } = jest.requireActual('path'); const posixPath = relative(resolve('/'), path).split(sep).join(posix.sep); switch (posixPath) { case 'path/to/template': return { template: true }; case 'path/to/no-symlink-preset/scripts.yaml': return { task: 'command_from_file' }; case 'path/to/symlink-only-preset/scripts.yaml': return { task: 'command_from_symlink' }; case `missing-preset/.presetterrc`: return { preset: 'missing-preset' }; case `project/.presetterrc`: return { preset: ['no-symlink-preset', 'symlink-only-preset'], noSymlinks: ['path/to/file'], }; default: throw new Error(`loadFile: missing ${path}`); } }), unlinkFiles: jest.fn(), writeFiles: jest.fn(), })); let mockArePeerPackagesAutoInstalled = false; jest.mock('#package', () => ({ __esModule: true, arePeerPackagesAutoInstalled: () => mockArePeerPackagesAutoInstalled, getPackage: jest.fn(async (root) => { switch (root) { case 'no-symlink-preset': case 'symlink-only-preset': return { json: { peerDependencies: { package: 'version', }, }, }; default: return { path: '/project/package.json', json: { name: 'client', scripts: { test: 'test', }, dependencies: {}, }, }; } }), reifyDependencies: jest.fn( async ({ add }: Parameters<typeof reifyDependencies>[0]) => add?.map((name) => ({ name, version: '*' })), ), })); const defaultContext: ResolvedPresetContext = { target: { name: 'client', root: '/project', package: {}, }, custom: { preset: ['no-symlink-preset', 'symlink-only-preset'], config: {}, noSymlinks: [], variable: {}, }, }; describe('fn:getPresetterRC', () => { it('accept an alternative file extension', async () => { expect(await getPresetterRC('/project')).toEqual({ preset: ['no-symlink-preset', 'symlink-only-preset'], noSymlinks: ['path/to/file'], }); }); it('throw an error if no configuration file is found', async () => { expect(() => getPresetterRC('/missing-presetterrc')).rejects.toThrow(); }); }); describe('fn:updatePresetterRC', () => { it('create a new .presetterrc if it is inexistent', async () => { await updatePresetterRC('/missing-presetterrc', { preset: ['new-preset'] }); expect(writeJSON).toBeCalledWith( resolve('/missing-presetterrc/.presetterrc.json'), { preset: ['new-preset'], }, { spaces: 2 }, ); }); it('merge with the existing .presetterrc', async () => { await updatePresetterRC('/project', { preset: ['new-preset'] }); expect(writeJSON).toBeCalledWith( resolve('/project/.presetterrc.json'), { preset: ['no-symlink-preset', 'symlink-only-preset', 'new-preset'], noSymlinks: ['path/to/file'], }, { spaces: 2 }, ); }); }); describe('fn:assertPresetterRC', () => { it('throw an error if the given value is not an object at all', () => { expect(() => assertPresetterRC(null)).toThrow(); }); it('throw an error if the given configuration misses the preset field', () => { expect(() => assertPresetterRC({})).toThrow(); }); it('throw an error if the preset field does not contain a preset name', () => { expect(() => assertPresetterRC({ preset: { not: { a: { name: true } } } }), ).toThrow(); }); it('pass if a valid preset is given', () => { expect(() => assertPresetterRC({ preset: 'preset' })).not.toThrow(); }); it('pass if multiple valid presets are given', () => { expect(() => assertPresetterRC({ preset: ['preset1', 'preset2'] }), ).not.toThrow(); }); }); describe('fn:getPresetAssets', () => { it('compute the preset configuration', async () => { expect(await getPresetAssets(defaultContext)).toEqual([ { template: { 'path/to/file': '/path/to/template', }, scripts: '/path/to/no-symlink-preset/scripts.yaml', }, { template: { 'link/pointed/to/preset': '/path/to/template', 'link/pointed/to/other': '/path/to/template', 'link/rewritten/by/project': '/path/to/template', }, scripts: '/path/to/symlink-only-preset/scripts.yaml', }, ]); }); it('add and merge extended presets', async () => { expect( await getPresetAssets({ ...defaultContext, custom: { ...defaultContext.custom, preset: 'extension-preset' }, }), ).toEqual([ { template: { 'path/to/file': '/path/to/template', }, scripts: '/path/to/no-symlink-preset/scripts.yaml', }, { template: { 'link/pointed/to/preset': '/path/to/template', 'link/pointed/to/other': '/path/to/template', 'link/rewritten/by/project': '/path/to/template', }, scripts: '/path/to/symlink-only-preset/scripts.yaml', }, { extends: ['no-symlink-preset', 'symlink-only-preset'] }, ]); }); it('warn about any missing presets', async () => { await expect(() => getPresetAssets({ target: { name: 'client', root: '/missing-preset', package: {}, }, custom: { preset: 'missing-preset' }, }), ).rejects.toThrow(); }); }); describe('fn:getScripts', () => { it('combine script templates from presets', async () => { const scripts = await getScripts(defaultContext); expect(scripts).toEqual({ task: 'command_from_symlink' }); }); }); describe('fn:setupPreset', () => { beforeAll(() => { jest.clearAllMocks(); setupPreset('preset1', 'preset2'); }); it('install presetter and the preset', async () => { expect(reifyDependencies).toBeCalledWith({ add: ['presetter', 'preset1', 'preset2'], root: '/project', saveAs: 'dev', lockFile: true, }); }); it('write to .presetter', async () => { expect(writeJSON).toBeCalledWith( resolve('/project/.presetterrc.json'), { preset: [ 'no-symlink-preset', 'symlink-only-preset', 'preset1', 'preset2', ], noSymlinks: ['path/to/file'], }, { spaces: 2 }, ); }); it('install the peer dependencies provided by the preset', async () => { expect(reifyDependencies).toHaveBeenCalledTimes(1); }); it('merge the bootstrapping script to package.json', async () => { expect(writePackage).toBeCalledWith('/project', { name: 'client', scripts: { prepare: 'presetter bootstrap', test: 'test', }, dependencies: {}, }); }); }); describe('fn:bootstrapPreset', () => { describe('peer packages auto installed disabled', () => { beforeAll(async () => { jest.clearAllMocks(); mockArePeerPackagesAutoInstalled = false; await bootstrapPreset(); }); it('install packages specified by the preset', async () => { expect(reifyDependencies).toHaveBeenCalledTimes(1); }); }); describe('peer packages auto installed enabled', () => { beforeEach(() => { jest.clearAllMocks(); mockArePeerPackagesAutoInstalled = true; }); afterAll(() => { mockArePeerPackagesAutoInstalled = false; }); it('install packages regardless', async () => { await bootstrapPreset({ force: true }); expect(reifyDependencies).toHaveBeenCalledTimes(1); }); it('skip installing peer packages manually if it is supported by package manager', async () => { mockArePeerPackagesAutoInstalled = true; await bootstrapPreset(); expect(reifyDependencies).not.toHaveBeenCalled(); }); }); }); describe('fn:bootstrapContent', () => { it('write configuration and link symlinks', async () => { await bootstrapContent({ ...defaultContext, custom: { ...defaultContext.custom, noSymlinks: ['path/to/file'] }, }); expect(writeFiles).toBeCalledWith( '/project', { 'link/pointed/to/other': { template: true }, 'link/pointed/to/preset': { template: true }, 'link/rewritten/by/project': { template: true }, 'path/to/file': { template: true }, }, { 'link/pointed/to/other': resolve( '/presetter/generated/client/link/pointed/to/other', ), 'link/pointed/to/preset': resolve( '/presetter/generated/client/link/pointed/to/preset', ), 'link/rewritten/by/project': resolve( '/presetter/generated/client/link/rewritten/by/project', ), 'path/to/file': resolve('/project/path/to/file'), }, ); expect(linkFiles).toBeCalledWith('/project', { 'path/to/file': resolve('/project/path/to/file'), 'link/pointed/to/preset': resolve( '/presetter/generated/client/link/pointed/to/preset', ), 'link/pointed/to/other': resolve( '/presetter/generated/client/link/pointed/to/other', ), 'link/rewritten/by/project': resolve( '/presetter/generated/client/link/rewritten/by/project', ), }); }); it('ignore configuration', async () => { await bootstrapContent({ ...defaultContext, custom: { ...defaultContext.custom, config: { 'path/to/file': { name: 'path/to/file' }, 'link/pointed/to/preset': { name: 'link/pointed/to/preset' }, 'link/pointed/to/other': { name: 'link/pointed/to/other' }, 'link/rewritten/by/project': { name: 'link/rewritten/by/project' }, }, noSymlinks: ['path/to/file'], ignores: [ 'link/pointed/to/preset', 'link/pointed/to/other', 'link/rewritten/by/project', { 'path/to/file': ['name'] }, ], }, }); expect(writeFiles).toBeCalledWith( '/project', { 'path/to/file': { template: true } }, { 'path/to/file': resolve('/project/path/to/file') }, ); expect(linkFiles).toBeCalledWith('/project', { 'path/to/file': resolve('/project/path/to/file'), }); }); }); describe('fn:unsetPreset', () => { beforeAll(unsetPreset); it('clean up any artifacts installed on the project root', async () => { expect(unlinkFiles).toHaveBeenCalledWith('/project', { 'link/pointed/to/other': resolve( '/presetter/generated/client/link/pointed/to/other', ), 'link/pointed/to/preset': resolve( '/presetter/generated/client/link/pointed/to/preset', ), 'link/rewritten/by/project': resolve( '/presetter/generated/client/link/rewritten/by/project', ), 'path/to/file': resolve('/project/path/to/file'), }); }); }); describe('fn:getContext', () => { it('compute the current context', async () => { expect(await getContext()).toEqual({ target: { name: 'client', root: '/project', package: { dependencies: {}, name: 'client', scripts: { test: 'test', }, }, }, custom: { preset: ['no-symlink-preset', 'symlink-only-preset'], noSymlinks: ['path/to/file'], }, }); }); }); describe('fn:getDestinationMap', () => { it('compute the correct output paths', async () => { expect( await getDestinationMap( { config: '/path/to/template', }, defaultContext, ), ).toEqual({ config: resolve('/presetter/generated/client/config'), }); }); it('compute the correct output paths', async () => { expect( await getDestinationMap( { noSymlink: '/path/to/template', symlink: '/path/to/template', }, { ...defaultContext, custom: { ...defaultContext.custom, noSymlinks: ['noSymlink'] }, }, ), ).toEqual({ noSymlink: resolve('/project/noSymlink'), symlink: resolve('/presetter/generated/client/symlink'), }); }); });
the_stack
import type { BufferInfo } from '../utils/buffer-helper'; import { BufferHelper } from '../utils/buffer-helper'; import { ErrorTypes, ErrorDetails } from '../errors'; import { Events } from '../events'; import { logger } from '../utils/logger'; import type Hls from '../hls'; import type { HlsConfig } from '../config'; import type { FragmentTracker } from './fragment-tracker'; import { Fragment } from '../loader/fragment'; export const STALL_MINIMUM_DURATION_MS = 250; export const MAX_START_GAP_JUMP = 2.0; export const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1; export const SKIP_BUFFER_RANGE_START = 0.05; export default class GapController { private config: HlsConfig; private media: HTMLMediaElement; private fragmentTracker: FragmentTracker; private hls: Hls; private nudgeRetry: number = 0; private stallReported: boolean = false; private stalled: number | null = null; private moved: boolean = false; private seeking: boolean = false; constructor(config, media, fragmentTracker, hls) { this.config = config; this.media = media; this.fragmentTracker = fragmentTracker; this.hls = hls; } public destroy() { // @ts-ignore this.hls = this.fragmentTracker = this.media = null; } /** * Checks if the playhead is stuck within a gap, and if so, attempts to free it. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range). * * @param {number} lastCurrentTime Previously read playhead position */ public poll(lastCurrentTime: number) { const { config, media, stalled } = this; const { currentTime, seeking } = media; const seeked = this.seeking && !seeking; const beginSeek = !this.seeking && seeking; this.seeking = seeking; // The playhead is moving, no-op if (currentTime !== lastCurrentTime) { this.moved = true; if (stalled !== null) { // The playhead is now moving, but was previously stalled if (this.stallReported) { const stalledDuration = self.performance.now() - stalled; logger.warn( `playback not stuck anymore @${currentTime}, after ${Math.round( stalledDuration )}ms` ); this.stallReported = false; } this.stalled = null; this.nudgeRetry = 0; } return; } // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek if (beginSeek || seeked) { this.stalled = null; } // The playhead should not be moving if ( media.paused || media.ended || media.playbackRate === 0 || !BufferHelper.getBuffered(media).length ) { return; } const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0); const isBuffered = bufferInfo.len > 0; const nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer) if (!isBuffered && !nextStart) { return; } if (seeking) { // Waiting for seeking in a buffered range to complete const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking const noBufferGap = !nextStart || (nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime)); if (hasEnoughBuffer || noBufferGap) { return; } // Reset moved state when seeking to a point in or before a gap this.moved = false; } // Skip start gaps if we haven't played, but the last poll detected the start of a stall // The addition poll gives the browser a chance to jump the gap for us if (!this.moved && this.stalled !== null) { // Jump start gaps within jump threshold const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment // that begins over 1 target duration after the video start position. const level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null; const isLive = level?.details?.live; const maxStartGapJump = isLive ? level!.details!.targetduration * 2 : MAX_START_GAP_JUMP; if (startJump > 0 && startJump <= maxStartGapJump) { this._trySkipBufferHole(null); return; } } // Start tracking stall time const tnow = self.performance.now(); if (stalled === null) { this.stalled = tnow; return; } const stalledDuration = tnow - stalled; if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) { // Report stalling after trying to fix this._reportStall(bufferInfo.len); } const bufferedWithHoles = BufferHelper.bufferInfo( media, currentTime, config.maxBufferHole ); this._tryFixBufferStall(bufferedWithHoles, stalledDuration); } /** * Detects and attempts to fix known buffer stalling issues. * @param bufferInfo - The properties of the current buffer. * @param stalledDurationMs - The amount of time Hls.js has been stalling for. * @private */ private _tryFixBufferStall( bufferInfo: BufferInfo, stalledDurationMs: number ) { const { config, fragmentTracker, media } = this; const currentTime = media.currentTime; const partial = fragmentTracker.getPartialFragment(currentTime); if (partial) { // Try to skip over the buffer hole caused by a partial fragment // This method isn't limited by the size of the gap between buffered ranges const targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning // the branch below only executes when we don't handle a partial fragment if (targetTime) { return; } } // if we haven't had to skip over a buffer hole of a partial fragment // we may just have to "nudge" the playlist as the browser decoding/rendering engine // needs to cross some sort of threshold covering all source-buffers content // to start playing properly. if ( bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000 ) { logger.warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds // We only try to jump the hole if it's under the configured size // Reset stalled so to rearm watchdog timer this.stalled = null; this._tryNudgeBuffer(); } } /** * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period. * @param bufferLen - The playhead distance from the end of the current buffer segment. * @private */ private _reportStall(bufferLen) { const { hls, media, stallReported } = this; if (!stallReported) { // Report stalled error once this.stallReported = true; logger.warn( `Playback stalling at @${media.currentTime} due to low buffer (buffer=${bufferLen})` ); hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen, }); } } /** * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments * @param partial - The partial fragment found at the current time (where playback is stalling). * @private */ private _trySkipBufferHole(partial: Fragment | null): number { const { config, hls, media } = this; const currentTime = media.currentTime; let lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments const buffered = BufferHelper.getBuffered(media); for (let i = 0; i < buffered.length; i++) { const startTime = buffered.start(i); if ( currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime ) { const targetTime = Math.max( startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS ); logger.warn( `skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}` ); this.moved = true; this.stalled = null; media.currentTime = targetTime; if (partial) { hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`, frag: partial, }); } return targetTime; } lastEndTime = buffered.end(i); } return 0; } /** * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount. * @private */ private _tryNudgeBuffer() { const { config, hls, media } = this; const currentTime = media.currentTime; const nudgeRetry = (this.nudgeRetry || 0) + 1; this.nudgeRetry = nudgeRetry; if (nudgeRetry < config.nudgeMaxRetry) { const targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this logger.warn(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`); media.currentTime = targetTime; hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false, }); } else { logger.error( `Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges` ); hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: true, }); } } }
the_stack
import { AbstractJSONRPCTransport, DummyTransport, HTTPTransport, WSTransport } from './transport'; import { BigNumber, ethers } from 'ethers'; import { AccountState, Address, IncomingTxFeeType, ContractAddress, Fee, Network, PriorityOperationReceipt, TokenAddress, TokenLike, Tokens, TransactionReceipt, TxEthSignature, TxEthSignatureVariant, NFTInfo, Toggle2FARequest, Toggle2FAResponse } from './types'; import { isTokenETH, sleep, TokenSet } from './utils'; import { Governance, GovernanceFactory, ZkSync, ZkSyncFactory, ZkSyncNFTFactory, ZkSyncNFTFactoryFactory } from './typechain'; import { SyncProvider } from './provider-interface'; export async function getDefaultProvider(network: Network, transport: 'WS' | 'HTTP' = 'HTTP'): Promise<Provider> { if (transport === 'WS') { console.warn('Websocket support will be removed in future. Use HTTP transport instead.'); } if (network === 'localhost') { if (transport === 'WS') { return await Provider.newWebsocketProvider('ws://127.0.0.1:3031'); } else if (transport === 'HTTP') { return await Provider.newHttpProvider('http://127.0.0.1:3030'); } } else if (network === 'ropsten') { if (transport === 'WS') { return await Provider.newWebsocketProvider('wss://ropsten-api.zksync.io/jsrpc-ws'); } else if (transport === 'HTTP') { return await Provider.newHttpProvider('https://ropsten-api.zksync.io/jsrpc'); } } else if (network === 'rinkeby') { if (transport === 'WS') { return await Provider.newWebsocketProvider('wss://rinkeby-api.zksync.io/jsrpc-ws'); } else if (transport === 'HTTP') { return await Provider.newHttpProvider('https://rinkeby-api.zksync.io/jsrpc'); } } else if (network === 'ropsten-beta') { if (transport === 'WS') { return await Provider.newWebsocketProvider('wss://ropsten-beta-api.zksync.io/jsrpc-ws'); } else if (transport === 'HTTP') { return await Provider.newHttpProvider('https://ropsten-beta-api.zksync.io/jsrpc'); } } else if (network === 'rinkeby-beta') { if (transport === 'WS') { return await Provider.newWebsocketProvider('wss://rinkeby-beta-api.zksync.io/jsrpc-ws'); } else if (transport === 'HTTP') { return await Provider.newHttpProvider('https://rinkeby-beta-api.zksync.io/jsrpc'); } } else if (network === 'mainnet') { if (transport === 'WS') { return await Provider.newWebsocketProvider('wss://api.zksync.io/jsrpc-ws'); } else if (transport === 'HTTP') { return await Provider.newHttpProvider('https://api.zksync.io/jsrpc'); } } else { throw new Error(`Ethereum network ${network} is not supported`); } } export class Provider extends SyncProvider { private constructor(public transport: AbstractJSONRPCTransport) { super(); this.providerType = 'RPC'; } /** * @deprecated Websocket support will be removed in future. Use HTTP transport instead. */ static async newWebsocketProvider(address: string): Promise<Provider> { const transport = await WSTransport.connect(address); const provider = new Provider(transport); const contractsAndTokens = await Promise.all([provider.getContractAddress(), provider.getTokens()]); provider.contractAddress = contractsAndTokens[0]; provider.tokenSet = new TokenSet(contractsAndTokens[1]); return provider; } static async newHttpProvider( address: string = 'http://127.0.0.1:3030', pollIntervalMilliSecs?: number ): Promise<Provider> { const transport = new HTTPTransport(address); const provider = new Provider(transport); if (pollIntervalMilliSecs) { provider.pollIntervalMilliSecs = pollIntervalMilliSecs; } const contractsAndTokens = await Promise.all([provider.getContractAddress(), provider.getTokens()]); provider.contractAddress = contractsAndTokens[0]; provider.tokenSet = new TokenSet(contractsAndTokens[1]); return provider; } /** * Provides some hardcoded values the `Provider` responsible for * without communicating with the network */ static async newMockProvider(network: string, ethPrivateKey: Uint8Array, getTokens: Function): Promise<Provider> { const transport = new DummyTransport(network, ethPrivateKey, getTokens); const provider = new Provider(transport); const contractsAndTokens = await Promise.all([provider.getContractAddress(), provider.getTokens()]); provider.contractAddress = contractsAndTokens[0]; provider.tokenSet = new TokenSet(contractsAndTokens[1]); return provider; } // return transaction hash (e.g. sync-tx:dead..beef) async submitTx(tx: any, signature?: TxEthSignatureVariant, fastProcessing?: boolean): Promise<string> { return await this.transport.request('tx_submit', [tx, signature, fastProcessing]); } // Requests `zkSync` server to execute several transactions together. // return transaction hash (e.g. sync-tx:dead..beef) async submitTxsBatch( transactions: { tx: any; signature?: TxEthSignatureVariant }[], ethSignatures?: TxEthSignature | TxEthSignature[] ): Promise<string[]> { let signatures: TxEthSignature[] = []; // For backwards compatibility we allow sending single signature as well // as no signatures at all. if (ethSignatures == undefined) { signatures = []; } else if (ethSignatures instanceof Array) { signatures = ethSignatures; } else { signatures.push(ethSignatures); } return await this.transport.request('submit_txs_batch', [transactions, signatures]); } async getContractAddress(): Promise<ContractAddress> { return await this.transport.request('contract_address', null); } async getTokens(): Promise<Tokens> { return await this.transport.request('tokens', null); } async getState(address: Address): Promise<AccountState> { return await this.transport.request('account_info', [address]); } // get transaction status by its hash (e.g. 0xdead..beef) async getTxReceipt(txHash: string): Promise<TransactionReceipt> { return await this.transport.request('tx_info', [txHash]); } async getPriorityOpStatus(serialId: number): Promise<PriorityOperationReceipt> { return await this.transport.request('ethop_info', [serialId]); } async getConfirmationsForEthOpAmount(): Promise<number> { return await this.transport.request('get_confirmations_for_eth_op_amount', []); } async getEthTxForWithdrawal(withdrawal_hash: string): Promise<string> { return await this.transport.request('get_eth_tx_for_withdrawal', [withdrawal_hash]); } async getNFT(id: number): Promise<NFTInfo> { const nft = await this.transport.request('get_nft', [id]); // If the NFT does not exist, throw an exception if (nft == null) { throw new Error(`Requested NFT doesn't exist or the corresponding mintNFT operation is not verified yet`); } return nft; } async getNFTOwner(id: number): Promise<number> { return await this.transport.request('get_nft_owner', [id]); } async notifyPriorityOp(serialId: number, action: 'COMMIT' | 'VERIFY'): Promise<PriorityOperationReceipt> { if (this.transport.subscriptionsSupported()) { return await new Promise((resolve) => { const subscribe = this.transport.subscribe( 'ethop_subscribe', [serialId, action], 'ethop_unsubscribe', (resp) => { subscribe .then((sub) => sub.unsubscribe()) .catch((err) => console.log(`WebSocket connection closed with reason: ${err}`)); resolve(resp); } ); }); } else { while (true) { const priorOpStatus = await this.getPriorityOpStatus(serialId); const notifyDone = action === 'COMMIT' ? priorOpStatus.block && priorOpStatus.block.committed : priorOpStatus.block && priorOpStatus.block.verified; if (notifyDone) { return priorOpStatus; } else { await sleep(this.pollIntervalMilliSecs); } } } } async notifyTransaction(hash: string, action: 'COMMIT' | 'VERIFY'): Promise<TransactionReceipt> { if (this.transport.subscriptionsSupported()) { return await new Promise((resolve) => { const subscribe = this.transport.subscribe('tx_subscribe', [hash, action], 'tx_unsubscribe', (resp) => { subscribe .then((sub) => sub.unsubscribe()) .catch((err) => console.log(`WebSocket connection closed with reason: ${err}`)); resolve(resp); }); }); } else { while (true) { const transactionStatus = await this.getTxReceipt(hash); const notifyDone = action == 'COMMIT' ? transactionStatus.block && transactionStatus.block.committed : transactionStatus.block && transactionStatus.block.verified; if (notifyDone) { return transactionStatus; } else { await sleep(this.pollIntervalMilliSecs); } } } } async getTransactionFee(txType: IncomingTxFeeType, address: Address, tokenLike: TokenLike): Promise<Fee> { const transactionFee = await this.transport.request('get_tx_fee', [txType, address.toString(), tokenLike]); return { feeType: transactionFee.feeType, gasTxAmount: BigNumber.from(transactionFee.gasTxAmount), gasPriceWei: BigNumber.from(transactionFee.gasPriceWei), gasFee: BigNumber.from(transactionFee.gasFee), zkpFee: BigNumber.from(transactionFee.zkpFee), totalFee: BigNumber.from(transactionFee.totalFee) }; } async getTransactionsBatchFee( txTypes: IncomingTxFeeType[], addresses: Address[], tokenLike: TokenLike ): Promise<BigNumber> { const batchFee = await this.transport.request('get_txs_batch_fee_in_wei', [txTypes, addresses, tokenLike]); return BigNumber.from(batchFee.totalFee); } async getTokenPrice(tokenLike: TokenLike): Promise<number> { const tokenPrice = await this.transport.request('get_token_price', [tokenLike]); return parseFloat(tokenPrice); } async toggle2FA(toggle2FA: Toggle2FARequest): Promise<boolean> { const result: Toggle2FAResponse = await this.transport.request('toggle_2fa', [toggle2FA]); return result.success; } async disconnect() { return await this.transport.disconnect(); } } export class ETHProxy { private governanceContract: Governance; private zkSyncContract: ZkSync; private zksyncNFTFactory: ZkSyncNFTFactory; // Needed for typechain to work private dummySigner: ethers.VoidSigner; constructor(private ethersProvider: ethers.providers.Provider, public contractAddress: ContractAddress) { this.dummySigner = new ethers.VoidSigner(ethers.constants.AddressZero, this.ethersProvider); const governanceFactory = new GovernanceFactory(this.dummySigner); this.governanceContract = governanceFactory.attach(contractAddress.govContract); const zkSyncFactory = new ZkSyncFactory(this.dummySigner); this.zkSyncContract = zkSyncFactory.attach(contractAddress.mainContract); } getGovernanceContract(): Governance { return this.governanceContract; } getZkSyncContract(): ZkSync { return this.zkSyncContract; } // This method is very helpful for those who have already fetched the // default factory and want to avoid asynchorouns execution from now on getCachedNFTDefaultFactory(): ZkSyncNFTFactory | undefined { return this.zksyncNFTFactory; } async getDefaultNFTFactory(): Promise<ZkSyncNFTFactory> { if (this.zksyncNFTFactory) { return this.zksyncNFTFactory; } const nftFactoryAddress = await this.governanceContract.defaultFactory(); const nftFactory = new ZkSyncNFTFactoryFactory(this.dummySigner); this.zksyncNFTFactory = nftFactory.attach(nftFactoryAddress); return this.zksyncNFTFactory; } async resolveTokenId(token: TokenAddress): Promise<number> { if (isTokenETH(token)) { return 0; } else { const tokenId = await this.governanceContract.tokenIds(token); if (tokenId == 0) { throw new Error(`ERC20 token ${token} is not supported`); } return tokenId; } } }
the_stack
import { schemas } from '@0x/json-schemas'; import { MarketOperation, Order } from '@0x/types'; import { BigNumber } from '@0x/utils'; import * as _ from 'lodash'; import { assert } from './assert'; import { constants } from './constants'; import { FeeOrdersAndRemainingFeeAmount, FindFeeOrdersThatCoverFeesForTargetOrdersOpts, FindOrdersThatCoverMakerAssetFillAmountOpts, FindOrdersThatCoverTakerAssetFillAmountOpts, OrdersAndRemainingMakerFillAmount, OrdersAndRemainingTakerFillAmount, } from './types'; export const marketUtils = { findOrdersThatCoverTakerAssetFillAmount<T extends Order>( orders: T[], takerAssetFillAmount: BigNumber, opts?: FindOrdersThatCoverTakerAssetFillAmountOpts, ): OrdersAndRemainingTakerFillAmount<T> { return findOrdersThatCoverAssetFillAmount<T>( orders, takerAssetFillAmount, MarketOperation.Sell, opts, ) as OrdersAndRemainingTakerFillAmount<T>; }, /** * Takes an array of orders and returns a subset of those orders that has enough makerAssetAmount * in order to fill the input makerAssetFillAmount plus slippageBufferAmount. Iterates from first order to last order. * Sort the input by ascending rate in order to get the subset of orders that will cost the least ETH. * @param orders An array of objects that extend the Order interface. All orders should specify the same makerAsset. * All orders should specify WETH as the takerAsset. * @param makerAssetFillAmount The amount of makerAsset desired to be filled. * @param opts Optional arguments this function accepts. * @return Resulting orders and remaining fill amount that could not be covered by the input. */ findOrdersThatCoverMakerAssetFillAmount<T extends Order>( orders: T[], makerAssetFillAmount: BigNumber, opts?: FindOrdersThatCoverMakerAssetFillAmountOpts, ): OrdersAndRemainingMakerFillAmount<T> { return findOrdersThatCoverAssetFillAmount<T>( orders, makerAssetFillAmount, MarketOperation.Buy, opts, ) as OrdersAndRemainingMakerFillAmount<T>; }, /** * Takes an array of orders and an array of feeOrders. Returns a subset of the feeOrders that has enough ZRX * in order to fill the takerFees required by orders plus a slippageBufferAmount. * Iterates from first feeOrder to last. Sort the feeOrders by ascending rate in order to get the subset of * feeOrders that will cost the least ETH. * @param orders An array of objects that extend the Order interface. All orders should specify ZRX as * the makerAsset and WETH as the takerAsset. * @param feeOrders An array of objects that extend the Order interface. All orders should specify ZRX as * the makerAsset and WETH as the takerAsset. * @param opts Optional arguments this function accepts. * @return Resulting orders and remaining fee amount that could not be covered by the input. */ findFeeOrdersThatCoverFeesForTargetOrders<T extends Order>( orders: T[], feeOrders: T[], opts?: FindFeeOrdersThatCoverFeesForTargetOrdersOpts, ): FeeOrdersAndRemainingFeeAmount<T> { assert.doesConformToSchema('orders', orders, schemas.ordersSchema); assert.doesConformToSchema('feeOrders', feeOrders, schemas.ordersSchema); // try to get remainingFillableMakerAssetAmounts from opts, if it's not there, use makerAssetAmount values from orders const remainingFillableMakerAssetAmounts = _.get( opts, 'remainingFillableMakerAssetAmounts', _.map(orders, order => order.makerAssetAmount), ) as BigNumber[]; _.forEach(remainingFillableMakerAssetAmounts, (amount, index) => assert.isValidBaseUnitAmount(`remainingFillableMakerAssetAmount[${index}]`, amount), ); assert.assert( orders.length === remainingFillableMakerAssetAmounts.length, 'Expected orders.length to equal opts.remainingFillableMakerAssetAmounts.length', ); // try to get remainingFillableFeeAmounts from opts, if it's not there, use makerAssetAmount values from feeOrders const remainingFillableFeeAmounts = _.get( opts, 'remainingFillableFeeAmounts', _.map(feeOrders, order => order.makerAssetAmount), ) as BigNumber[]; _.forEach(remainingFillableFeeAmounts, (amount, index) => assert.isValidBaseUnitAmount(`remainingFillableFeeAmounts[${index}]`, amount), ); assert.assert( feeOrders.length === remainingFillableFeeAmounts.length, 'Expected feeOrders.length to equal opts.remainingFillableFeeAmounts.length', ); // try to get slippageBufferAmount from opts, if it's not there, default to 0 const slippageBufferAmount = _.get(opts, 'slippageBufferAmount', constants.ZERO_AMOUNT) as BigNumber; assert.isValidBaseUnitAmount('opts.slippageBufferAmount', slippageBufferAmount); // calculate total amount of ZRX needed to fill orders const totalFeeAmount = _.reduce( orders, (accFees, order, index) => { const makerAssetAmountAvailable = remainingFillableMakerAssetAmounts[index]; const feeToFillMakerAssetAmountAvailable = makerAssetAmountAvailable .multipliedBy(order.takerFee) .dividedToIntegerBy(order.makerAssetAmount); return accFees.plus(feeToFillMakerAssetAmountAvailable); }, constants.ZERO_AMOUNT, ); const { resultOrders, remainingFillAmount, ordersRemainingFillableMakerAssetAmounts, } = marketUtils.findOrdersThatCoverMakerAssetFillAmount(feeOrders, totalFeeAmount, { remainingFillableMakerAssetAmounts: remainingFillableFeeAmounts, slippageBufferAmount, }); return { resultFeeOrders: resultOrders, remainingFeeAmount: remainingFillAmount, feeOrdersRemainingFillableMakerAssetAmounts: ordersRemainingFillableMakerAssetAmounts, }; // TODO: add more orders here to cover rounding // https://github.com/0xProject/0x-protocol-specification/blob/master/v2/forwarding-contract-specification.md#over-buying-zrx }, }; function findOrdersThatCoverAssetFillAmount<T extends Order>( orders: T[], assetFillAmount: BigNumber, operation: MarketOperation, opts?: FindOrdersThatCoverTakerAssetFillAmountOpts | FindOrdersThatCoverMakerAssetFillAmountOpts, ): OrdersAndRemainingTakerFillAmount<T> | OrdersAndRemainingMakerFillAmount<T> { const variablePrefix = operation === MarketOperation.Buy ? 'Maker' : 'Taker'; assert.doesConformToSchema('orders', orders, schemas.ordersSchema); assert.isValidBaseUnitAmount('assetFillAmount', assetFillAmount); // try to get remainingFillableTakerAssetAmounts from opts, if it's not there, use takerAssetAmount values from orders const remainingFillableAssetAmounts = _.get( opts, `remainingFillable${variablePrefix}AssetAmounts`, _.map(orders, order => (operation === MarketOperation.Buy ? order.makerAssetAmount : order.takerAssetAmount)), ) as BigNumber[]; _.forEach(remainingFillableAssetAmounts, (amount, index) => assert.isValidBaseUnitAmount(`remainingFillable${variablePrefix}AssetAmount[${index}]`, amount), ); assert.assert( orders.length === remainingFillableAssetAmounts.length, `Expected orders.length to equal opts.remainingFillable${variablePrefix}AssetAmounts.length`, ); // try to get slippageBufferAmount from opts, if it's not there, default to 0 const slippageBufferAmount = _.get(opts, 'slippageBufferAmount', constants.ZERO_AMOUNT) as BigNumber; assert.isValidBaseUnitAmount('opts.slippageBufferAmount', slippageBufferAmount); // calculate total amount of asset needed to be filled const totalFillAmount = assetFillAmount.plus(slippageBufferAmount); // iterate through the orders input from left to right until we have enough makerAsset to fill totalFillAmount const result = _.reduce( orders, ({ resultOrders, remainingFillAmount, ordersRemainingFillableAssetAmounts }, order, index) => { if (remainingFillAmount.isLessThanOrEqualTo(constants.ZERO_AMOUNT)) { return { resultOrders, remainingFillAmount: constants.ZERO_AMOUNT, ordersRemainingFillableAssetAmounts, }; } else { const assetAmountAvailable = remainingFillableAssetAmounts[index]; const shouldIncludeOrder = assetAmountAvailable.gt(constants.ZERO_AMOUNT); // if there is no assetAmountAvailable do not append order to resultOrders // if we have exceeded the total amount we want to fill set remainingFillAmount to 0 return { resultOrders: shouldIncludeOrder ? _.concat(resultOrders, order) : resultOrders, ordersRemainingFillableAssetAmounts: shouldIncludeOrder ? _.concat(ordersRemainingFillableAssetAmounts, assetAmountAvailable) : ordersRemainingFillableAssetAmounts, remainingFillAmount: BigNumber.max( constants.ZERO_AMOUNT, remainingFillAmount.minus(assetAmountAvailable), ), }; } }, { resultOrders: [] as T[], remainingFillAmount: totalFillAmount, ordersRemainingFillableAssetAmounts: [] as BigNumber[], }, ); const { ordersRemainingFillableAssetAmounts: resultOrdersRemainingFillableAssetAmounts, // tslint:disable-next-line: trailing-comma ...ordersAndRemainingFillAmount } = result; if (operation === MarketOperation.Buy) { return { ...ordersAndRemainingFillAmount, ordersRemainingFillableMakerAssetAmounts: resultOrdersRemainingFillableAssetAmounts, }; } else { return { ...ordersAndRemainingFillAmount, ordersRemainingFillableTakerAssetAmounts: resultOrdersRemainingFillableAssetAmounts, }; } }
the_stack
import { ContainerPool } from "../core/container"; import { BadRequest, InternalServerError } from "../core/errors"; import { LogLevel } from "../core/logger"; import { EventRecord, EventRequest, EventResult, HttpMethod, HttpRequest, HttpResponse, RemoteRequest } from "../core/types"; import { HttpUtils, Utils } from "../core/utils"; import { LambdaError } from "./error"; export type UUID = string; export interface RemoteEvent extends RemoteRequest { // Any additional params ... } export interface LambdaS3Event { Records: LambdaS3Record[]; } export interface LambdaEventRecord extends EventRecord { eventSource: "aws:s3" | "aws:dynamodb"; eventVersion: string; eventName: string; // TODO: Enum awsRegion: string; } export interface LambdaS3Record extends LambdaEventRecord { eventSource: "aws:s3"; eventTime: string; userIdentity?: { principalId: string; [key: string]: string; }; requestParameters?: { sourceIPAddress: string; [key: string]: string; }; responseElements: Record<string, string>; // { // "x-amz-request-id": "977AC95B5E343C51", // "x-amz-id-2": "ECIEtKyeUlJpLZskSCbflZJZdPz1XGVu6mOb9knu50TFHlL/FcRSkn5g76IYWrpG874IR0rCTmA=" // } s3: { s3SchemaVersion: "1.0" | string, configurationId: string, bucket: { name: string; ownerIdentity: { principalId: string; }, arn: string; }; object: { key: string, size: number, eTag: string, sequencer: string }; }; } export interface LambdaDynamoEvent { Records: LambdaDynamoRecord[]; } export interface LambdaDynamoRecord extends LambdaEventRecord { eventID: string; eventSource: "aws:dynamodb"; eventSourceARN: string; eventName: "INSERT" | "MODIFY" | "REMOVE"; // TODO: object keyword supported in typescript ???? dynamodb: { ApproximateCreationDateTime: number, Keys: Record<string, object>; SequenceNumber: string; SizeBytes: number, StreamViewType: "KEYS_ONLY" | "NEW_IMAGE" | "OLD_IMAGE" | "NEW_AND_OLD_IMAGES"; NewImage?: Record<string, object>; OldImage?: Record<string, object>; }; } export interface LambdaScheduleEvent { type: string; action: string; [prop: string]: string; } export interface LambdaApiEvent { resource: string; path: string; httpMethod: string; headers: { [header: string]: string; }; pathParameters: { [param: string]: string; }; queryStringParameters: { [param: string]: string; }; body: string | null; isBase64Encoded: boolean; stageVariables?: { [variable: string]: string; }; req?: { accountId: string; resourceId: string; stage: string; requestId: UUID; identity: { sourceIp: string; userAgent: string; cognitoIdentityId: any; cognitoIdentityPoolId: any; cognitoAuthenticationType: any; cognitoAuthenticationProvider: any; accountId: any; caller: any; apiKey: any; accessKey: any; userArn: any; user: any; }; }; } export interface LambdaContext { functionName: string; functionVersion: string; invokeid: UUID; awsRequestId: UUID; callbackWaitsForEmptyEventLoop: boolean; logGroupName: string; logStreamName: string; memoryLimitInMB: string; invokedFunctionArn: string; succeed?: (object: any) => void; fail?: (error: any) => void; done?: (error: any, result: any) => void; } export interface LambdaCallback { (err: LambdaError, response?: HttpResponse | Object): void; } export type LambdaEvent = RemoteEvent & LambdaApiEvent & LambdaS3Event & LambdaDynamoEvent & LambdaScheduleEvent; export interface LambdaHandler { ( event: LambdaEvent, context: LambdaContext, callback: LambdaCallback ): boolean | void; } export class LambdaContainer extends ContainerPool { constructor(applicationId: string) { super(applicationId, LambdaContainer.name); } public export(): LambdaHandler { try { this.prepare(); } catch (err) { console.log(err); } return (event, context, callback) => { this.handler(event, context) .then(res => callback(null, res)) .catch(err => callback(new LambdaError(err), null)); }; } private async handler(event: LambdaEvent, context: LambdaContext) { try { this.prepare(); } catch (err) { this.log.error(err); return HttpUtils.error(err); } LogLevel.set(this.config.logLevel); this.log.debug("Lambda Event: %j", event); this.log.debug("Lambda Context: %j", context); if (event.httpMethod) { try { let res = await this.http(event, context); return HttpUtils.prepare(res); } catch (err) { this.log.error(err); return HttpUtils.error(err); } } else if ((event.type === "remote" || event.type === "internal") && event.service && event.method) { try { return await this.remote(event, context); } catch (err) { this.log.error(err); throw InternalServerError.wrap(err); } } else if (event.type === "schedule" && event.action) { try { return await this.schedule(event, context); } catch (err) { this.log.error(err); throw InternalServerError.wrap(err); } } else if (event.Records && event.Records[0] && event.Records[0].eventSource === "aws:s3") { try { return await this.s3(event, context); } catch (err) { this.log.error(err); throw InternalServerError.wrap(err); } } else if (event.Records && event.Records[0] && event.Records[0].eventSource === "aws:dynamodb") { try { return await this.dynamo(event, context); } catch (err) { this.log.error(err); throw InternalServerError.wrap(err); } } else { throw new BadRequest("Invalid event"); } } private async http(event: LambdaApiEvent, context: LambdaContext): Promise<HttpResponse> { let req: HttpRequest = { type: "http", requestId: context && context.awsRequestId || Utils.uuid(), sourceIp: (event.req && event.req.identity && event.req.identity.sourceIp) || "255.255.255.255", application: undefined, service: undefined, method: undefined, httpMethod: event.httpMethod as HttpMethod, resource: event.resource, path: event.path, pathParameters: event.pathParameters || {}, queryStringParameters: event.queryStringParameters || {}, headers: HttpUtils.canonicalHeaders(event.headers || {}), body: event.body, isBase64Encoded: event.isBase64Encoded || false }; return super.httpRequest(req); } private async remote(event: RemoteEvent, context: LambdaContext): Promise<any> { event.requestId = context && context.awsRequestId || Utils.uuid(); return super.remoteRequest(event); } private async s3(event: LambdaS3Event, context: LambdaContext): Promise<EventResult> { this.log.info("S3 Event: %j", event); let requestId = context && context.awsRequestId || Utils.uuid(); let time = new Date().toISOString(); let reqs: Record<string, EventRequest> = {}; for (let record of event.Records) { let resource = record.s3.bucket.name; let object = record.s3.object.key; let action = record.eventName; let group = `${resource}/${action}@${object}`; if (!reqs[group]) reqs[group] = { type: "event", source: "aws:s3", application: undefined, service: undefined, method: undefined, requestId, resource, action, time, object, records: [] }; reqs[group].records.push(record); } // TODO: Iteration of all, combine result let result: EventResult; for (let key in reqs) { let req = reqs[key]; this.log.info("S3 Request [%s:%s]: %j", req.resource, req.object, req); result = await super.eventRequest(req); } return result; } private async schedule(event: LambdaScheduleEvent, context: LambdaContext): Promise<EventResult> { this.log.info("Schedule Event: %j", event); let requestId = context && context.awsRequestId || Utils.uuid(); let time = new Date().toISOString(); let req: EventRequest = { type: "event", source: "aws:cloudwatch", application: undefined, service: undefined, method: undefined, requestId, resource: "events", action: event.action, time, object: null, records: [ event ] }; this.log.info("Schedule Request [%s:%s]: %j", req.resource, req.object, req); let result = await super.eventRequest(req); return result; } private async dynamo(event: LambdaDynamoEvent, context: LambdaContext): Promise<EventResult> { this.log.info("Dynamo Event: %j", event); let requestId = context && context.awsRequestId || Utils.uuid(); let time = new Date().toISOString(); let reqs: Record<string, EventRequest> = {}; for (let record of event.Records) { let resource = record.eventSourceARN.split("/")[1]; let object = resource; let action = record.eventName; let group = `${resource}/${action}@${object}`; if (!reqs[group]) reqs[group] = { type: "event", source: "aws:dynamodb", application: undefined, service: undefined, method: undefined, requestId, resource, action, time, object, records: [] }; reqs[group].records.push(record); } // TODO: Iteration of all, combine result let result: EventResult; for (let key in reqs) { let req = reqs[key]; this.log.info("Dynamo Request [%s]: %j", req.resource, req); result = await super.eventRequest(req); } return result; } }
the_stack