text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { GatsbyIterable } from "../../common/iterable" import { DbComparator, DbComparatorValue, DbQuery, dbQueryToDottedField, getFilterStatement, IDbFilterStatement, sortBySpecificity, } from "../../common/query" import { IDataStore, ILmdbDatabases, NodeId } from "../../types" import { IIndexMetadata, IndexFieldValue, IndexKey, undefinedSymbol, } from "./create-index" import { cartesianProduct, matchesFilter } from "./common" import { inspect } from "util" // JS values encoded by ordered-binary never start with 0 or 255 byte export const BinaryInfinityNegative = Buffer.from([0]) export const BinaryInfinityPositive = String.fromCharCode(255).repeat(4) type RangeEdgeAfter = [IndexFieldValue, typeof BinaryInfinityPositive] type RangeEdgeBefore = [typeof undefinedSymbol, IndexFieldValue] type RangeValue = | IndexFieldValue | RangeEdgeAfter | RangeEdgeBefore | typeof BinaryInfinityPositive | typeof BinaryInfinityNegative type RangeBoundary = Array<RangeValue> export interface IIndexEntry { key: IndexKey value: NodeId } interface IIndexRange { start: RangeBoundary end: RangeBoundary } enum ValueEdges { BEFORE = -1, EQ = 0, AFTER = 1, } export interface IFilterArgs { datastore: IDataStore databases: ILmdbDatabases dbQueries: Array<DbQuery> indexMetadata: IIndexMetadata limit?: number skip?: number reverse?: boolean } interface IFilterContext extends IFilterArgs { usedLimit: number | undefined usedSkip: number usedQueries: Set<DbQuery> } export interface IFilterResult { entries: GatsbyIterable<IIndexEntry> usedQueries: Set<DbQuery> usedLimit: number | undefined usedSkip: number } interface ILmdbStoreRangeOptions { start?: any end?: any limit?: number | undefined offset?: number | undefined revers?: boolean snapshot?: boolean } export function filterUsingIndex(args: IFilterArgs): IFilterResult { const context = createFilteringContext(args) const ranges = getIndexRanges(context) let entries = ranges.length > 0 ? performRangeScan(context, ranges) : performFullScan(context) if (context.usedQueries.size !== args.dbQueries.length) { // Try to additionally filter out results using data stored in index entries = narrowResultsIfPossible(context, entries) } if (isMultiKeyIndex(context) && needsDeduplication(context)) { entries = entries.deduplicate(getIdentifier) } return { entries, usedQueries: context.usedQueries, usedLimit: context.usedLimit, usedSkip: context.usedSkip, } } export function countUsingIndexOnly(args: IFilterArgs): number { const context = createFilteringContext(args) const { databases: { indexes }, dbQueries, indexMetadata: { keyPrefix }, } = args const ranges = getIndexRanges(context) if (context.usedQueries.size !== dbQueries.length) { throw new Error(`Cannot count using index only`) } if (isMultiKeyIndex(context) && needsDeduplication(context)) { throw new Error(`Cannot count using MultiKey index.`) } if (ranges.length === 0) { const range: ILmdbStoreRangeOptions = { start: [keyPrefix], end: [getValueEdgeAfter(keyPrefix)], snapshot: false, } return indexes.getKeysCount(range) } let count = 0 for (let { start, end } of ranges) { start = [keyPrefix, ...start] end = [keyPrefix, ...end] // Assuming ranges are not overlapping const range: ILmdbStoreRangeOptions = { start, end, snapshot: false } count += indexes.getKeysCount(range) } return count } function createFilteringContext(args: IFilterArgs): IFilterContext { return { ...args, usedLimit: undefined, usedSkip: 0, usedQueries: new Set<DbQuery>(), } } function isMultiKeyIndex(context: IFilterContext): boolean { return context.indexMetadata.multiKeyFields.length > 0 } function needsDeduplication(context: IFilterContext): boolean { if (!isMultiKeyIndex(context)) { return false } // Deduplication is not needed if all multiKeyFields have applied `eq` filters const fieldsWithAppliedEq = new Set<string>() context.usedQueries.forEach(q => { const filter = getFilterStatement(q) if (filter.comparator === DbComparator.EQ) { fieldsWithAppliedEq.add(dbQueryToDottedField(q)) } }) return context.indexMetadata.multiKeyFields.some( fieldName => !fieldsWithAppliedEq.has(fieldName) ) } function performRangeScan( context: IFilterContext, ranges: Array<IIndexRange> ): GatsbyIterable<IIndexEntry> { const { indexMetadata: { keyPrefix, stats }, reverse, } = context let { limit, skip: offset = 0 } = context if (context.dbQueries.length !== context.usedQueries.size) { // Since this query is not fully satisfied by the index, we can't use limit/skip limit = undefined offset = 0 } if (ranges.length > 1) { // e.g. { in: [1, 2] } // Cannot use offset: we will run several range queries and it's not clear which one to offset // TODO: assuming ranges are sorted and not overlapping it should be possible to use offsets in this case // by running first range query, counting results while lazily iterating and // running the next range query when the previous iterator is done (and count is known) // with offset = offset - previousRangeCount, limit = limit - previousRangeCount limit = typeof limit !== `undefined` ? offset + limit : undefined offset = 0 } if (limit && isMultiKeyIndex(context) && needsDeduplication(context)) { // Cannot use limit: // MultiKey index may contain duplicates - we can only set a safe upper bound limit *= stats.maxKeysPerItem } // Assuming ranges are sorted and not overlapping, we can yield results sequentially const lmdbRanges: Array<ILmdbStoreRangeOptions> = [] for (let { start, end } of ranges) { start = [keyPrefix, ...start] end = [keyPrefix, ...end] const range = !reverse ? { start, end, limit, offset, snapshot: false } : { start: end, end: start, limit, offset, reverse, snapshot: false } lmdbRanges.push(range) } context.usedLimit = limit context.usedSkip = offset return new GatsbyIterable(() => traverseRanges(context, lmdbRanges)) } function performFullScan(context: IFilterContext): GatsbyIterable<IIndexEntry> { // *Caveat*: our old query implementation was putting undefined and null values at the end // of the list when ordered ascending. But lmdb-store keeps them at the top. // So in LMDB case, need to concat two ranges to conform to our old format: // concat(undefinedToEnd, topToUndefined) const { reverse, indexMetadata: { keyPrefix }, } = context let start: RangeBoundary = [keyPrefix, getValueEdgeAfter(undefinedSymbol)] let end: RangeBoundary = [getValueEdgeAfter(keyPrefix)] let range = !reverse ? { start, end, snapshot: false } : { start: end, end: start, reverse, snapshot: false } const undefinedToEnd = range // Concat null/undefined values end = start start = [keyPrefix, null] range = !reverse ? { start, end, snapshot: false } : { start: end, end: start, reverse, snapshot: false } const topToUndefined = range const ranges: Array<ILmdbStoreRangeOptions> = !reverse ? [undefinedToEnd, topToUndefined] : [topToUndefined, undefinedToEnd] return new GatsbyIterable(() => traverseRanges(context, ranges)) } function* traverseRanges( context: IFilterContext, ranges: Array<ILmdbStoreRangeOptions> ): Generator<IIndexEntry> { const { databases: { indexes }, } = context for (const range of ranges) { // @ts-ignore yield* indexes.getRange(range) } } /** * Takes results after the index scan and tries to filter them additionally with unused parts of the query. * * This is O(N) but the advantage is that it uses data available in the index. * So it effectively bypasses the `getNode()` call for such filters (with all associated deserialization complexity). * * Example: * Imagine the index is: { foo: 1, bar: 1 } * * Now we run the query: * sort: [`foo`] * filter: { bar: { eq: `test` }} * * Initial filtering pass will have to perform a full index scan (because `bar` is the last field in the index). * * But we still have values of `bar` stored in the index itself, * so can filter by this value without loading the full node contents. */ function narrowResultsIfPossible( context: IFilterContext, entries: GatsbyIterable<IIndexEntry> ): GatsbyIterable<IIndexEntry> { const { indexMetadata, dbQueries, usedQueries } = context const indexFields = new Map<string, number>() indexMetadata.keyFields.forEach(([fieldName], positionInKey) => { // Every index key is [indexId, field1, field2, ...] and `indexMetadata.keyFields` contains [field1, field2, ...] // As `indexId` is in the first column the fields need to be offset by +1 for correct addressing indexFields.set(fieldName, positionInKey + 1) }) type Filter = [filter: IDbFilterStatement, fieldPositionInIndex: number] const filtersToApply: Array<Filter> = [] for (const query of dbQueries) { const fieldName = dbQueryToDottedField(query) const positionInKey = indexFields.get(fieldName) if (typeof positionInKey === `undefined`) { // No data for this field in index continue } if (usedQueries.has(query)) { // Filter is already applied continue } if (isMultiKeyIndex(context) && isNegatedQuery(query)) { // NE/NIN not supported with MultiKey indexes: // MultiKey indexes include duplicates; negated queries will only filter some of those // but may still incorrectly include others in final results continue } const filter = getFilterStatement(query) filtersToApply.push([filter, positionInKey]) usedQueries.add(query) } return filtersToApply.length === 0 ? entries : entries.filter(({ key }) => { for (const [filter, fieldPositionInIndex] of filtersToApply) { const value = key[fieldPositionInIndex] === undefinedSymbol ? undefined : key[fieldPositionInIndex] if (!matchesFilter(filter, value)) { // Mimic AND semantics return false } } return true }) } /** * Returns query clauses that can potentially use index. * Returned list is sorted by query specificity */ function getSupportedQueries( context: IFilterContext, dbQueries: Array<DbQuery> ): Array<DbQuery> { const isSupported = new Set([ DbComparator.EQ, DbComparator.IN, DbComparator.GTE, DbComparator.LTE, DbComparator.GT, DbComparator.LT, DbComparator.NIN, DbComparator.NE, ]) let supportedQueries = dbQueries.filter(query => isSupported.has(getFilterStatement(query).comparator) ) if (isMultiKeyIndex(context)) { // Note: // NE and NIN are not supported by multi-key indexes. Why? // Imagine a node { id: 1, field: [`foo`, `bar`] } // Then the filter { field: { ne: `foo` } } should completely remove this node from results. // But multikey index contains separate entries for `foo` and `bar` values. // Final range will exclude entry "foo" but it will still include entry for "bar" hence // will incorrectly include our node in results. supportedQueries = supportedQueries.filter(query => !isNegatedQuery(query)) } return sortBySpecificity(supportedQueries) } function isEqualityQuery(query: DbQuery): boolean { const filter = getFilterStatement(query) return ( filter.comparator === DbComparator.EQ || filter.comparator === DbComparator.IN ) } function isNegatedQuery(query: DbQuery): boolean { const filter = getFilterStatement(query) return ( filter.comparator === DbComparator.NE || filter.comparator === DbComparator.NIN ) } export function getIndexRanges(context: IFilterContext): Array<IIndexRange> { const { dbQueries, indexMetadata: { keyFields }, } = context const rangeStarts: Array<RangeBoundary> = [] const rangeEndings: Array<RangeBoundary> = [] const supportedQueries = getSupportedQueries(context, dbQueries) for (const indexFieldInfo of new Map(keyFields)) { const query = getMostSpecificQuery(supportedQueries, indexFieldInfo) if (!query) { // Use index prefix, not all index fields break } const result = resolveIndexFieldRanges(context, query, indexFieldInfo) rangeStarts.push(result.rangeStarts) rangeEndings.push(result.rangeEndings) if (!isEqualityQuery(query)) { // Compound index { a: 1, b: 1, c: 1 } supports only one non-eq (range) operator. E.g.: // Supported: { a: { eq: `foo` }, b: { eq: 8 }, c: { gt: 5 } } // Not supported: { a: { eq: `foo` }, b: { gt: 5 }, c: { eq: 5 } } // (or to be precise, can do a range scan only for { a: { eq: `foo` }, b: { gt: 5 } }) break } } if (!rangeStarts.length) { return [] } // Only the last segment encloses the whole range. // For example, given an index { a: 1, b: 1 } and a filter { a: { eq: `foo` }, b: { eq: `bar` } }, // It should produce this range: // { // start: [`foo`, `bar`], // end: [`foo`, [`bar`, BinaryInfinityPositive]] // } // // Not this: // { // start: [`foo`, `bar`], // end: [[`foo`, BinaryInfinityPositive], [`bar`, BinaryInfinityPositive]] // } for (let i = 0; i < rangeStarts.length - 1; i++) { rangeEndings[i] = rangeStarts[i] } // Example: // rangeStarts: [ // [field1Start1, field1Start2], // [field2Start1], // ] // rangeEnds: [ // [field1End1, field1End2], // [field2End1], // ] // Need: // rangeStartsProduct: [ // [field1Start1, field2Start1], // [field1Start2, field2Start1], // ] // rangeEndingsProduct: [ // [field1End1, field2End1], // [field1End2, field2End1], // ] const rangeStartsProduct = cartesianProduct(...rangeStarts) const rangeEndingsProduct = cartesianProduct(...rangeEndings) const ranges: Array<IIndexRange> = [] for (let i = 0; i < rangeStartsProduct.length; i++) { ranges.push({ start: rangeStartsProduct[i], end: rangeEndingsProduct[i], }) } // TODO: sort and intersect ranges. Also, we may want this at some point: // https://docs.mongodb.com/manual/core/multikey-index-bounds/ return ranges } function getFieldQueries( queries: Array<DbQuery>, fieldName: string ): Array<DbQuery> { return queries.filter(q => dbQueryToDottedField(q) === fieldName) } function getMostSpecificQuery( queries: Array<DbQuery>, [indexField]: [fieldName: string, sortDirection: number] ): DbQuery | undefined { const fieldQueries = getFieldQueries(queries, indexField) // Assuming queries are sorted by specificity, the best bet is to pick the first query return fieldQueries[0] } function resolveIndexFieldRanges( context: IFilterContext, query: DbQuery, [field, sortDirection]: [fieldName: string, sortDirection: number] ): { rangeStarts: RangeBoundary rangeEndings: RangeBoundary } { // Tracking starts and ends separately instead of doing Array<[start, end]> // to simplify cartesian product creation later const rangeStarts: RangeBoundary = [] const rangeEndings: RangeBoundary = [] const filter = getFilterStatement(query) if (filter.comparator === DbComparator.IN && !Array.isArray(filter.value)) { throw new Error("The argument to the `in` predicate should be an array") } context.usedQueries.add(query) switch (filter.comparator) { case DbComparator.EQ: case DbComparator.IN: { const arr = Array.isArray(filter.value) ? [...filter.value] : [filter.value] // Sort ranges by index sort direction arr.sort((a: any, b: any): number => { if (a === b) return 0 if (sortDirection === 1) return a > b ? 1 : -1 return a < b ? 1 : -1 }) let hasNull = false for (const item of new Set(arr)) { const value = toIndexFieldValue(item, filter) if (value === null) hasNull = true rangeStarts.push(value) rangeEndings.push(getValueEdgeAfter(value)) } // Special case: { eq: null } or { in: [null, `any`]} must also include values for undefined! if (hasNull) { rangeStarts.push(undefinedSymbol) rangeEndings.push(getValueEdgeAfter(undefinedSymbol)) } break } case DbComparator.LT: case DbComparator.LTE: { if (Array.isArray(filter.value)) throw new Error(`${filter.comparator} value must not be an array`) const value = toIndexFieldValue(filter.value, filter) const end = filter.comparator === DbComparator.LT ? value : getValueEdgeAfter(value) // Try to find matching GTE/GT filter const start = resolveRangeEdge(context, field, DbComparator.GTE) ?? resolveRangeEdge(context, field, DbComparator.GT, ValueEdges.AFTER) // Do not include null or undefined in results unless null was requested explicitly // // Index ordering: // BinaryInfinityNegative // null // Symbol(`undef`) // -10 // 10 // `Hello` // [`Hello`] // BinaryInfinityPositive const rangeHead = value === null ? BinaryInfinityNegative : getValueEdgeAfter(undefinedSymbol) rangeStarts.push(start ?? rangeHead) rangeEndings.push(end) break } case DbComparator.GT: case DbComparator.GTE: { if (Array.isArray(filter.value)) throw new Error(`${filter.comparator} value must not be an array`) const value = toIndexFieldValue(filter.value, filter) const start = filter.comparator === DbComparator.GTE ? value : getValueEdgeAfter(value) // Try to find matching LT/LTE const end = resolveRangeEdge(context, field, DbComparator.LTE, ValueEdges.AFTER) ?? resolveRangeEdge(context, field, DbComparator.LT) const rangeTail = value === null ? getValueEdgeAfter(null) : BinaryInfinityPositive rangeStarts.push(start) rangeEndings.push(end ?? rangeTail) break } case DbComparator.NE: case DbComparator.NIN: { const arr = Array.isArray(filter.value) ? [...filter.value] : [filter.value] // Sort ranges by index sort direction arr.sort((a: any, b: any): number => { if (a === b) return 0 if (sortDirection === 1) return a > b ? 1 : -1 return a < b ? 1 : -1 }) const hasNull = arr.some(value => value === null) if (hasNull) { rangeStarts.push(getValueEdgeAfter(undefinedSymbol)) } else { rangeStarts.push(BinaryInfinityNegative) } for (const item of new Set(arr)) { const value = toIndexFieldValue(item, filter) if (value === null) continue // already handled via hasNull case above rangeEndings.push(value) rangeStarts.push(getValueEdgeAfter(value)) } rangeEndings.push(BinaryInfinityPositive) break } default: throw new Error(`Unsupported predicate: ${filter.comparator}`) } return { rangeStarts, rangeEndings } } function resolveRangeEdge( context: IFilterContext, indexField: string, predicate: DbComparator, edge: ValueEdges = ValueEdges.EQ ): IndexFieldValue | RangeEdgeBefore | RangeEdgeAfter | undefined { const fieldQueries = getFieldQueries(context.dbQueries, indexField) for (const dbQuery of fieldQueries) { if (context.usedQueries.has(dbQuery)) { continue } const filterStatement = getFilterStatement(dbQuery) if (filterStatement.comparator !== predicate) { continue } context.usedQueries.add(dbQuery) const value = filterStatement.value if (Array.isArray(value)) { throw new Error(`Range filter ${predicate} should not have array value`) } if (typeof value === `object` && value !== null) { throw new Error( `Range filter ${predicate} should not have value of type ${typeof value}` ) } if (edge === 0) { return value } return edge < 0 ? getValueEdgeBefore(value) : getValueEdgeAfter(value) } return undefined } /** * Returns the edge after the given value, suitable for lmdb range queries. * * Example: * Get all items from index starting with ["foo"] prefix up to the next existing prefix: * * ```js * db.getRange({ start: ["foo"], end: [getValueEdgeAfter("foo")] }) * ``` * * This method relies on ordered-binary format used by lmdb-store to persist keys * and assumes keys are composite and represented as arrays. * * Implementation detail: ordered-binary treats `null` as multipart separator within binary sequence */ function getValueEdgeAfter(value: IndexFieldValue): RangeEdgeAfter { return [value, BinaryInfinityPositive] } function getValueEdgeBefore(value: IndexFieldValue): RangeEdgeBefore { return [undefinedSymbol, value] } function toIndexFieldValue( filterValue: DbComparatorValue, filter: IDbFilterStatement ): IndexFieldValue { if (typeof filterValue === `object` && filterValue !== null) { throw new Error( `Bad filter value for predicate ${filter.comparator}: ${inspect( filter.value )}` ) } return filterValue } function getIdentifier(entry: IIndexEntry): number | string { const id = entry.key[entry.key.length - 1] if (typeof id !== `number` && typeof id !== `string`) { const out = inspect(id) throw new Error( `Last element of index key is expected to be numeric or string id, got ${out}` ) } return id }
the_stack
import fs from "fs"; import path from "path"; import { prettyPrint } from "recast"; import { Type, builders as b, namedTypes as n, getBuilderName, } from "../main"; const Op = Object.prototype; const hasOwn = Op.hasOwnProperty; const RESERVED_WORDS: { [reservedWord: string]: boolean | undefined } = { extends: true, default: true, arguments: true, static: true, }; const NAMED_TYPES_ID = b.identifier("namedTypes"); const NAMED_TYPES_IMPORT = b.importDeclaration( [b.importSpecifier(NAMED_TYPES_ID)], b.stringLiteral("./namedTypes"), ); const KINDS_ID = b.identifier("K"); const KINDS_IMPORT = b.importDeclaration( [b.importNamespaceSpecifier(KINDS_ID)], b.stringLiteral("./kinds") ); const supertypeToSubtypes = getSupertypeToSubtypes(); const builderTypeNames = getBuilderTypeNames(); const out = [ { file: "kinds.ts", ast: moduleWithBody([ NAMED_TYPES_IMPORT, ...Object.keys(supertypeToSubtypes).map(supertype => { const buildableSubtypes = getBuildableSubtypes(supertype); if (buildableSubtypes.length === 0) { // Some of the XML* types don't have buildable subtypes, // so fall back to using the supertype's node type return b.exportNamedDeclaration( b.tsTypeAliasDeclaration( b.identifier(`${supertype}Kind`), b.tsTypeReference(b.tsQualifiedName(NAMED_TYPES_ID, b.identifier(supertype))) ) ); } return b.exportNamedDeclaration( b.tsTypeAliasDeclaration( b.identifier(`${supertype}Kind`), b.tsUnionType(buildableSubtypes.map(subtype => b.tsTypeReference(b.tsQualifiedName(NAMED_TYPES_ID, b.identifier(subtype))) )) ) ); }), ]), }, { file: "namedTypes.ts", ast: moduleWithBody([ b.importDeclaration([b.importSpecifier(b.identifier("Omit"))], b.stringLiteral("../types")), b.importDeclaration([b.importSpecifier(b.identifier("Type"))], b.stringLiteral("../lib/types")), KINDS_IMPORT, b.exportNamedDeclaration( b.tsModuleDeclaration( b.identifier("namedTypes"), b.tsModuleBlock([ ...Object.keys(n).map(typeName => { const typeDef = Type.def(typeName); const ownFieldNames = Object.keys(typeDef.ownFields); return b.exportNamedDeclaration( b.tsInterfaceDeclaration.from({ id: b.identifier(typeName), extends: typeDef.baseNames.map(baseName => { const baseDef = Type.def(baseName); const commonFieldNames = ownFieldNames .filter(fieldName => !!baseDef.allFields[fieldName]); if (commonFieldNames.length > 0) { return b.tsExpressionWithTypeArguments( b.identifier("Omit"), b.tsTypeParameterInstantiation([ b.tsTypeReference(b.identifier(baseName)), b.tsUnionType( commonFieldNames.map(fieldName => b.tsLiteralType(b.stringLiteral(fieldName)) ) ), ]) ); } else { return b.tsExpressionWithTypeArguments(b.identifier(baseName)); } }), body: b.tsInterfaceBody( ownFieldNames.map(fieldName => { const field = typeDef.allFields[fieldName]; if (field.name === "type" && field.defaultFn) { return b.tsPropertySignature( b.identifier("type"), b.tsTypeAnnotation(b.tsLiteralType(b.stringLiteral(field.defaultFn()))) ); } else if (field.defaultFn) { return b.tsPropertySignature( b.identifier(field.name), b.tsTypeAnnotation(getTSTypeAnnotation(field.type)), true, // optional ); } return b.tsPropertySignature( b.identifier(field.name), b.tsTypeAnnotation(getTSTypeAnnotation(field.type)) ); }) ), }) ); }), b.exportNamedDeclaration( b.tsTypeAliasDeclaration( b.identifier("ASTNode"), b.tsUnionType( Object.keys(n) .filter(typeName => Type.def(typeName).buildable) .map(typeName => b.tsTypeReference(b.identifier(typeName))), ) ) ), ...Object.keys(n).map(typeName => b.exportNamedDeclaration( b.variableDeclaration("let", [ b.variableDeclarator( b.identifier.from({ name: typeName, typeAnnotation: b.tsTypeAnnotation( b.tsTypeReference( b.identifier("Type"), b.tsTypeParameterInstantiation([ b.tsTypeReference( b.identifier(typeName), ), ]), ), ), }), ), ]), ), ), ]), ) ), b.exportNamedDeclaration( b.tsInterfaceDeclaration( b.identifier("NamedTypes"), b.tsInterfaceBody( Object.keys(n).map(typeName => b.tsPropertySignature( b.identifier(typeName), b.tsTypeAnnotation( b.tsTypeReference( b.identifier("Type"), b.tsTypeParameterInstantiation([ b.tsTypeReference(b.tsQualifiedName( b.identifier("namedTypes"), b.identifier(typeName), )), ]) ) ) ) ) ) ) ), ]), }, { file: "builders.ts", ast: moduleWithBody([ KINDS_IMPORT, NAMED_TYPES_IMPORT, ...builderTypeNames.map(typeName => { const typeDef = Type.def(typeName); const returnType = b.tsTypeAnnotation( b.tsTypeReference(b.tsQualifiedName(NAMED_TYPES_ID, b.identifier(typeName))) ); const buildParamAllowsUndefined: { [buildParam: string]: boolean } = {}; const buildParamIsOptional: { [buildParam: string]: boolean } = {}; [...typeDef.buildParams].reverse().forEach((cur, i, arr) => { const field = typeDef.allFields[cur]; if (field && field.defaultFn) { if (i === 0) { buildParamIsOptional[cur] = true; } else { if (buildParamIsOptional[arr[i - 1]]) { buildParamIsOptional[cur] = true; } else { buildParamAllowsUndefined[cur] = true; } } } }); return b.exportNamedDeclaration( b.tsInterfaceDeclaration( b.identifier(`${typeName}Builder`), b.tsInterfaceBody([ b.tsCallSignatureDeclaration( typeDef.buildParams .filter(buildParam => !!typeDef.allFields[buildParam]) .map(buildParam => { const field = typeDef.allFields[buildParam]; const name = RESERVED_WORDS[buildParam] ? `${buildParam}Param` : buildParam; return b.identifier.from({ name, typeAnnotation: b.tsTypeAnnotation( !!buildParamAllowsUndefined[buildParam] ? b.tsUnionType([getTSTypeAnnotation(field.type), b.tsUndefinedKeyword()]) : getTSTypeAnnotation(field.type) ), optional: !!buildParamIsOptional[buildParam], }); }), returnType ), b.tsMethodSignature( b.identifier("from"), [ b.identifier.from({ name: "params", typeAnnotation: b.tsTypeAnnotation( b.tsTypeLiteral( Object.keys(typeDef.allFields) .filter(fieldName => fieldName !== "type") .sort() // Sort field name strings lexicographically. .map(fieldName => { const field = typeDef.allFields[fieldName]; return b.tsPropertySignature( b.identifier(field.name), b.tsTypeAnnotation(getTSTypeAnnotation(field.type)), field.defaultFn != null || field.hidden ); }) ) ), }), ], returnType ), ]) ) ); }), b.exportNamedDeclaration( b.tsInterfaceDeclaration( b.identifier("builders"), b.tsInterfaceBody([ ...builderTypeNames.map(typeName => b.tsPropertySignature( b.identifier(getBuilderName(typeName)), b.tsTypeAnnotation(b.tsTypeReference(b.identifier(`${typeName}Builder`))) ) ), b.tsIndexSignature( [ b.identifier.from({ name: "builderName", typeAnnotation: b.tsTypeAnnotation(b.tsStringKeyword()), }), ], b.tsTypeAnnotation(b.tsAnyKeyword()) ), ]) ) ), ]), }, { file: "visitor.ts", ast: moduleWithBody([ b.importDeclaration( [b.importSpecifier(b.identifier("NodePath"))], b.stringLiteral("../lib/node-path") ), b.importDeclaration( [b.importSpecifier(b.identifier("Context"))], b.stringLiteral("../lib/path-visitor") ), NAMED_TYPES_IMPORT, b.exportNamedDeclaration( b.tsInterfaceDeclaration.from({ id: b.identifier("Visitor"), typeParameters: b.tsTypeParameterDeclaration([ b.tsTypeParameter("M", undefined, b.tsTypeLiteral([])), ]), body: b.tsInterfaceBody([ ...Object.keys(n).map(typeName => { return b.tsMethodSignature.from({ key: b.identifier(`visit${typeName}`), parameters: [ b.identifier.from({ name: "this", typeAnnotation: b.tsTypeAnnotation( b.tsIntersectionType([ b.tsTypeReference(b.identifier("Context")), b.tsTypeReference(b.identifier("M")), ]) ), }), b.identifier.from({ name: "path", typeAnnotation: b.tsTypeAnnotation( b.tsTypeReference( b.identifier("NodePath"), b.tsTypeParameterInstantiation([ b.tsTypeReference(b.tsQualifiedName(NAMED_TYPES_ID, b.identifier(typeName))), ]) ) ), }), ], optional: true, typeAnnotation: b.tsTypeAnnotation(b.tsAnyKeyword()), }); }), ]), }) ), ]), }, ]; out.forEach(({ file, ast }) => { fs.writeFileSync( path.resolve(__dirname, `../gen/${file}`), prettyPrint(ast, { tabWidth: 2, includeComments: true }).code ); }); function moduleWithBody(body: any[]) { return b.file.from({ comments: [b.commentBlock(" !!! THIS FILE WAS AUTO-GENERATED BY `npm run gen` !!! ")], program: b.program(body), }); } function getSupertypeToSubtypes() { const supertypeToSubtypes: { [supertypeName: string]: string[] } = {}; Object.keys(n).map(typeName => { Type.def(typeName).supertypeList.forEach(supertypeName => { supertypeToSubtypes[supertypeName] = supertypeToSubtypes[supertypeName] || []; supertypeToSubtypes[supertypeName].push(typeName); }); }); return supertypeToSubtypes; } function getBuilderTypeNames() { return Object.keys(n).filter(typeName => { const typeDef = Type.def(typeName); const builderName = getBuilderName(typeName); return !!typeDef.buildParams && !!(b as any)[builderName]; }); } function getBuildableSubtypes(supertype: string): string[] { return Array.from(new Set( Object.keys(n).filter(typeName => { const typeDef = Type.def(typeName); return typeDef.allSupertypes[supertype] != null && typeDef.buildable; }) )); } function getTSTypeAnnotation(type: import("../lib/types").Type<any>): any { switch (type.kind) { case "ArrayType": { const elemTypeAnnotation = getTSTypeAnnotation(type.elemType); // TODO Improve this test. return n.TSUnionType.check(elemTypeAnnotation) ? b.tsArrayType(b.tsParenthesizedType(elemTypeAnnotation)) : b.tsArrayType(elemTypeAnnotation); } case "IdentityType": { if (type.value === null) { return b.tsNullKeyword(); } switch (typeof type.value) { case "undefined": return b.tsUndefinedKeyword(); case "string": return b.tsLiteralType(b.stringLiteral(type.value)); case "boolean": return b.tsLiteralType(b.booleanLiteral(type.value)); case "number": return b.tsNumberKeyword(); case "object": return b.tsObjectKeyword(); case "function": return b.tsFunctionType([]); case "symbol": return b.tsSymbolKeyword(); default: return b.tsAnyKeyword(); } } case "ObjectType": { return b.tsTypeLiteral( type.fields.map(field => b.tsPropertySignature( b.identifier(field.name), b.tsTypeAnnotation(getTSTypeAnnotation(field.type)) ) ) ); } case "OrType": { return b.tsUnionType(type.types.map(type => getTSTypeAnnotation(type))); } case "PredicateType": { if (typeof type.name !== "string") { return b.tsAnyKeyword(); } if (hasOwn.call(n, type.name)) { return b.tsTypeReference(b.tsQualifiedName(KINDS_ID, b.identifier(`${type.name}Kind`))); } if (/^[$A-Z_][a-z0-9_$]*$/i.test(type.name)) { return b.tsTypeReference(b.identifier(type.name)); } if (/^number [<>=]+ \d+$/.test(type.name)) { return b.tsNumberKeyword(); } // Not much else to do... return b.tsAnyKeyword(); } default: return assertNever(type); } } function assertNever(x: never): never { throw new Error("Unexpected: " + x); }
the_stack
import GoldenLayout from "@glue42/golden-layout"; export type ComponentState = GoldenLayout.Component["config"]["componentState"]; export type ParentItem = WorkspaceItem | RowItem | ColumnItem | GroupItem; export type AnyItem = ParentItem | WindowItem; export interface WorkspaceItem { id?: string; type?: "workspace"; children: Array<RowItem | ColumnItem | GroupItem | WindowItem>; config?: { name?: string; context?: object; reuseWorkspaceId?: string; minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; allowDrop?: boolean; allowExtract?: boolean; showEjectButtons?: boolean; allowSplitters?: boolean; showWindowCloseButtons?: boolean; showAddWindowButtons?: boolean; [k: string]: any; }; } export interface GroupItem { id?: string; type: "group"; children: WindowItem[]; config?: { allowDrop?: boolean; allowExtract?: boolean; showEjectButton?: boolean; showMaximizeButton?: boolean; showAddWindowButton?: boolean; minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; [k: string]: any; }; } export interface WindowItem { id: string; type: "window"; config: { url: string; appName: string; windowId?: string; isMaximized: boolean; isLoaded: boolean; isFocused: boolean; workspaceId?: string; frameId?: string; positionIndex?: number; title?: string; context?: string; allowExtract?: boolean; showCloseButton?: boolean; minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; }; } export interface RowItem { id?: string; type: "row"; children: Array<RowItem | ColumnItem | GroupItem | WindowItem>; config?: { allowDrop?: boolean; minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; [k: string]: any; }; } export interface ColumnItem { id?: string; type: "column"; children: Array<RowItem | ColumnItem | GroupItem | WindowItem>; config?: { allowDrop?: boolean; minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; [k: string]: any; }; } export interface WorkspaceSummary { id: string; config: WorkspaceConfig; } export interface WorkspaceConfig { frameId: string; title: string; positionIndex: number; name: string; layoutName?: string; isHibernated: boolean; isSelected: boolean; lastActive: number; } export interface WindowSummary { itemId: string; parentId: string; config: { frameId: string; workspaceId: string; positionIndex: number; windowId?: string; isMaximized: boolean; isLoaded: boolean; isFocused: boolean; appName: string; url: string; allowExtract?: boolean; showCloseButton?: boolean; title: string; minWidth: number; maxWidth: number; minHeight: number; maxHeight: number; widthInPx: number; heightInPx: number; }; } export interface ContainerSummary { itemId: string; type: "group" | "column" | "row" | "workspace"; config: { frameId: string; workspaceId: string; positionIndex: number; allowDrop: boolean; allowDropHeader?: boolean; allowDropLeft?: boolean; allowDropTop?: boolean; allowDropRight?: boolean; allowDropBottom?: boolean; allowExtract?: boolean; showMaximizeButton?: boolean; showEjectButton?: boolean; showAddWindowButton?: boolean; allowSplitters?: boolean; minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; widthInPx?: number; heightInPx?: number; isPinned?: boolean; isMaximized: boolean; }; } export interface FrameSummary { id: string; } export interface WorkspaceSnapshot { id: string; config: object; children: object; frameSummary: FrameSummary; } export interface WindowAddedArgs { newWindow: Window; windows: Window[]; } export interface Bounds { left: number; width: number; top: number; height: number; } export interface Size { width: number; height: number; } export interface Window { id: string; bounds?: Bounds; appName?: string; windowId?: string; url?: string; } export interface Workspace { id: string; windows: Window[]; hibernatedWindows: Window[]; layout: GoldenLayout; hibernateConfig?: GoldenLayout.Config; context?: object; lastActive: number; } export interface WorkspaceLayout { name: string; type: "Workspace"; metadata?: object; components: Array<{ type: "Workspace"; state: WorkspaceItem }>; } export interface FrameLayoutConfig { workspaceLayout: GoldenLayout.Config; workspaceConfigs: Array<{ id: string; config: GoldenLayout.Config }>; frameId: string; showLoadingIndicator?: boolean; } export interface WindowDefinition { appName?: string; url?: string; windowId?: string; context?: object; config?: { showCloseButton?: boolean; allowExtract?: boolean; minWidth?: number; minHeight?: number; maxWidth?: number; maxHeight?: number; }; } export interface StartupConfig { emptyFrame: boolean; disableCustomButtons: boolean; workspaceName?: string; workspaceNames?: string[]; context?: object; build: boolean; } export interface APIWIndowSettings { id: string | string[]; windowId: string; isMaximized: boolean; isFocused: boolean; appName?: string; url?: string; workspaceId: string; frameId: string; title: string; positionIndex: number; allowExtract: boolean; showCloseButton: boolean; minWidth: number; minHeight: number; maxWidth: number; maxHeight: number; widthInPx: number; heightInPx: number; } export interface GDWindowOptions { windowId: string; id?: string; appName?: string; url?: string; title?: string; context?: object; allowExtract: boolean; showCloseButton: boolean; minWidth: number; maxWidth: number; minHeight: number; maxHeight: number; } export interface SavedConfigWithData { config: GoldenLayout.Config; layoutData: { metadata: object; name: string; context: object; }; } export interface SaveWorkspaceConfig { title?: string; workspace: Workspace; name: string; saveContext?: boolean; metadata?:object; } export interface WorkspaceDropOptions { allowDrop?: boolean; allowDropLeft?: boolean; allowDropTop?: boolean; allowDropRight?: boolean; allowDropBottom?: boolean; } export interface ComponentFactory { createLogo?: (options: { domNode: HTMLElement }, frameId: string) => void; createAddWorkspace?: (options: { domNode: HTMLElement }, frameId: string) => void; createSystemButtons?: (options: { domNode: HTMLElement }, frameId: string) => void; createWorkspaceContents?: (options: { domNode: HTMLElement, workspaceId: string }) => void; createAddApplicationPopup?: (options: AddApplicationPopupOptions) => void; createSaveWorkspacePopup?: (options: SaveWorkspacePopupOptions) => void; createAddWorkspacePopup?: (options: OpenWorkspacePopupOptions) => void; hideSystemPopups?: (cb: () => void) => void; } export interface DecoratedComponentFactory { createLogo?: (options: { domNode: HTMLElement }) => void; createAddWorkspace?: (options: { domNode: HTMLElement }) => void; createSystemButtons?: (options: { domNode: HTMLElement }) => void; createWorkspaceContents?: (options: { domNode: HTMLElement, workspaceId: string }) => void; createAddApplicationPopup?: (options: AddApplicationPopupOptions) => void; createSaveWorkspacePopup?: (options: SaveWorkspacePopupOptions) => void; createAddWorkspacePopup?: (options: OpenWorkspacePopupOptions) => void; hideSystemPopups?: (cb: () => void) => void; } interface BasePayloadOptions { domNode: HTMLElement; resizePopup: (size: any) => void; hidePopup: () => void; callback?: () => void; frameId: string; } export interface AddApplicationPopupOptions extends BasePayloadOptions { boxId: string; workspaceId: string; parentType?: string; } export interface SaveWorkspacePopupOptions extends BasePayloadOptions { workspaceId: string; buildMode: boolean; } // tslint:disable-next-line: no-empty-interface export interface OpenWorkspacePopupOptions extends BasePayloadOptions { } export interface VisibilityState { logo: [options: { domNode: HTMLElement }, frameId: string], addWorkspace: [options: { domNode: HTMLElement }, frameId: string], systemButtons: [options: { domNode: HTMLElement }, frameId: string], workspaceContents: Array<[options: { domNode: HTMLElement, workspaceId: string }]> } export type WorkspaceOptionsWithTitle = GoldenLayout.WorkspacesOptions & { title?: string }; export type WorkspaceOptionsWithLayoutName = GoldenLayout.WorkspacesOptions & { layoutName?: string }; export type LayoutWithMaximizedItem = GoldenLayout & { _maximizedItem?: GoldenLayout.ContentItem }; export interface MaximumActiveWorkspacesRule { threshold: number; } export interface IdleWorkspacesRule { idleMSThreshold: number; } export interface WorkspacesHibernationConfig { maximumActiveWorkspaces?: MaximumActiveWorkspacesRule; idleWorkspaces?: IdleWorkspacesRule; } export type LoadingStrategy = "direct" | "delayed" | "lazy"; export interface WorkspacesLoadingConfig { /** * Default restore strategy when restoring Swimlane workspaces. */ defaultStrategy?: LoadingStrategy; delayed: { /** * Valid only in `delayed` mode. Initial period after which to start loading applications in batches. */ initialOffsetInterval?: number; /** * Valid only in `delayed` mode. Interval in minutes at which to load the application batches. */ interval?: number; /** * Valid only in `delayed` mode. Number of applications in a batch to be loaded at each interval. */ batch?: number; } /** * Visual indicator `Zzz` on tabs of apps which are not loaded yet. Useful for developing and testing purposes. */ showDelayedIndicator?: boolean; } export interface WorkspacesSystemConfig { src: string; hibernation?: WorkspacesHibernationConfig; loadingStrategy?: WorkspacesLoadingConfig; } export interface Constraints { minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; }
the_stack
import { Vector2 } from "three"; import { clamp01, distance, lerp, repeat } from "../utils/ToolSet"; import { CurveType, GPathPoint } from "./GPathPoint"; export class GPath { private _segments: Array<Segment>; private _points: Array<Vector2>; private _fullLength: number; constructor() { this._segments = new Array<Segment>(); this._points = new Array<Vector2>(); } public get length(): number { return this._fullLength; } public create2(pt1: GPathPoint, pt2: GPathPoint, pt3?: GPathPoint, pt4?: GPathPoint): void { var points: Array<GPathPoint> = new Array<GPathPoint>(); points.push(pt1); points.push(pt2); if (pt3) points.push(pt3); if (pt4) points.push(pt4); this.create(points); } public create(points: Array<GPathPoint>): void { this._segments.length = 0; this._points.length = 0; this._fullLength = 0; var cnt: number = points.length; if (cnt == 0) return; var splinePoints: Array<Vector2> = []; var prev: GPathPoint = points[0]; if (prev.curveType == CurveType.CRSpline) splinePoints.push(new Vector2(prev.x, prev.y)); for (var i: number = 1; i < cnt; i++) { var current: GPathPoint = points[i]; if (prev.curveType != CurveType.CRSpline) { var seg: Segment = {}; seg.type = prev.curveType; seg.ptStart = this._points.length; if (prev.curveType == CurveType.Straight) { seg.ptCount = 2; this._points.push(new Vector2(prev.x, prev.y)); this._points.push(new Vector2(current.x, current.y)); } else if (prev.curveType == CurveType.Bezier) { seg.ptCount = 3; this._points.push(new Vector2(prev.x, prev.y)); this._points.push(new Vector2(current.x, current.y)); this._points.push(new Vector2(prev.control1_x, prev.control1_y)); } else if (prev.curveType == CurveType.CubicBezier) { seg.ptCount = 4; this._points.push(new Vector2(prev.x, prev.y)); this._points.push(new Vector2(current.x, current.y)); this._points.push(new Vector2(prev.control1_x, prev.control1_y)); this._points.push(new Vector2(prev.control2_x, prev.control2_y)); } seg.length = distance(prev.x, prev.y, current.x, current.y); this._fullLength += seg.length; this._segments.push(seg); } if (current.curveType != CurveType.CRSpline) { if (splinePoints.length > 0) { splinePoints.push(new Vector2(current.x, current.y)); this.createSplineSegment(splinePoints); } } else splinePoints.push(new Vector2(current.x, current.y)); prev = current; } if (splinePoints.length > 1) this.createSplineSegment(splinePoints); } private createSplineSegment(splinePoints: Array<Vector2>): void { var cnt: number = splinePoints.length; splinePoints.splice(0, 0, splinePoints[0]); splinePoints.push(splinePoints[cnt]); splinePoints.push(splinePoints[cnt]); cnt += 3; var seg: Segment = {}; seg.type = CurveType.CRSpline; seg.ptStart = this._points.length; seg.ptCount = cnt; this._points = this._points.concat(splinePoints); seg.length = 0; for (var i: number = 1; i < cnt; i++) { seg.length += distance(splinePoints[i - 1].x, splinePoints[i - 1].y, splinePoints[i].x, splinePoints[i].y); } this._fullLength += seg.length; this._segments.push(seg); splinePoints.length = 0; } public clear(): void { this._segments.length = 0; this._points.length = 0; } public getPointAt(t: number, result?: Vector2): Vector2 { if (!result) result = new Vector2(); else result.set(0, 0); t = clamp01(t); var cnt: number = this._segments.length; if (cnt == 0) { return result; } var seg: Segment; if (t == 1) { seg = this._segments[cnt - 1]; if (seg.type == CurveType.Straight) { result.x = lerp(this._points[seg.ptStart].x, this._points[seg.ptStart + 1].x, t); result.y = lerp(this._points[seg.ptStart].y, this._points[seg.ptStart + 1].y, t); return result; } else if (seg.type == CurveType.Bezier || seg.type == CurveType.CubicBezier) return this.onBezierCurve(seg.ptStart, seg.ptCount, t, result); else return this.onCRSplineCurve(seg.ptStart, seg.ptCount, t, result); } var len: number = t * this._fullLength; for (var i: number = 0; i < cnt; i++) { seg = this._segments[i]; len -= seg.length; if (len < 0) { t = 1 + len / seg.length; if (seg.type == CurveType.Straight) { result.x = lerp(this._points[seg.ptStart].x, this._points[seg.ptStart + 1].x, t); result.y = lerp(this._points[seg.ptStart].y, this._points[seg.ptStart + 1].y, t); } else if (seg.type == CurveType.Bezier || seg.type == CurveType.CubicBezier) result = this.onBezierCurve(seg.ptStart, seg.ptCount, t, result); else result = this.onCRSplineCurve(seg.ptStart, seg.ptCount, t, result); break; } } return result; } public get segmentCount(): number { return this._segments.length; } public getAnchorsInSegment(segmentIndex: number, points?: Array<Vector2>): Array<Vector2> { if (points == null) points = new Array<Vector2>(); var seg: Segment = this._segments[segmentIndex]; for (var i: number = 0; i < seg.ptCount; i++) points.push(new Vector2(this._points[seg.ptStart + i].x, this._points[seg.ptStart + i].y)); return points; } public getPointsInSegment(segmentIndex: number, t0: number, t1: number, points?: Array<Vector2>, ts?: Array<number>, pointDensity?: number): Array<Vector2> { if (points == null) points = new Array<Vector2>(); if (!pointDensity || isNaN(pointDensity)) pointDensity = 0.1; if (ts) ts.push(t0); var seg: Segment = this._segments[segmentIndex]; if (seg.type == CurveType.Straight) { points.push(new Vector2(lerp(this._points[seg.ptStart].x, this._points[seg.ptStart + 1].x, t0), lerp(this._points[seg.ptStart].y, this._points[seg.ptStart + 1].y, t0))); points.push(new Vector2(lerp(this._points[seg.ptStart].x, this._points[seg.ptStart + 1].x, t1), lerp(this._points[seg.ptStart].y, this._points[seg.ptStart + 1].y, t1))); } else { var func: Function; if (seg.type == CurveType.Bezier || seg.type == CurveType.CubicBezier) func = this.onBezierCurve; else func = this.onCRSplineCurve; points.push(func.call(this, seg.ptStart, seg.ptCount, t0, new Vector2())); var SmoothAmount: number = Math.min(seg.length * pointDensity, 50); for (var j: number = 0; j <= SmoothAmount; j++) { var t: number = j / SmoothAmount; if (t > t0 && t < t1) { points.push(func.call(this, seg.ptStart, seg.ptCount, t, new Vector2())); if (ts) ts.push(t); } } points.push(func.call(this, seg.ptStart, seg.ptCount, t1, new Vector2())); } if (ts) ts.push(t1); return points; } public getAllPoints(points?: Array<Vector2>, ts?: Array<number>, pointDensity?: number): Array<Vector2> { if (points == null) points = new Array<Vector2>(); if (!pointDensity || isNaN(pointDensity)) pointDensity = 0.1; var cnt: number = this._segments.length; for (var i: number = 0; i < cnt; i++) this.getPointsInSegment(i, 0, 1, points, ts, pointDensity); return points; } private onCRSplineCurve(ptStart: number, ptCount: number, t: number, result: Vector2): Vector2 { var adjustedIndex: number = Math.floor(t * (ptCount - 4)) + ptStart; //Since the equation works with 4 points, we adjust the starting point depending on t to return a point on the specific segment var p0x: number = this._points[adjustedIndex].x; var p0y: number = this._points[adjustedIndex].y; var p1x: number = this._points[adjustedIndex + 1].x; var p1y: number = this._points[adjustedIndex + 1].y; var p2x: number = this._points[adjustedIndex + 2].x; var p2y: number = this._points[adjustedIndex + 2].y; var p3x: number = this._points[adjustedIndex + 3].x; var p3y: number = this._points[adjustedIndex + 3].y; var adjustedT: number = (t == 1) ? 1 : repeat(t * (ptCount - 4), 1); // Then we adjust t to be that value on that new piece of segment... for t == 1f don't use repeat (that would return 0f); var t0: number = ((-adjustedT + 2) * adjustedT - 1) * adjustedT * 0.5; var t1: number = (((3 * adjustedT - 5) * adjustedT) * adjustedT + 2) * 0.5; var t2: number = ((-3 * adjustedT + 4) * adjustedT + 1) * adjustedT * 0.5; var t3: number = ((adjustedT - 1) * adjustedT * adjustedT) * 0.5; result.x = p0x * t0 + p1x * t1 + p2x * t2 + p3x * t3; result.y = p0y * t0 + p1y * t1 + p2y * t2 + p3y * t3; return result; } private onBezierCurve(ptStart: number, ptCount: number, t: number, result: Vector2): Vector2 { var t2: number = 1 - t; var p0x: number = this._points[ptStart].x; var p0y: number = this._points[ptStart].y; var p1x: number = this._points[ptStart + 1].x; var p1y: number = this._points[ptStart + 1].y; var cp0x: number = this._points[ptStart + 2].x; var cp0y: number = this._points[ptStart + 2].y; if (ptCount == 4) { var cp1x: number = this._points[ptStart + 3].x; var cp1y: number = this._points[ptStart + 3].y; result.x = t2 * t2 * t2 * p0x + 3 * t2 * t2 * t * cp0x + 3 * t2 * t * t * cp1x + t * t * t * p1x; result.y = t2 * t2 * t2 * p0y + 3 * t2 * t2 * t * cp0y + 3 * t2 * t * t * cp1y + t * t * t * p1y; } else { result.x = t2 * t2 * p0x + 2 * t2 * t * cp0x + t * t * p1x; result.y = t2 * t2 * p0y + 2 * t2 * t * cp0y + t * t * p1y; } return result; } } interface Segment { type?: number; length?: number; ptStart?: number; ptCount?: number; }
the_stack
* @fileoverview Helper functions and classes to work with ChangeSets with indexed collections (sets and maps) */ import cloneDeep from "lodash/cloneDeep"; import isEmpty from "lodash/isEmpty"; import isEqual from "lodash/isEqual"; import isObject from "lodash/isObject"; import without from "lodash/without"; import includes from "lodash/includes"; //@ts-ignore import { constants, joinPaths } from "@fluid-experimental/property-common"; import { ApplyChangeSetOptions, ConflictInfo, SerializedChangeSet } from "../changeset"; import { TypeIdHelper } from "../helpers/typeidHelper"; import { PathHelper } from "../pathHelper"; import { ConflictType } from "./changesetConflictTypes"; import { isEmptyChangeSet } from "./isEmptyChangeset"; const { PROPERTY_PATH_DELIMITER, MSG } = constants; /** * @namespace property-changeset.ChangeSetOperations.IndexedCollectionOperations * @alias property-changeset.ChangeSetOperations.IndexedCollectionOperations * Helper functions and classes to perform operations on ChangeSets with indexed collections (sets and maps) */ /** * Checks whether an object is empty (has no keys) * This function should be a bit faster than the isEmpty from * underscore. Unfortunately, at least on Chrome, it is still in * O(n) * * @param in_object - The object to check * @returns Is it empty? * @private */ const _fastIsEmptyObject = function(in_object: any): boolean { if (!in_object || Array.isArray(in_object) || !isObject(in_object)) { return isEmpty(in_object); } for (const _entry in in_object) { // eslint-disable-line return false; } return true; }; export namespace ChangeSetIndexedCollectionFunctions { /** * Applies a ChangeSet to a given indexed collection property (recursively). The ChangeSet is assumed to be relative * to the same property root and it will be applied behind the base ChangeSet (assuming that the changes are * relative to the state after the base ChangeSet has been applied. It will change the base ChangeSet. * * @param io_basePropertyChanges - The ChangeSet describing the initial state * @param in_appliedPropertyChanges - The ChangeSet to apply to this state * @param in_typeid - The typeid of the contents collection * (without the collection type) * @param in_options - Optional additional parameters * @param in_options.applyAfterMetaInformation - Additional meta information which help later to obtain * more compact changeset during the apply operation * * @private */ export const _performApplyAfterOnPropertyIndexedCollection = function( io_basePropertyChanges: SerializedChangeSet, // eslint-disable-line complexity in_appliedPropertyChanges: SerializedChangeSet, in_typeid: string, in_options: ApplyChangeSetOptions) { const isPrimitiveTypeid = TypeIdHelper.isPrimitiveType(in_typeid); // Handle remove entry operations if (in_appliedPropertyChanges.remove) { // Get and initialize the corresponding entries in the existing collection let removedEntries = in_appliedPropertyChanges.remove; io_basePropertyChanges = io_basePropertyChanges || {}; io_basePropertyChanges.remove = io_basePropertyChanges.remove || (Array.isArray(in_appliedPropertyChanges.remove) ? [] : {}); let baseInserted = io_basePropertyChanges.insert || {}; let baseRemoved = io_basePropertyChanges.remove; let baseModified = io_basePropertyChanges.modify; let done = false; if (!Array.isArray(removedEntries)) { if (isPrimitiveTypeid) { removedEntries = Object.keys(removedEntries); } else { // this is a reversible change set of templated types const removedTypes = Object.keys(removedEntries); for (let t = 0; t < removedTypes.length; t++) { const removedKeys = Object.keys(removedEntries[removedTypes[t]]); for (let i = 0; i < removedKeys.length; i++) { if (baseInserted[removedTypes[t]] && baseInserted[removedTypes[t]][removedKeys[i]] !== undefined) { delete baseInserted[removedTypes[t]][removedKeys[i]]; // If all entries for a typeid have been removed, we can remove // the whole typeid from the inserted section if (baseInserted && isEmpty(baseInserted[removedTypes[t]])) { delete baseInserted[removedTypes[t]]; } } else { if (baseModified && baseModified[removedTypes[t]] && baseModified[removedTypes[t]][removedKeys[i]] !== undefined) { delete baseModified[removedTypes[t]][removedKeys[i]]; // If all entries for a typeid have been removed, we can remove // the whole typeid from the inserted section if (baseModified && isEmpty(baseModified[removedTypes[t]])) { delete baseModified[removedTypes[t]]; } } if (Array.isArray(baseRemoved)) { baseRemoved.push(removedKeys[i]); } else { if (!baseRemoved[removedTypes[t]]) { baseRemoved[removedTypes[t]] = {}; } baseRemoved[removedTypes[t]][removedKeys[i]] = removedEntries[removedTypes[t]][removedKeys[i]]; } } } } done = true; } } if (!done) { if (isPrimitiveTypeid) { for (let i = 0; i < removedEntries.length; i++) { let key = removedEntries[i]; // If there is an insert for this key, we just remove it if (baseInserted[key] !== undefined) { delete baseInserted[key]; } else { // There could be a modify entry for this key, which we have to remove if (baseModified && baseModified[key] !== undefined) { delete baseModified[key]; } // Otherwise we add it to the remove list if (Array.isArray(baseRemoved)) { baseRemoved.push(key); } else { baseRemoved[key] = in_appliedPropertyChanges.remove[key]; } } } } else { const baseInsertedTypeids = Object.keys(baseInserted); for (let i = 0; i < removedEntries.length; i++) { let key = removedEntries[i]; let foundInTypeid; // Since we only have a flat remove list (without typeid) in the changeset, we have // to check all inserts for (let j = 0; j < baseInsertedTypeids.length; j++) { if (baseInserted[baseInsertedTypeids[j]] && baseInserted[baseInsertedTypeids[j]][key] !== undefined) { foundInTypeid = baseInsertedTypeids[j]; break; } } if (foundInTypeid) { // If this key was inserted by this ChangeSet, we just remove it from the inserted list delete baseInserted[foundInTypeid][key]; // If all entries for a typeid have been removed, we can remove // the whole typeid from the inserted or modified section if (baseInserted && isEmpty(baseInserted[foundInTypeid])) { delete baseInserted[foundInTypeid]; } if (baseModified && isEmpty(baseModified[foundInTypeid])) { delete baseModified[foundInTypeid]; } } else { // There could be a modify entry for this key, which we have to remove const baseModifiedTypeids = Object.keys(baseModified || {}); for (let j = 0; j < baseModifiedTypeids.length; j++) { if (baseModified[baseModifiedTypeids[j]][key]) { foundInTypeid = baseModifiedTypeids[j]; delete baseModified[foundInTypeid][key]; break; } } // Otherwise we add it to the remove list baseRemoved.push(key); } } } } }; // Apply insert operations if (in_appliedPropertyChanges.insert) { // Get and initialize the corresponding entries from the existing collection io_basePropertyChanges = io_basePropertyChanges || {}; io_basePropertyChanges.insert = io_basePropertyChanges.insert || {}; let baseInserted = io_basePropertyChanges.insert; let baseRemoved = io_basePropertyChanges.remove; // Insert the inserted entries // If no typeids are included, we just use a placeholder for the iteration below const insertedTypeids = isPrimitiveTypeid ? [undefined] : Object.keys(in_appliedPropertyChanges.insert); for (let i = 0; i < insertedTypeids.length; i++) { let typeid = insertedTypeids[i]; const insertedEntries = isPrimitiveTypeid ? in_appliedPropertyChanges.insert : in_appliedPropertyChanges.insert[typeid]; const insertedKeys = Object.keys(insertedEntries); let removalCS; if (baseRemoved) { removalCS = isPrimitiveTypeid ? baseRemoved : baseRemoved[typeid]; } for (let j = 0; j < insertedKeys.length; j++) { let key = insertedKeys[j]; let deeplyEqualCS = false; // If we have a complex type in the collection, we need to do a deep comparison of the two // ChangeSets to determine, whether they are equal // TODO: We should actually compute a diff between the two and recursively convert portions to modifies // Instead, right now, we only handle the case where the two keys cancel each out perfectly, i.e., // the insert is reinserting exactly what was removed. if (!isPrimitiveTypeid && removalCS && isObject(removalCS) && removalCS[key] !== undefined) { // Split out the two parts: all the keys other than remove/insert should match exactly. // The contents 'remove' and 'insert', if they exist, should also match. deeplyEqualCS = !!insertedEntries[key].insert === !!removalCS[key].remove; // If there are 'insert' and 'remove', see if the removed data matches the inserted data if (deeplyEqualCS && insertedEntries[key].insert) { deeplyEqualCS = isEqual( insertedEntries[key].insert, removalCS[key].remove, ); } // Finally, check if the data being inserted matches the data that was removed const insertedEntry = isObject(insertedEntries[key]) ? without(insertedEntries[key], "insert") : insertedEntries[key]; const removedEntry = isObject(removalCS[key]) ? without(removalCS[key], "remove") : removalCS[key]; deeplyEqualCS = deeplyEqualCS && isEqual(insertedEntry, removedEntry); } if ((isPrimitiveTypeid || TypeIdHelper.isPrimitiveType(typeid) || deeplyEqualCS) && removalCS && ((Array.isArray(removalCS) && includes(baseRemoved, key)) || removalCS[key] !== undefined)) { // A remove and insert are combined into a modify for primitive types // Remove the old remove command let oldValueMatches = false; if (Array.isArray(removalCS)) { if (isPrimitiveTypeid) { io_basePropertyChanges.remove = without(io_basePropertyChanges.remove, key); } else { io_basePropertyChanges.remove[typeid] = without(io_basePropertyChanges.remove[typeid], key); } } else { oldValueMatches = deeplyEqualCS || (removalCS[key] === insertedEntries[key]); delete removalCS[key]; } // Insert a modify command instead if (!oldValueMatches) { io_basePropertyChanges.modify = io_basePropertyChanges.modify || {}; if (isPrimitiveTypeid) { io_basePropertyChanges.modify[key] = insertedEntries[key]; } else { io_basePropertyChanges.modify[typeid] = io_basePropertyChanges.modify[typeid] || {}; io_basePropertyChanges.modify[typeid][key] = cloneDeep(insertedEntries[key]); } } } else if (isPrimitiveTypeid && baseInserted[key] === undefined) { baseInserted[key] = insertedEntries[key]; } else if (!isPrimitiveTypeid && (!baseInserted[typeid] || baseInserted[typeid][key] === undefined)) { baseInserted[typeid] = baseInserted[typeid] || {}; baseInserted[typeid][key] = cloneDeep(insertedEntries[key]); } else { throw new Error(MSG.ALREADY_EXISTING_ENTRY + key); } } } } // Handle modification operations if (in_appliedPropertyChanges.modify) { // Get and initialize the corresponding entries from the existing collection const modifiedEntries = in_appliedPropertyChanges.modify; io_basePropertyChanges = io_basePropertyChanges || {}; io_basePropertyChanges.modify = io_basePropertyChanges.modify || {}; let baseModified = io_basePropertyChanges.modify; let baseInserted = io_basePropertyChanges.insert || {}; // Process the modifications // If no typeids are included, we just use a placeholder for the iteration below const modifiedTypeids = isPrimitiveTypeid ? [undefined] : Object.keys(modifiedEntries); for (let i = 0; i < modifiedTypeids.length; i++) { let typeid = modifiedTypeids[i]; const modifyKeys = Object.keys(isPrimitiveTypeid ? modifiedEntries : modifiedEntries[typeid]); for (let j = 0; j < modifyKeys.length; j++) { let key = modifyKeys[j]; if (isPrimitiveTypeid) { let newValue = modifiedEntries[key]; if (newValue && newValue.hasOwnProperty("value")) { newValue = newValue.value; } if (baseInserted[key] !== undefined) { // If this entry was added by this ChangeSet, we modify the insert operation according to the // new ChangeSet baseInserted[key] = newValue; } else { if (baseModified[key] && baseModified[key].hasOwnProperty("value")) { baseModified[key].value = newValue; } else { baseModified[key] = newValue; } } } else { // If this is a polymorphic collection, we can still have individual entries with // primitive types const isEntryPrimitiveType = TypeIdHelper.isPrimitiveType(typeid); if (baseInserted[typeid] && baseInserted[typeid][key] !== undefined) { // If this entry was added by this ChangeSet, we modify the insert operation according to the // new ChangeSet if (isEntryPrimitiveType && typeid !== "String") { let newValue = modifiedEntries[typeid][key]; if (newValue && newValue.hasOwnProperty("value")) { newValue = modifiedEntries[typeid][key].value; } // In the case of Int64 or Uint64 we copy the array so that // both ChangeSets don't point to the same instance if (typeid === "Int64" || typeid === "Uint64") { newValue = newValue.slice(); } if (baseInserted[typeid][key] && baseInserted[typeid][key].hasOwnProperty("value")) { baseInserted[typeid][key].value = newValue; } else { baseInserted[typeid][key] = newValue; } } else { this.performApplyAfterOnPropertyWithTypeid(key, baseInserted[typeid], modifiedEntries[typeid], typeid, false, in_options); } } else if (baseModified[typeid] && baseModified[typeid][key] !== undefined) { // If there was a previous modification operation, we have to merge the two if (isEntryPrimitiveType && typeid !== "String") { // Primitive types can simply be overwritten, however we have an exception for // 64 bit integers (until javascript natively supports them) if (typeid === "Int64" || typeid === "Uint64") { let appliedVal = modifiedEntries[typeid][key]; if (appliedVal && appliedVal.hasOwnProperty("value")) { appliedVal = appliedVal.value; } baseModified[typeid][key] = appliedVal.slice(); } else { baseModified[typeid][key] = modifiedEntries[typeid][key]; } } else { this.performApplyAfterOnPropertyWithTypeid(key, baseModified[typeid], modifiedEntries[typeid], typeid, true, in_options); } } else { baseModified[typeid] = baseModified[typeid] || {}; baseModified[typeid][key] = cloneDeep(modifiedEntries[typeid][key]); } } } } } // Remove unnecessary entries from the ChangeSet this._cleanIndexedCollectionChangeSet(io_basePropertyChanges, !isPrimitiveTypeid); } /** * Performs the rebase operation for set and map collections * * @param in_ownPropertyChangeSet - The ChangeSet for this collection * @param io_rebasePropertyChangeSet - The ChangeSet for the collection to be rebased * @param in_basePath - Base path to get to the property processed by this function * @param in_typeid - The typeid of the contents collection (without the collection type) * @param in_useSquareBracketsInPath - * If set to true, paths will be created using the angular brackets syntax (for * arrays), otherwise dots will be used (for NodeProperties) * @param out_conflicts - A list of paths that resulted in conflicts together with the type of the conflict * @param in_options - Optional additional parameters * @param in_options.applyAfterMetaInformation - Additional meta information which help later to obtain * more compact changeset during the apply operation * * @private */ export const _rebaseIndexedCollectionChangeSetForProperty = function( in_ownPropertyChangeSet: SerializedChangeSet, // eslint-disable-line complexity io_rebasePropertyChangeSet: SerializedChangeSet, in_basePath: string, in_typeid: string, in_useSquareBracketsInPath: boolean, out_conflicts: ConflictInfo[], in_options: ApplyChangeSetOptions) { const isPrimitiveTypeid = TypeIdHelper.isPrimitiveType(in_typeid); const changesByKeys = {}; let modifyMap = {}; // Helper function which stores the changes indexed by key in the changesByKeys array to // make it easier to compare the related changes in the two ChangeSets const addChanges = function(in_collection: Record<string, any>, in_changeIdentifier: string, in_changePrefix: string, in_typeidChange?: string) { // Collection didn't exist in this ChangeSet if (in_collection === undefined) { return; } // For remove operations, the ChangeSet is only an array of keys, otherwise it is a map, so we have to // distinguish the two cases here const keys = Array.isArray(in_collection) ? in_collection : Object.keys(in_collection); // Add all entries indexed with the key for (let j = 0; j < keys.length; j++) { const key = keys[j]; // Store the type of the change changesByKeys[key] = changesByKeys[key] || {}; changesByKeys[key][in_changePrefix] = changesByKeys[key][in_changePrefix] ? `${changesByKeys[key][in_changePrefix]}_${in_changeIdentifier}` : in_changeIdentifier; // If applicable store the typeid of the change if (in_typeidChange) { changesByKeys[key][`${in_changePrefix}Typeid`] = in_typeidChange; } // Store the ChangeSet if (in_changePrefix === "other") { if (!Array.isArray(in_collection)) { changesByKeys[key].change = in_collection[key]; } else { changesByKeys[key].change = key; } } } }; // Helper function which adds the Changes for a ChangeSet that is ordered by typeid const addChangesWithTypeids = function (in_collection, in_changeIdentifier, in_changePrefix) { if (in_collection === undefined) { return; } // Iterate over the typeids (or use dummy entry for the iteration const addedKeyTypeids = Object.keys(in_collection); for (let i = 0; i < addedKeyTypeids.length; i++) { const Typeid = addedKeyTypeids[i]; addChanges(in_collection[Typeid], in_changeIdentifier, in_changePrefix, Typeid); } }; // Insert all changes from the ChangeSet into the lookup map if (Array.isArray(in_ownPropertyChangeSet.remove)) { addChanges(in_ownPropertyChangeSet.remove, "remove", "own"); } else { if (isPrimitiveTypeid) { addChanges(in_ownPropertyChangeSet.remove, "remove", "own"); } else { addChangesWithTypeids(in_ownPropertyChangeSet.remove, "remove", "own"); } } if (Array.isArray(io_rebasePropertyChangeSet.remove)) { addChanges(io_rebasePropertyChangeSet.remove, "remove", "other"); } else { if (isPrimitiveTypeid) { addChanges(io_rebasePropertyChangeSet.remove, "remove", "other"); } else { addChangesWithTypeids(io_rebasePropertyChangeSet.remove, "remove", "other"); } } if (isPrimitiveTypeid) { addChanges(in_ownPropertyChangeSet.insert, "insert", "own"); addChanges(in_ownPropertyChangeSet.modify, "modify", "own"); addChanges(io_rebasePropertyChangeSet.insert, "insert", "other"); addChanges(io_rebasePropertyChangeSet.modify, "modify", "other"); } else { addChangesWithTypeids(in_ownPropertyChangeSet.insert, "insert", "own"); addChangesWithTypeids(in_ownPropertyChangeSet.modify, "modify", "own"); addChangesWithTypeids(io_rebasePropertyChangeSet.insert, "insert", "other"); addChangesWithTypeids(io_rebasePropertyChangeSet.modify, "modify", "other"); } // Check for modifications that affect the same object const changedKeys = Object.keys(changesByKeys); for (let i = 0; i < changedKeys.length; i++) { const key = changedKeys[i]; const newPath = in_useSquareBracketsInPath ? `${in_basePath}[${PathHelper.quotePathSegmentIfNeeded(key)}]` : joinPaths(in_basePath, PathHelper.quotePathSegmentIfNeeded(key), PROPERTY_PATH_DELIMITER); const modification = changesByKeys[key]; if (modification.own && modification.other) { /* We found a key that was changed by both ChangeSets at the same time We now have to handle the conflicting changes. The changes we do, are summarized in this table: <START REBASE HANDLING TABLE> +-------+-----------------+------------------+-------------------+-------------------------------------+ | \Own| insert | modify | remove | remove+insert | | \ | | | | | |other\ | | | | | +=======+=================+==================+===================+=====================================+ | | conflicting | incompatible | incompatible | incompatible | |insert | inserts | psets | psets | psets | | | | | | | +-------+-----------------+------------------+-------------------+-------------------------------------+ | | incompatible | merge recursively| conflict | conflict | |modify | psets | (conflicting on | | (modify can not be applied due to | | | | leaf) | - delete modify | to incompatible base) | | | | | in other | | | | | | | - delete modify in other | +-------+-----------------+------------------+-------------------+-------------------------------------+ | | incompatible | non-conflicting | non-conflicting | incompatible | |remove | psets | change | change | psets | | | | | | | | | | | - rem dupl. remove| | +-------+-----------------+------------------+-------------------+-------------------------------------+ | | incompatible | non-conflicting | non-conflicting | conflict | |remove+| psets | change | change | | |insert | | | | - remove conflicting insert | | | | | - rem dupl. remove| | +-------+-----------------+------------------+-------------------+-------------------------------------+ <END REBASE HANDLING TABLE> */ // A key was modified after it had been removed if (modification.own === "modify" && modification.other === "modify") { if (isPrimitiveTypeid || (TypeIdHelper.isPrimitiveType(modification.ownTypeid) && modification.ownTypeid !== "String")) { // We have two modification operations that affect the same entry for a base type. // This is a legal operation, the second one will overwrite the first one, but we // report it as a possible conflict let ownModify = in_ownPropertyChangeSet.modify; let rebasedModify = io_rebasePropertyChangeSet.modify; if (modification.otherTypeid) { ownModify = ownModify[modification.otherTypeid]; rebasedModify = rebasedModify[modification.otherTypeid]; } let conflict = { path: newPath, type: ConflictType.COLLIDING_SET, conflictingChange: ownModify[key], }; out_conflicts.push(conflict); // If value is the same, delete the entry let ownValue = ownModify[key]; if (typeof ownValue === "object" && ownValue.hasOwnProperty("value")) { ownValue = ownValue.value; } let rebaseValue = rebasedModify[key]; if (typeof rebaseValue === "object" && rebaseValue.hasOwnProperty("value")) { rebaseValue = rebaseValue.value; } if (modification.ownTypeid === "Int64" || modification.ownTypeid === "Uint64" || ownValue.length === 2) { // For (u)int64, values are arrays of 2 elements if (ownValue[0] === rebaseValue[0] && ownValue[1] === rebaseValue[1]) { delete rebasedModify[key]; } } else { if (ownValue === rebaseValue) { delete rebasedModify[key]; } } } else { this.rebaseChangeSetForPropertyEntryWithTypeid(key, in_ownPropertyChangeSet.modify[modification.ownTypeid], io_rebasePropertyChangeSet.modify[modification.otherTypeid], modification.ownTypeid, newPath, true, out_conflicts, in_options); } } else if (modification.own === "remove" && modification.other === "modify") { modifyMap = modification.otherTypeid ? io_rebasePropertyChangeSet.modify[modification.otherTypeid] : io_rebasePropertyChangeSet.modify; // Create the conflict information let conflict = { path: newPath, type: ConflictType.ENTRY_MODIFIED_AFTER_REMOVE, conflictingChange: modifyMap[key], }; out_conflicts.push(conflict); // Delete the modification from the rebased ChangeSet delete modifyMap[key]; } else if (modification.own === "remove_insert" && modification.other === "modify") { // We have a conflicting change. A node was removed and inserted (replaced) in the original // ChangeSet and then modified by the rebased ChangeSet. Since the base of the modification // can have been changed significantly by this operation, we don't know whether we can // apply the modification // Create the conflict information let conflict = { path: newPath, type: ConflictType.ENTRY_MODIFICATION_AFTER_REMOVE_INSERT, conflictingChange: io_rebasePropertyChangeSet.modify[modification.otherTypeid][key], }; out_conflicts.push(conflict); // Delete the modification from the rebased ChangeSet delete io_rebasePropertyChangeSet.modify[key]; } else if ((modification.own === "modify" || modification.own === "remove") && (modification.other === "remove" || modification.other === "remove_insert")) { if (modification.own === "modify") { modifyMap = modification.ownTypeid ? in_ownPropertyChangeSet.modify[modification.ownTypeid] : in_ownPropertyChangeSet.modify; // Create the conflict information let conflict = { path: newPath, type: ConflictType.REMOVE_AFTER_MODIFY, conflictingChange: modifyMap[key], }; out_conflicts.push(conflict); } // If we have a duplicated delete, we remove it from the new ChangeSet if (modification.own === "remove") { if (Array.isArray(io_rebasePropertyChangeSet.remove)) { io_rebasePropertyChangeSet.remove = without(io_rebasePropertyChangeSet.remove, key); } else { if (isPrimitiveTypeid) { delete io_rebasePropertyChangeSet.remove[key]; } else { delete io_rebasePropertyChangeSet.remove[modification.otherTypeid][key]; } } } } else if (modification.own === "insert" && modification.other === "insert") { if (isPrimitiveTypeid || (TypeIdHelper.isPrimitiveType(modification.ownTypeid))) { let insertMap = modification.otherTypeid ? io_rebasePropertyChangeSet.insert[modification.otherTypeid] : io_rebasePropertyChangeSet.insert; // We have two insert operations that affect the same key for a primitive type. // This is a legal operation, the second one will overwrite the first one, but we // report it as a possible conflicting set let conflict = { path: newPath, type: ConflictType.COLLIDING_SET, conflictingChange: insertMap[key], }; out_conflicts.push(conflict); // Convert to modify let oldValue; if (modification.otherTypeid) { io_rebasePropertyChangeSet.modify = io_rebasePropertyChangeSet.modify || {}; io_rebasePropertyChangeSet.modify[modification.otherTypeid] = io_rebasePropertyChangeSet.modify[modification.otherTypeid] || {}; modifyMap = io_rebasePropertyChangeSet.modify[modification.otherTypeid]; oldValue = in_ownPropertyChangeSet.insert[modification.ownTypeid][key]; } else { io_rebasePropertyChangeSet.modify = io_rebasePropertyChangeSet.modify || {}; modifyMap = io_rebasePropertyChangeSet.modify; oldValue = in_ownPropertyChangeSet.insert[key]; } modifyMap[key] = { value: insertMap[key], oldValue }; delete insertMap[key]; } else { // Here we have two insert operations for objects. Since these affect a whole sub-tree and not // just a single value, we cannot easily convert it into a modify and instead report it as invalid let insertMap = modification.otherTypeid ? io_rebasePropertyChangeSet.insert[modification.otherTypeid] : io_rebasePropertyChangeSet.insert; // Create the conflict information let conflict = { path: newPath, type: ConflictType.INSERTED_ENTRY_WITH_SAME_KEY, conflictingChange: insertMap[key], }; out_conflicts.push(conflict); // Delete the modification from the rebased ChangeSet delete insertMap[key]; } } else if (modification.own === "remove_insert" && modification.other === "remove_insert") { let insertMap = modification.otherTypeid ? io_rebasePropertyChangeSet.insert[modification.otherTypeid] : io_rebasePropertyChangeSet.insert; // Raise the duplicate inserts as a conflict let conflict = { path: newPath, type: ConflictType.COLLIDING_SET, conflictingChange: insertMap[key], }; out_conflicts.push(conflict); } else { // All other operations are conflicting changes, which only occur for ChangeSets that are relative // to different bases // Create the conflict information let conflict = { path: newPath, type: ConflictType.INVALID_CHANGESET_BASE, conflictingChange: modification.change, }; out_conflicts.push(conflict); // Remove the change from the ChangeSet if (modification.other !== "remove") { if (modification.otherTypeid !== undefined) { delete io_rebasePropertyChangeSet[modification.other][modification.otherTypeid][key]; } else { delete io_rebasePropertyChangeSet[modification.other][key]; } } else { // Remove remove operations from the ChangeSet if (Array.isArray(io_rebasePropertyChangeSet[modification.other])) { io_rebasePropertyChangeSet[modification.other] = without(io_rebasePropertyChangeSet[modification.other], key); } else { delete io_rebasePropertyChangeSet[modification.other][key]; } } console.error("Rebase operation with conflicting ChangeSets. Probably incorrect bases."); } } } // Remove unnecessary entries from the ChangeSet this._cleanIndexedCollectionChangeSet(io_rebasePropertyChangeSet, !isPrimitiveTypeid); } /** * Removes empty entries from the .children collection of the ChangeSet * * @param in_propertyChanges - The ChangeSet to clean up * @param in_containsTypeids - Does this ChangeSet contain typeids * @private */ export const _cleanIndexedCollectionChangeSet = function(in_propertyChanges: SerializedChangeSet, in_containsTypeids: boolean) { const changes = in_propertyChanges; // Clean inserts // First remove unused typeid sections if (in_containsTypeids) { let typeidList = Object.keys(changes.insert || {}); for (let j = 0; j < typeidList.length; j++) { if (_fastIsEmptyObject(changes.insert[typeidList[j]])) { delete changes.insert[typeidList[j]]; } } } // Remove add group if no operations are present if (_fastIsEmptyObject(changes.insert)) { delete changes.insert; } // First remove unused typeid sections if (in_containsTypeids) { let typeidList = Object.keys(changes.remove || {}); for (let j = 0; j < typeidList.length; j++) { if (_fastIsEmptyObject(changes.remove[typeidList[j]])) { delete changes.remove[typeidList[j]]; } } } // Remove remove group if no operations are present if (_fastIsEmptyObject(changes.remove)) { delete changes.remove; } // Clean modifies // First remove unused typeid sections if (in_containsTypeids) { let typeidList = Object.keys(changes.modify || {}); for (let j = 0; j < typeidList.length; j++) { const modifies = changes.modify[typeidList[j]]; const modifyKeys = Object.keys(modifies); for (let k = 0; k < modifyKeys.length; k++) { if (isEmptyChangeSet(modifies[modifyKeys[k]])) { delete modifies[modifyKeys[k]]; } } if (_fastIsEmptyObject(changes.modify[typeidList[j]])) { delete changes.modify[typeidList[j]]; } } } // Remove modify group if no operations are present if (_fastIsEmptyObject(changes.modify)) { delete changes.modify; } } };
the_stack
import { createEntityAdapter, EntityAdapter, Update } from '@ngrx/entity'; import { Project, ProjectState } from '../project.model'; import { createReducer, on } from '@ngrx/store'; import { FIRST_PROJECT, PROJECT_MODEL_VERSION } from '../project.const'; import { WorkContextAdvancedCfg, WorkContextType, } from '../../work-context/work-context.model'; import { addTask, convertToMainTask, deleteTask, moveToArchive, moveToOtherProject, restoreTask, } from '../../tasks/store/task.actions'; import { moveTaskDownInTodayList, moveTaskInTodayList, moveTaskUpInTodayList, } from '../../work-context/store/work-context-meta.actions'; import { moveItemInList, moveTaskForWorkContextLikeState, } from '../../work-context/store/work-context-meta.helper'; import { arrayMoveLeftUntil, arrayMoveRightUntil } from '../../../util/array-move'; import { filterOutId } from '../../../util/filter-out-id'; import { unique } from '../../../util/unique'; import { loadAllData } from '../../../root-store/meta/load-all-data.action'; import { migrateProjectState } from '../migrate-projects-state.util'; import { MODEL_VERSION_KEY } from '../../../app.constants'; import { Task } from '../../tasks/task.model'; import { devError } from '../../../util/dev-error'; import { addProject, addProjects, addToProjectBreakTime, archiveProject, deleteProject, deleteProjects, loadProjects, moveProjectTaskDownInBacklogList, moveProjectTaskInBacklogList, moveProjectTaskToBacklogList, moveProjectTaskToBacklogListAuto, moveProjectTaskToTodayList, moveProjectTaskToTodayListAuto, moveProjectTaskUpInBacklogList, unarchiveProject, updateProject, updateProjectAdvancedCfg, updateProjectIssueProviderCfg, updateProjectOrder, updateProjectWorkEnd, updateProjectWorkStart, upsertProject, } from './project.actions'; export const PROJECT_FEATURE_NAME = 'projects'; const WORK_CONTEXT_TYPE: WorkContextType = WorkContextType.PROJECT; export const projectAdapter: EntityAdapter<Project> = createEntityAdapter<Project>(); // DEFAULT // ------- export const initialProjectState: ProjectState = projectAdapter.getInitialState({ ids: [FIRST_PROJECT.id], entities: { [FIRST_PROJECT.id]: FIRST_PROJECT, }, [MODEL_VERSION_KEY]: PROJECT_MODEL_VERSION, }); export const projectReducer = createReducer<ProjectState>( initialProjectState, // META ACTIONS // ------------ on(loadAllData, (oldState, { appDataComplete }) => appDataComplete.project ? migrateProjectState({ ...appDataComplete.project }) : oldState, ), on( moveTaskInTodayList, (state, { taskId, newOrderedIds, target, workContextType, workContextId }) => { if (workContextType !== WORK_CONTEXT_TYPE) { return state; } const taskIdsBefore = (state.entities[workContextId] as Project).taskIds; const taskIds = moveTaskForWorkContextLikeState( taskId, newOrderedIds, target, taskIdsBefore, ); return projectAdapter.updateOne( { id: workContextId, changes: { taskIds, }, }, state, ); }, ), on(moveProjectTaskInBacklogList, (state, { taskId, newOrderedIds, workContextId }) => { const taskIdsBefore = (state.entities[workContextId] as Project).backlogTaskIds; const backlogTaskIds = moveTaskForWorkContextLikeState( taskId, newOrderedIds, null, taskIdsBefore, ); return projectAdapter.updateOne( { id: workContextId, changes: { backlogTaskIds, }, }, state, ); }), // Project Actions // ------------ on(addProject, (state, { project }) => projectAdapter.addOne(project, state)), on(upsertProject, (state, { project }) => projectAdapter.upsertOne(project, state)), on(addProjects, (state, { projects }) => projectAdapter.addMany(projects, state)), on(updateProject, (state, { project }) => projectAdapter.updateOne(project, state)), on(deleteProject, (state, { id }) => projectAdapter.removeOne(id, state)), on(deleteProjects, (state, { ids }) => projectAdapter.removeMany(ids, state)), on(loadProjects, (state, { projects }) => projectAdapter.setAll(projects, state)), on(archiveProject, (state, { id }) => projectAdapter.updateOne( { id, changes: { isArchived: true, }, }, state, ), ), on(unarchiveProject, (state, { id }) => projectAdapter.updateOne( { id, changes: { isArchived: false, }, }, state, ), ), on(updateProjectWorkStart, (state, { id, date, newVal }) => { const oldP = state.entities[id] as Project; return projectAdapter.updateOne( { id, changes: { workStart: { ...oldP.workStart, [date]: newVal, }, }, }, state, ); }), on(updateProjectWorkEnd, (state, { id, date, newVal }) => { const oldP = state.entities[id] as Project; return projectAdapter.updateOne( { id, changes: { workEnd: { ...oldP.workEnd, [date]: newVal, }, }, }, state, ); }), on(addToProjectBreakTime, (state, { id, date, valToAdd }) => { const oldP = state.entities[id] as Project; const oldBreakTime = oldP.breakTime[date] || 0; const oldBreakNr = oldP.breakNr[date] || 0; return projectAdapter.updateOne( { id, changes: { breakNr: { ...oldP.breakNr, [date]: oldBreakNr + 1, }, breakTime: { ...oldP.breakTime, [date]: oldBreakTime + valToAdd, }, }, }, state, ); }), on(updateProjectAdvancedCfg, (state, { projectId, sectionKey, data }) => { const currentProject = state.entities[projectId] as Project; const advancedCfg: WorkContextAdvancedCfg = Object.assign( {}, currentProject.advancedCfg, ); return projectAdapter.updateOne( { id: projectId, changes: { advancedCfg: { ...advancedCfg, [sectionKey]: { ...advancedCfg[sectionKey], ...data, }, }, }, }, state, ); }), on( updateProjectIssueProviderCfg, (state, { projectId, providerCfg, issueProviderKey, isOverwrite }) => { const currentProject = state.entities[projectId] as Project; return projectAdapter.updateOne( { id: projectId, changes: { issueIntegrationCfgs: { ...currentProject.issueIntegrationCfgs, [issueProviderKey]: { ...(isOverwrite ? {} : currentProject.issueIntegrationCfgs[issueProviderKey]), ...providerCfg, }, }, }, }, state, ); }, ), on(updateProjectOrder, (state, { ids }) => { const currentIds = state.ids as string[]; let newIds: string[] = ids; if (ids.length !== currentIds.length) { const allP = currentIds.map((id) => state.entities[id]) as Project[]; const archivedIds = allP.filter((p) => p.isArchived).map((p) => p.id); const unarchivedIds = allP.filter((p) => !p.isArchived).map((p) => p.id); if ( ids.length === unarchivedIds.length && ids.length > 0 && unarchivedIds.includes(ids[0]) ) { newIds = [...ids, ...archivedIds]; } else if ( ids.length === archivedIds.length && ids.length > 0 && archivedIds.includes(ids[0]) ) { newIds = [...unarchivedIds, ...ids]; } else { throw new Error('Invalid param given to UpdateProjectOrder'); } } if (!newIds) { throw new Error('Project ids are undefined'); } return { ...state, ids: newIds }; }), // MOVE TASK ACTIONS // ----------------- on(moveProjectTaskToBacklogList, (state, { taskId, newOrderedIds, workContextId }) => { const todaysTaskIdsBefore = (state.entities[workContextId] as Project).taskIds; const backlogIdsBefore = (state.entities[workContextId] as Project).backlogTaskIds; const filteredToday = todaysTaskIdsBefore.filter(filterOutId(taskId)); const backlogTaskIds = moveItemInList(taskId, backlogIdsBefore, newOrderedIds); return projectAdapter.updateOne( { id: workContextId, changes: { taskIds: filteredToday, backlogTaskIds, }, }, state, ); }), on(moveProjectTaskToTodayList, (state, { taskId, newOrderedIds, workContextId }) => { const backlogIdsBefore = (state.entities[workContextId] as Project).backlogTaskIds; const todaysTaskIdsBefore = (state.entities[workContextId] as Project).taskIds; const filteredBacklog = backlogIdsBefore.filter(filterOutId(taskId)); const newTodaysTaskIds = moveItemInList(taskId, todaysTaskIdsBefore, newOrderedIds); return projectAdapter.updateOne( { id: workContextId, changes: { taskIds: newTodaysTaskIds, backlogTaskIds: filteredBacklog, }, }, state, ); }), on( moveTaskUpInTodayList, (state, { taskId, workContextType, workContextId, doneTaskIds }) => { return workContextType === WORK_CONTEXT_TYPE ? projectAdapter.updateOne( { id: workContextId, changes: { taskIds: arrayMoveLeftUntil( (state.entities[workContextId] as Project).taskIds, taskId, (id) => !doneTaskIds.includes(id), ), }, }, state, ) : state; }, ), on( moveTaskDownInTodayList, (state, { taskId, workContextType, workContextId, doneTaskIds }) => { return workContextType === WORK_CONTEXT_TYPE ? projectAdapter.updateOne( { id: workContextId, changes: { taskIds: arrayMoveRightUntil( (state.entities[workContextId] as Project).taskIds, taskId, (id) => !doneTaskIds.includes(id), ), }, }, state, ) : state; }, ), on( moveProjectTaskUpInBacklogList, (state, { taskId, workContextId, doneBacklogTaskIds }) => { return projectAdapter.updateOne( { id: workContextId, changes: { backlogTaskIds: arrayMoveLeftUntil( (state.entities[workContextId] as Project).backlogTaskIds, taskId, (id) => !doneBacklogTaskIds.includes(id), ), }, }, state, ); }, ), on( moveProjectTaskDownInBacklogList, (state, { taskId, workContextId, doneBacklogTaskIds }) => { return projectAdapter.updateOne( { id: workContextId, changes: { backlogTaskIds: arrayMoveRightUntil( (state.entities[workContextId] as Project).backlogTaskIds, taskId, (id) => !doneBacklogTaskIds.includes(id), ), }, }, state, ); }, ), on(moveProjectTaskToBacklogListAuto, (state, { taskId, projectId }) => { const todaysTaskIdsBefore = (state.entities[projectId] as Project).taskIds; const backlogIdsBefore = (state.entities[projectId] as Project).backlogTaskIds; return backlogIdsBefore.includes(taskId) ? state : projectAdapter.updateOne( { id: projectId, changes: { taskIds: todaysTaskIdsBefore.filter(filterOutId(taskId)), backlogTaskIds: [taskId, ...backlogIdsBefore], }, }, state, ); }), on(moveProjectTaskToTodayListAuto, (state, { taskId, projectId, isMoveToTop }) => { const todaysTaskIdsBefore = (state.entities[projectId] as Project).taskIds; const backlogIdsBefore = (state.entities[projectId] as Project).backlogTaskIds; return todaysTaskIdsBefore.includes(taskId) ? state : projectAdapter.updateOne( { id: projectId, changes: { backlogTaskIds: backlogIdsBefore.filter(filterOutId(taskId)), taskIds: isMoveToTop ? [taskId, ...todaysTaskIdsBefore] : [...todaysTaskIdsBefore, taskId], }, }, state, ); }), // Task Actions // ------------ on(addTask, (state, { task, isAddToBottom, isAddToBacklog }) => { const affectedProject = task.projectId && state.entities[task.projectId]; if (!affectedProject) return state; // if there is no projectId, no changes are needed const prop: 'backlogTaskIds' | 'taskIds' = isAddToBacklog ? 'backlogTaskIds' : 'taskIds'; const changes: { [x: string]: any[] } = {}; if (isAddToBottom) { changes[prop] = [...affectedProject[prop], task.id]; } else { // TODO #1382 get the currentTaskId from a different part of the state tree or via payload or _taskService // const currentTaskId = payload.currentTaskId || this._taskService.currentTaskId // const isAfterRunningTask = prop==='taskIds' && currentTaskId // console.log('isAfterRunningTask?',isAfterRunningTask,'currentTaskId',currentTaskId); // if (isAfterRunningTask) add the new task in the list after currentTaskId // else { // add to the top changes[prop] = [task.id, ...affectedProject[prop]]; //} } return projectAdapter.updateOne( { id: task.projectId as string, changes, }, state, ); }), on(convertToMainTask, (state, { task }) => { const affectedEntity = task.projectId && state.entities[task.projectId]; return affectedEntity ? projectAdapter.updateOne( { id: task.projectId as string, changes: { taskIds: [task.id, ...affectedEntity.taskIds], }, }, state, ) : state; }), on(deleteTask, (state, { task }) => { const project = task.projectId && (state.entities[task.projectId] as Project); return project ? projectAdapter.updateOne( { id: task.projectId as string, changes: { taskIds: project.taskIds.filter((ptId) => ptId !== task.id), backlogTaskIds: project.backlogTaskIds.filter((ptId) => ptId !== task.id), }, }, state, ) : state; }), on(moveToArchive, (state, { tasks }) => { const taskIdsToMoveToArchive = tasks.map((t: Task) => t.id); const projectIds = unique<string>( tasks .map((t: Task) => t.projectId) .filter((pid: string | null) => !!pid) as string[], ); const updates: Update<Project>[] = projectIds.map((pid: string) => ({ id: pid, changes: { taskIds: (state.entities[pid] as Project).taskIds.filter( (taskId) => !taskIdsToMoveToArchive.includes(taskId), ), backlogTaskIds: (state.entities[pid] as Project).backlogTaskIds.filter( (taskId) => !taskIdsToMoveToArchive.includes(taskId), ), }, })); return projectAdapter.updateMany(updates, state); }), on(restoreTask, (state, { task }) => { if (!task.projectId) { return state; } return projectAdapter.updateOne( { id: task.projectId, changes: { taskIds: [...(state.entities[task.projectId] as Project).taskIds, task.id], }, }, state, ); }), on(moveToOtherProject, (state, { task, targetProjectId }) => { const srcProjectId = task.projectId; const updates: Update<Project>[] = []; if (srcProjectId === targetProjectId) { devError('Moving task from same project to same project.'); return state; } if (srcProjectId) { updates.push({ id: srcProjectId, changes: { taskIds: (state.entities[srcProjectId] as Project).taskIds.filter( (id) => id !== task.id, ), backlogTaskIds: (state.entities[srcProjectId] as Project).backlogTaskIds.filter( (id) => id !== task.id, ), }, }); } if (targetProjectId) { updates.push({ id: targetProjectId, changes: { taskIds: [...(state.entities[targetProjectId] as Project).taskIds, task.id], }, }); } return projectAdapter.updateMany(updates, state); }), // on(AAA, (state, {AAA})=> { }), );
the_stack
import GameState from './GameState'; import Constants from '../data/Constants'; import Pool from '../utility/Pool'; import Save from '../utility/Save'; import ReturnOfGanon from '../fonts/ReturnOfGanon'; enum MainMenuActiveMenu { SELECT, REGISTER, ERASE, COPY }; export default class MainMenu extends GameState { music: Phaser.Sound; frames: Phaser.FrameData; selectGroup: Phaser.Group; registerGroup: Phaser.Group; charactersGroup: Phaser.Group; selectSound: Phaser.Sound; cursorSound: Phaser.Sound; eraseSound: Phaser.Sound; errorSound: Phaser.Sound; lowhpSound: Phaser.Sound; selectSprite: Phaser.Sprite; registerSprite: Phaser.Sprite; pointerSprite: Phaser.Sprite; fairySprite: Phaser.Sprite; linkSprites: Phaser.Sprite[]; heartsGroups: Phaser.Group[]; slotTexts: ReturnOfGanon[]; pname: ReturnOfGanon; fontpool: Pool<ReturnOfGanon>; heartpool: Pool<Phaser.Sprite>; private active: MainMenuActiveMenu; private pnameI: number; private selected: number; private selectedChar: Phaser.Point; private delta: Phaser.Point; private line: Phaser.Graphics; private saves: Save[]; private characters: ReturnOfGanon[][]; preload() { super.preload(); } create() { super.create(); this.active = MainMenuActiveMenu.SELECT; this.selected = 0; this.selectedChar = new Phaser.Point(6, 0); this.delta = new Phaser.Point(16, 16); this.saves = null; this.music = this.add.audio('music_select', Constants.AUDIO_MUSIC_VOLUME, true); this.frames = this.cache.getFrameData('sprite_select'); this.selectSound = this.add.audio('effect_menu_select', Constants.AUDIO_EFFECT_VOLUME); this.cursorSound = this.add.audio('effect_menu_select_cursor', Constants.AUDIO_EFFECT_VOLUME); this.eraseSound = this.add.audio('effect_menu_select_erase', Constants.AUDIO_EFFECT_VOLUME); this.errorSound = this.add.audio('effect_error', Constants.AUDIO_EFFECT_VOLUME); this.lowhpSound = this.add.audio('effect_lowhp', Constants.AUDIO_EFFECT_VOLUME); this.fontpool = new Pool<ReturnOfGanon>(this.game, ReturnOfGanon); this.heartpool = new Pool<Phaser.Sprite>(this.game, Phaser.Sprite); this.pnameI = 0; this.onInputDown.add(this._onInputDown, this); this.onInputUp.add(this._onInputUp, this); this._setupSelect(); this._setupRegister(); this.activate(MainMenuActiveMenu.SELECT); } move(direction: number) { if (this.active === MainMenuActiveMenu.SELECT) { if (direction === Phaser.DOWN) { this.selected++; this.selected %= 5; } else if (direction === Phaser.UP) { this.selected--; if (this.selected === -1) { this.selected = 4; } } switch (this.selected) { case 0: // slot 1 this.fairySprite.position.y = 72; break; case 1: // slot 2 this.fairySprite.position.y = 103; break; case 2: // slot 3 this.fairySprite.position.y = 132; break; case 3: // copy this.fairySprite.position.y = 177; break; case 4: // erase this.fairySprite.position.y = 192; break; } this.cursorSound.play(); } else if (this.active === MainMenuActiveMenu.REGISTER) { // move line around, and move text around switch (direction) { case Phaser.DOWN: this.selectedChar.y++; break; case Phaser.UP: this.selectedChar.y--; break; case Phaser.LEFT: this.selectedChar.x--; break; case Phaser.RIGHT: this.selectedChar.x++; break; } this.selectedChar.clampY(0, 3); this.selectedChar.clampX(0, 28); this.line.position.y = 132 + (this.selectedChar.y * this.delta.y); this.charactersGroup.position.x = -((this.selectedChar.x - 6) * this.delta.x); } else if (this.active === MainMenuActiveMenu.ERASE) { // TODO: Implement ERASE } else if (this.active === MainMenuActiveMenu.COPY) { // TODO: Implement COPY } } complete() { this.game.loadedSave = this.saves[this.selected]; this.game.state.start('state_play', true); } select() { if (this.active === MainMenuActiveMenu.SELECT) { // select a save to play if (this.selected <= 2) { if (!this.saves[this.selected].saveFileExists) { this.activate(MainMenuActiveMenu.REGISTER); } else { this.complete(); } } // select ERASE else if (this.selected === 3) { this.errorSound.play(); return; } // select COPY else if (this.selected === 4) { this.errorSound.play(); return; } this.selectSound.play(); } else if (this.active === MainMenuActiveMenu.REGISTER) { // add letter let n = this.pname.text; const ch = this.characters[this.selectedChar.y][this.selectedChar.x]; if (ch.name === 'end') { if (!n.trim()) { return this.activate(MainMenuActiveMenu.SELECT); } else { const ls = new Save(this.selected, n.split('').filter((ch: string, i: number) => (i % 2 === 0)).join('')); ls.save(); this.selectSound.play(); return this.activate(MainMenuActiveMenu.SELECT); } } else if (ch.name === 'left') { this.pnameI = Math.max(0, this.pnameI - 1); this.pointerSprite.position.x = 30 + (this.pnameI * 2 * this.pname.monospace); return; } else if (ch.name === 'right') { this.pnameI = Math.min((n.length / 2), this.pnameI + 1); this.pointerSprite.position.x = 30 + (this.pnameI * 2 * this.pname.monospace); return; } // max length, replace other characters if (n.length === 11 || this.pnameI < (n.length / 2)) { const i = this.pnameI * 2; n = n.substr(0, i) + ch.text + n.substr(i + 1); } // otherwise just add new character else { if (n.length) { n += ' '; } n += ch.text; } this.pnameI = (this.pnameI + 1) % 6; this.pname.text = n; this.pointerSprite.position.x = 30 + (this.pnameI * this.pname.monospace); this.lowhpSound.play(); } else if (this.active === MainMenuActiveMenu.ERASE) { // TODO: Implement ERASE } else if (this.active === MainMenuActiveMenu.COPY) { // TODO: Implement COPY } } activate(menu: MainMenuActiveMenu) { this.selectGroup.visible = false; this.registerGroup.visible = false; this.active = menu; if (menu === MainMenuActiveMenu.REGISTER) { this.registerGroup.visible = true; this.pname.text = ''; this.pnameI = 0; this.pointerSprite.x = 30; } else if (menu === MainMenuActiveMenu.SELECT) { this.selectGroup.visible = true; const s = this.saves = [ new Save(0), new Save(1), new Save(2), ]; for (let i = 0; i < s.length; ++i) { const sv = s[i].load(); const spr = this.linkSprites[i]; const txt = this.slotTexts[i]; txt.text = (i + 1) + '.' + (sv.saveFileExists ? sv.name : ''); if (sv.saveFileExists) { spr.visible = true; if (sv.inventory.sword === 1 && sv.inventory.shield === 1) { spr.setFrame(this.frames.getFrameByName('link4.png')); } else if (sv.inventory.shield === 1) { spr.setFrame(this.frames.getFrameByName('link3.png')); } else if (sv.inventory.sword === 1) { spr.setFrame(this.frames.getFrameByName('link2.png')); } else { spr.setFrame(this.frames.getFrameByName('link1.png')); } this._renderHearts(this.heartsGroups[i], sv.health, sv.maxHealth); } } } } private _renderHearts(group: Phaser.Group, value: number, max: number) { let x = 0; let y = 20; const size = 16; const perRow = 10; let done = 0; for (let hp = value; hp > 0; --hp) { done++; const spr = this.heartpool.alloc(); spr.setFrame(this.frames.getFrameByName(hp < 1 ? 'heart-half.png' : 'heart-full.png')); spr.position.x = x; spr.position.y = y + (hp < 1 ? 2 : 0); spr.visible = true; if ((x / size) >= (perRow - 1)) { x = 0; y += size; } else { x += size; } group.add(spr); } for (; done < max; ++done) { const spr = this.heartpool.alloc(); spr.setFrame(this.frames.getFrameByName('heart-empty.png')); spr.position.x = x; spr.position.y = y; spr.visible = true; if ((x / size) >= (perRow - 1)) { x = 0; y += size; } else { x += size; } group.add(spr); } } private _setupSelect() { this.selectGroup = this.add.group(this.world, 'select'); this.selectSprite = this.add.sprite(0, 0, 'sprite_select', 'select.png', this.selectGroup); this.selectSprite.name = 'select'; this.fairySprite = this.add.sprite(27, 72, 'sprite_select', null, this.selectGroup); this.fairySprite.animations.add('flap', ['fairy1.png', 'fairy2.png'], 6, true).play(); this.fairySprite.name = 'fairy'; this.linkSprites = [ this.add.sprite(52, 64, 'sprite_select', null, this.selectGroup), this.add.sprite(52, 96, 'sprite_select', null, this.selectGroup), this.add.sprite(52, 124, 'sprite_select', null, this.selectGroup), ]; this.linkSprites[0].visible = false; this.linkSprites[0].name = 'link-1'; this.linkSprites[1].visible = false; this.linkSprites[1].name = 'link-2'; this.linkSprites[2].visible = false; this.linkSprites[2].name = 'link-3'; this.heartsGroups = [ this.add.group(this.selectGroup, 'hearts-1'), this.add.group(this.selectGroup, 'hearts-2'), this.add.group(this.selectGroup, 'hearts-3'), ]; this.heartsGroups[0].position.set(142, 63); this.heartsGroups[1].position.set(142, 93); this.heartsGroups[2].position.set(142, 142); const textGroup = this.add.group(this.selectGroup, 'text'); textGroup.add(this.fontpool.alloc(false, 40, 25, 'PLAYER SELECT', 16)); textGroup.add(this.fontpool.alloc(false, 50, 178, 'COPY PLAYER', 16)); textGroup.add(this.fontpool.alloc(false, 50, 193, 'ERASE PLAYER', 16)); this.slotTexts = [ textGroup.add(this.fontpool.alloc(false, 72, 72, '1.', 16)), textGroup.add(this.fontpool.alloc(false, 72, 102, '2.', 16)), textGroup.add(this.fontpool.alloc(false, 72, 132, '3.', 16)), ]; } private _setupRegister() { this.registerGroup = this.add.group(this.world, 'register'); this.pointerSprite = this.add.sprite(30, 88, 'sprite_select', 'pointer.png', this.registerGroup); this.pointerSprite.name = 'pointer'; const textGroup = this.add.group(this.registerGroup, 'text'); const lines = [ 'ABCDEFGHIJ abcdefghij 01234', 'KLMNOPQRST klmnopqrst 56789', 'UVWXYZDPC uvwxyzDPC EQPP ', ' <> =+ <> =+ <> =+', ]; textGroup.add(this.fontpool.alloc(false, 40, 40, 'REGISTER YOUR NAME', 16)); this.pname = textGroup.add(this.fontpool.alloc(false, 30, 96, '', 16)); // create all the characters this.charactersGroup = this.add.group(textGroup, 'characters'); this.characters = []; const sx = 32; const sy = 125; let cx = sx; let cy = sy; for (let y = 0; y < lines.length; ++y) { this.characters[y] = []; const line = lines[y].split(''); for (let x = 0; x < line.length; ++x) { const txt = this.charactersGroup.add(this.fontpool.alloc(false, cx, cy)); this.characters[y][x] = txt; if (line[x] === '=') { txt.text = 'END'; txt.name = 'end'; } else if (line[x] === '+') { txt.text = ' '; txt.name = 'end'; } else if (line[x] === '<') { txt.text = '<'; txt.name = 'left'; } else if (line[x] === '>') { txt.text = '>'; txt.name = 'right'; } else { txt.text = line[x]; } cx += this.delta.x; } cy += this.delta.y; cx = sx; } this.line = this.add.graphics(24, 132, this.registerGroup); this.line.name = 'line'; this.line.lineStyle(1, 0xffffff, 1); this.line.moveTo(0, 0); this.line.lineTo(624, 0); this.registerSprite = this.add.sprite(0, 0, 'sprite_select', 'register.png', this.registerGroup); this.registerSprite.name = 'register'; this.registerGroup.visible = false; } private _onInputDown(key: number, value: number, event: any) { switch (key) { case Phaser.Keyboard.DOWN: case Phaser.Keyboard.S: case Phaser.Gamepad.XBOX360_DPAD_DOWN: this.move(Phaser.DOWN); break; case Phaser.Keyboard.UP: case Phaser.Keyboard.W: case Phaser.Gamepad.XBOX360_DPAD_UP: this.move(Phaser.UP); break; case Phaser.Keyboard.LEFT: case Phaser.Keyboard.A: case Phaser.Gamepad.XBOX360_DPAD_LEFT: this.move(Phaser.LEFT); break; case Phaser.Keyboard.RIGHT: case Phaser.Keyboard.D: case Phaser.Gamepad.XBOX360_DPAD_RIGHT: this.move(Phaser.RIGHT); break; case Phaser.Gamepad.XBOX360_STICK_LEFT_X: this.move(value > 0 ? Phaser.RIGHT : Phaser.LEFT); break; case Phaser.Gamepad.XBOX360_STICK_LEFT_Y: this.move(value > 0 ? Phaser.DOWN : Phaser.UP); break; case Phaser.Keyboard.ENTER: case Phaser.Keyboard.SPACEBAR: case Phaser.Gamepad.XBOX360_A: case Phaser.Gamepad.XBOX360_B: case Phaser.Gamepad.XBOX360_START: this.select(); break; } } private _onInputUp(key: number, value: number, event: any) { // abstract } }
the_stack
import test from 'ava'; import * as util from 'util'; import { nohm } from '../ts'; import * as args from './testArgs'; import { cleanUpPromise } from './helper'; const redis = args.redis; const prefix = args.prefix + 'validationTests'; test.before(async () => { nohm.setPrefix(prefix); await args.setClient(nohm, redis); await cleanUpPromise(redis, prefix); }); test.after(async () => { await cleanUpPromise(redis, prefix); }); nohm.setExtraValidations(__dirname + '/custom_validations.js'); const UserMockup = nohm.model('UserMockup', { // !!! this mockup must be defined with valid default values !!! properties: { name: { defaultValue: 'test', type: 'string', validations: ['notEmpty'], }, castInteger: { defaultValue: 2, type: 'integer', }, castFloat: { defaultValue: 2.5, type: 'float', }, castNumber: { defaultValue: 2.5, type: 'number', }, castTimestamp: { defaultValue: 100000, type: 'timestamp', }, behavior: { defaultValue: 1, type: function incrementBy(value, _key, old) { if (typeof value !== 'string' || typeof old !== 'string') { throw new Error('Behavior arguments were not strings!'); } return parseInt(old, 10) + parseInt(value, 10); }, }, minMax: { defaultValue: 5, type: 'integer', validations: [ { name: 'minMax', options: { min: 2, max: 20, }, }, ], }, minOptional: { defaultValue: 0, type: 'integer', validations: [ { name: 'minMax', options: { min: 10, optional: true, // this is a bit stupid. because 0 will trigger it as optional }, }, ], }, email: { defaultValue: 'blub@bla.de', type: 'string', validations: [ { name: 'length', // not needed for a normal email validation, using this to test multiple validations options: { min: 3, }, }, 'email', ], }, optionalEmail: { defaultValue: '', type: 'string', validations: [ { name: 'email', options: { optional: true, }, }, ], }, minLength: { defaultValue: 'asd', type: 'string', validations: [ { name: 'length', options: { min: 3, }, }, ], }, minLength2: { defaultValue: '', type: 'string', validations: [ { name: 'length', options: { min: 3, optional: true, }, }, ], }, maxLength: { defaultValue: 'asd', type: 'string', validations: [ { name: 'length', options: { max: 5, }, }, ], }, number: { defaultValue: '1,000.5623', type: 'string', validations: ['number'], }, numberUS: { defaultValue: '2,000.5623', type: 'string', validations: ['numberUS'], }, numberEU: { defaultValue: '3.000,5623', type: 'string', validations: ['numberEU'], }, numberSI: { defaultValue: '4 000,5623', type: 'string', validations: ['numberSI'], }, url: { defaultValue: 'http://test.de', type: 'string', validations: ['url'], }, custom: { defaultValue: 'valid', type: 'string', validations: [ (value) => { return Promise.resolve(value === 'valid'); }, ], }, custom2: { defaultValue: 'valid2', type: 'string', validations: [ (value) => { return Promise.resolve(value === 'valid2'); }, ], }, customNamed: { defaultValue: 'validNamed', type: 'string', validations: [ function /*test*/ customNamedFunc(value) { return Promise.resolve(value === 'validNamed'); }, ], }, customNamedAsync: { defaultValue: 'validNamedAsync', type: 'string', validations: [ async function customNamedAsyncFunc(value) { return Promise.resolve(value === 'validNamedAsync'); }, ], }, alphanumeric: { defaultValue: 'hurgel1234', type: 'string', validations: ['alphanumeric'], }, regexp: { defaultValue: 'asd1', type: 'string', validations: [ { name: 'regexp', options: { regex: /^asd[\d]+$/, optional: true, }, }, ], }, // TODO: write test for multi-validation properties /* TODO: re-enable once custom validations are implemented customValidationFile: { type: 'string', defaultValue: 'customValidationFile', validations: [ 'customValidationFile' ] }, customValidationFileOptional: { type: 'string', defaultValue: 'customValidationFile', validations: [ { name: 'customValidationFile', options: { optional: true } } ] }, customDependentValidation: { type: 'string', defaultValue: 'test', validations: [ { name: 'instanceValidation', options: { property: 'name' } } ] }*/ }, }); function testSimpleProps(t, props) { props.tests.forEach((prop) => { const user = new UserMockup(); user.property(props.name, prop.input); t.is( user.property(props.name), prop.expected, 'Setting the property ' + props.name + ' to ' + util.inspect(prop.input) + ' did not cast it to ' + util.inspect(prop.expected), ); }); } function testValidateProp(t, objectName, propName) { const tests: Array<() => void> = []; return { push: (expected, setValue) => { tests.push(() => { return (async () => { const obj = await nohm.factory(objectName); let setReturn = ''; if (typeof setValue !== 'undefined') { setReturn = obj.property(propName, setValue); } const valid = await obj.validate(propName); const errorStr = `Property '${propName}' was not validated properly. Details: object: ${objectName} prop: ${propName} value: ${util.inspect(setValue)} after casting: ${util.inspect(setReturn)} errors: ${util.inspect(obj.errors)}`; t.is(expected, valid, errorStr); })(); }); }, launch: async () => { const promises = tests.map((testFn) => testFn()); await Promise.all(promises); }, }; } test('default values validate', async (t) => { const user = new UserMockup(); const valid = await user.validate(); t.true(valid, 'The Model was not recognized as valid. Is it? Should be!'); }); test('castString', (t) => { const tests = { name: 'name', tests: [ { input: null, expected: '', }, { input: false, expected: '', }, { input: true, expected: '', }, { input: 0, expected: '', }, { input: {}, expected: '', }, { input: [], expected: '', }, ], }; testSimpleProps(t, tests); }); test('castInteger', (t) => { const tests = { name: 'castInteger', tests: [ { input: '15', expected: 15, }, { input: '15asd', expected: 15, }, { input: '1.5', expected: 1, }, { input: '0x15', expected: 0, }, { input: '.5', expected: 0, }, { input: '0.1e2', expected: 0, }, ], }; testSimpleProps(t, tests); }); test('castFloat', (t) => { const user = new UserMockup(); user.property('castFloat', '1.5'); t.is( user.property('castFloat'), 1.5, 'Setting a Float to a string "1.5" did not cast it to 1.5.', ); user.property('castFloat', '1.5asd'); t.is( user.property('castFloat'), 1.5, 'Setting a Float to a string "1.5asd" did not cast it to 1.5.', ); user.property('castFloat', '01.5'); t.is( user.property('castFloat'), 1.5, 'Setting a Float to a string "01.5" did not cast it to 1.5.', ); user.property('castFloat', '0x1.5'); t.is( user.property('castFloat'), 0, 'Setting a Float to a string "0x1.5" did not cast it to 0.', ); user.property('castFloat', '.5'); t.is( user.property('castFloat'), 0.5, 'Setting a Float to a string ".5" did not cast it to 0.5.', ); user.property('castFloat', '0.1e2'); t.is( user.property('castFloat'), 10, 'Setting a Float to a string "0.1e2" did not cast it to 10.', ); }); test('castNumber', (t) => { const user = new UserMockup(); user.property('castNumber', '1.5'); t.is( user.property('castNumber'), 1.5, 'Setting a Float to a string "1.5" did not cast it to 1.5.', ); user.property('castNumber', '1.5asd'); t.is( user.property('castNumber'), 1.5, 'Setting a Float to a string "1.5asd" did not cast it to 1.5.', ); user.property('castNumber', '01.5'); t.is( user.property('castNumber'), 1.5, 'Setting a Float to a string "01.5" did not cast it to 1.5.', ); user.property('castNumber', '0x1.5'); t.is( user.property('castNumber'), 0, 'Setting a Float to a string "0x1.5" did not cast it to 0.', ); user.property('castNumber', '.5'); t.is( user.property('castNumber'), 0.5, 'Setting a Float to a string ".5" did not cast it to 0.5.', ); user.property('castNumber', '0.1e2'); t.is( user.property('castNumber'), 10, 'Setting a Float to a string "0.1e2" did not cast it to 10.', ); }); test('castTimestamp', (t) => { const user = new UserMockup(); const should = new Date('1988-03-12T00:00:00Z').getTime().toString(); user.property('castTimestamp', should); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a number should did not cast it to ' + should, ); user.property('castTimestamp', '' + should); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a string "should" did not cast it to ' + should, ); user.property('castTimestamp', '1988-03-12T00:00:00Z'); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a string "1988-03-12T00:00:00Z" did not cast it to ' + should, ); user.property('castTimestamp', '1988-03-12 04:30:00 +04:30'); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a string "1988-03-12 04:30:00 +04:30" did not cast it to ' + should, ); user.property('castTimestamp', '1988-03-11 19:30:00 -04:30'); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a string "1988-03-11 20:30:00 -04:30" did not cast it to ' + should, ); user.property('castTimestamp', 'Sat, 12 Mar 1988 00:00:00'); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a string "Sat, 12 Mar 1988 00:00:00" did not cast it to ' + should, ); user.property('castTimestamp', '03.12.1988'); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a string "03.12.1988" did not cast it to ' + should, ); user.property('castTimestamp', '03/12/1988'); t.true( user.property('castTimestamp') === should, 'Setting a Timestamp to a string "03/12/1988" did not cast it to ' + should, ); }); test('behaviors', (t) => { const user = new UserMockup(); user.property('behavior', 5); t.is( user.property('behavior'), 6, 'Using the behavior did not work correctly', ); }); test('notEmpty', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'name'); tests.push(false, ''); tests.push(false, ' '); await tests.launch(); }); test('stringMinLength', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'minLength'); tests.push(false, 'as'); await tests.launch(); }); test('stringMaxLength', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'maxLength'); tests.push(false, 'asdasd'); await tests.launch(); }); test('stringLengthOptional', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'minLength2'); tests.push(true, ''); tests.push(false, 'as'); await tests.launch(); }); test('minMax', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'minMax'); tests.push(false, 1); tests.push(false, 21); await tests.launch(); }); test('minOptional', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'minOptional'); tests.push(true, 0); await tests.launch(); }); test('email', async (t) => { // this isn't really sufficient to ensure that the regex is really working correctly, but it's good enough for now. const tests = testValidateProp(t, 'UserMockup', 'email'); tests.push(true, 'asdasd@asd.de'); tests.push(true, 'asdasd+asd@asd.de'); tests.push(true, '"Abc\\@def"@example.com'); tests.push(true, '"Fred Bloggs"@example.com'); tests.push(true, '"Joe\\Blow"@example.com'); tests.push(true, '"Abc@def"@example.com'); tests.push(true, 'customer/department=shipping@example.com'); tests.push(true, '$A12345@example.com'); tests.push(true, '!def!xyz%abc@example.com'); tests.push(true, '_somename@example.com'); tests.push(false, 'somename@example'); tests.push(false, '@example.com'); tests.push(false, 'example'); tests.push(false, 'asd'); await tests.launch(); }); test('number', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'number'); tests.push(true, '0'); tests.push(true, '1'); tests.push(true, '-1'); tests.push(true, '10'); tests.push(true, '1000'); tests.push(true, '1,1'); tests.push(true, '1.1'); tests.push(true, '1.000,1'); tests.push(true, '1,000.1'); tests.push(true, '1 000.1'); tests.push(true, '1 000,1'); await tests.launch(); }); test('alphanumeric', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'alphanumeric'); tests.push(true, 'asd'); tests.push(true, '1234'); tests.push(false, ' asd'); tests.push(false, 'a$aa'); await tests.launch(); }); test('regexp', async (t) => { const tests = testValidateProp(t, 'UserMockup', 'regexp'); tests.push(true, 'asd1234123'); tests.push(true, 'asd1'); tests.push(true, ''); tests.push(false, ' asd'); tests.push(false, '12345'); await tests.launch(); }); /* TODO: Re-enable once custom validation is implemented test('customValidationFile', (t) => { const tests = testValidateProp(t, 'UserMockup', 'customValidationFile'); tests.push(false, 'somethingelse'); await tests.launch(); }); test('customValidationFileOptional', (t) => { const tests = testValidateProp(t, 'UserMockup', 'customValidationFileOptional'); tests.push(true, ''); await tests.launch(); }); test('customDependentValidation', (t) => { const tests = testValidateProp(t, 'UserMockup', 'customDependentValidation'); tests.push(true, 'test'); await tests.launch(); }); */ test('errorFromObject', async (t) => { const user = new UserMockup(); user.property('minMax', 'a'); await user.validate('minMax'); t.deepEqual(user.errors.minMax, ['minMax'], 'Error was incorrect'); }); test('consistency', async (t) => { const user = new UserMockup(); const valid1 = await user.validate('name'); const valid2 = await user.validate('email'); t.is( valid1, valid2, 'Validating two valid properties resulted in different outputs.', ); const valid3 = await user.validate(); t.is( valid1, valid3, 'Validating the entire Model had a different result than validating a single property.', ); }); test('functionArgument', async (t) => { const user = new UserMockup(); const valid = await user.validate(); t.is( valid, true, 'Validating with a function as the first arg did not call the callback with true as its first arg', ); user.property({ name: '', email: 'asd', }); const valid2 = await user.validate(); t.is( valid2, false, 'Validating with a function as the first arg did not call the callback with false as its first arg', ); }); test('errorsCleared', async (t) => { const user = new UserMockup(); user.property({ name: '', email: 'asd', }); await user.validate(); t.deepEqual( { user: user.errors.name, email: user.errors.email, }, { user: ['notEmpty'], email: ['email'], }, 'Validating a user did not set the user.errors properly.', ); user.property({ name: 'test', }); await user.validate(); t.deepEqual( { user: user.errors.name, email: user.errors.email, }, { user: [], email: ['email'], }, 'Validating a user did not reset the user.errors properly.', ); }); test('customErrorNames', async (t) => { const user = new UserMockup(); user.property({ custom: 'INVALID', custom2: 'INVALID', customNamed: 'INVALID', }); await user.validate(); t.deepEqual( { custom: user.errors.custom, custom2: user.errors.custom2, customNamed: user.errors.customNamed, }, { custom: ['custom_custom'], custom2: ['custom_custom2'], customNamed: ['custom_customNamedFunc'], }, 'Validating a user with custom validations failing did not put the proper error messages in user.errors.', ); }); test('customErrorNamesAsync', async (t) => { const user = new UserMockup(); user.property({ customNamedAsync: 'INVALID', }); await user.validate(); t.deepEqual( { customNamedAsync: user.errors.customNamedAsync, }, { customNamedAsync: ['custom_customNamedAsyncFunc'], }, 'Validating a user with custom validations failing did not put the proper error messages in user.errors.', ); }); test('invalidSaveResetsId', async (t) => { const user = new UserMockup(); user.property('name', ''); try { await user.save(); } catch (e) { t.true(e instanceof nohm.ValidationError, 'Unexpected error.'); } finally { t.is(user.id, null, 'The id of an invalid user was not reset properly.'); } }); test('skipValidation', async (t) => { const user = new UserMockup(); user.property('name', ''); try { await user.save({ skip_validation_and_unique_indexes: true }); t.notDeepEqual( user.id, null, 'The id of an invalid user with skip_validation was reset.', ); } catch (err) { t.fail('The validation has been run even though skip_validation was true.'); } }); test('invalid regexp option', async (t) => { const model = nohm.model( 'invalidRegexpOption', { properties: { noRegexp: { defaultValue: 'hurgel1234', type: 'string', validations: [ { name: 'regexp', options: { regex: 'invalidRegexp', }, }, ], }, }, }, true, ); const instance = new model(); try { await instance.validate(); t.fail('Validation did not throw with an invalid validation regexp'); } catch (err) { t.is( err.message, 'Option for regexp validation was not a RegExp object.', 'Wrong error thrown', ); } }); test('ValidationError only has objects for properties with errors', async (t) => { const user = new UserMockup(); user.property('name', ''); try { await user.save(); t.fail('Succeeded where it should not have.'); } catch (e) { t.true(e instanceof nohm.ValidationError, 'Unexpected error.'); const errorKeys = Object.keys(e.errors); t.deepEqual( ['name'], errorKeys, 'ValidationError was not restricted to error keys', ); } }); test('multiple validation failures produce multiple error entries', async (t) => { const user = new UserMockup(); user.property('email', 'a'); try { await user.save(); t.fail('Succeeded where it should not have.'); } catch (e) { t.deepEqual( ['length', 'email'], e.errors.email, 'ValidationError was not restricted to error keys', ); } }); test('ValidationError has modelName as property', async (t) => { const user = new UserMockup(); user.property('name', ''); try { await user.save(); t.fail('Succeeded where it should not have.'); } catch (e) { t.deepEqual( e.modelName, user.modelName, "ValidationError didn't have the right modelName set", ); } });
the_stack
'use strict'; import * as vscode from 'vscode'; import { EOL, platform } from 'os' import * as cp from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import { Platform, Operator, Operators, Register } from './language'; import { BuildTaskProvider } from './buildTaskProvider'; import { Console } from 'console'; let currentPlatform: Platform = Platform.x86; let functions: Map<vscode.Uri, XSharpFunction[]> = new Map<vscode.Uri, XSharpFunction[]>(); let compilerPath: string; let taskProvider: vscode.Disposable; let storagePath: string; // settings let compileOnSave: boolean; let compileOutputPath: string; let nasmPath: string; export function activate(context: vscode.ExtensionContext) { //compilerPath = context.asAbsolutePath("compiler/xsc.exe"); storagePath = context.storagePath != undefined ? context.storagePath : context.extensionPath; compileOnSave = vscode.workspace.getConfiguration("xsharp").get<boolean>("compileOnSave"); compileOutputPath = vscode.workspace.getConfiguration("xsharp").get<string>("compileOutputPath"); compilerPath = vscode.workspace.getConfiguration("xsharp").get<string>("compilerPath"); nasmPath = vscode.workspace.getConfiguration("xsharp").get<string>("nasmPath"); checkCompilerPathSet(); taskProvider = vscode.tasks.registerTaskProvider("process", new BuildTaskProvider("")); let compileAsmToBin = vscode.commands.registerCommand("xsharp.createBin", function (){ if(compileOutputPath == ""){ vscode.window.showErrorMessage("Output path for compiler must be set!"); return; } if(fs.readdirSync(compileOutputPath).length == 0){ vscode.window.showErrorMessage("No files found in " + compileOutputPath + " to convert to bin"); return; } if(nasmPath == ""){ vscode.window.showErrorMessage("Nasm Path must be set!"); return; } let files : string[] = []; fs.readdirSync(compileOutputPath).forEach(file => { if(path.extname(file) == ".asm"){ files.push(path.join(compileOutputPath, file)); console.log("Adding " + path.join(compileOutputPath, file) + " to files to convert"); } }); let command = "\"" + nasmPath + "\" -f bin -o " + compileOutputPath + "output.bin "; files.forEach(f => command += "\"" + f + "\" "); console.log("Executing command: " + command); cp.exec(command, (error, stdout, stderr) => { if(error != null){ console.log("Error: " + error.message); vscode.window.showErrorMessage("Error while running nasm: " + error.message); } console.log("stdout: " + stdout) }); vscode.window.showInformationMessage("Succesfully created output.bin file!"); }); let languageCompileFile = vscode.commands.registerTextEditorCommand("xsharp.compileFile", function (textEditor) { checkCompilerPathSet(); if(compileOutputPath == ""){ compileOutputPath = path.join(path.dirname(textEditor.document.fileName), "/bin/"); vscode.workspace.getConfiguration("xsharp").update("compileOutputPath", compileOutputPath); } console.log("Triggered compile single file"); if (vscode.languages.match("xsharp", textEditor.document)) { let unsaved: boolean = false; if (textEditor.document.isDirty) { unsaved = true; } compileDocument(textEditor.document, true); vscode.window.showInformationMessage("Compiled current file"); } }); let languageCompileAllFiles = vscode.commands.registerTextEditorCommand("xsharp.compileAllFiles", function (textEditor) { checkCompilerPathSet(); if(compileOutputPath == ""){ compileOutputPath = path.join(path.dirname(textEditor.document.fileName), "/bin/") } let visibleDocumentsUri: vscode.Uri[] = new Array<vscode.Uri>(); vscode.window.visibleTextEditors.forEach(function (textEditor) { if (vscode.languages.match("xsharp", textEditor.document)) { visibleDocumentsUri.push(textEditor.document.uri); compileDocument(textEditor.document, textEditor.document.isDirty) } }); vscode.workspace.findFiles("*.xs").then(function (uri) { uri.forEach(u => function () { if (visibleDocumentsUri.find(docUri => docUri == u) == undefined) { let textDoc = vscode.workspace.textDocuments.find(doc => doc.uri == u); if (textDoc != undefined) { compileDocument(textDoc); } else { vscode.workspace.openTextDocument(u).then(compileDocument); } } }); }); vscode.window.showInformationMessage("Compiled all files in current directory"); }); if (vscode.workspace.rootPath != undefined) { vscode.workspace.findFiles("*.xs").then(function (uri) { uri.forEach(u => vscode.workspace.openTextDocument(u).then(parseFunctions)); }) } else { vscode.window.visibleTextEditors.forEach(e => parseFunctions(e.document)); } let languageOnActiveTextEditorChanged = vscode.window.onDidChangeActiveTextEditor(function (e) { if (e != undefined && vscode.languages.match("xsharp", e.document)) { //updateCurrentPlatform(e); } }); let languageOnTextSelectionChanged = vscode.window.onDidChangeTextEditorSelection(function (e) { if (e.textEditor.document.languageId == "xsharp" && (currentPlatform == undefined || e.selections.find(s => s.intersection(e.textEditor.document.lineAt(0).range) != undefined) != undefined)) { //updateCurrentPlatform(e.textEditor); } }); let languageOnDocumentOpened = vscode.workspace.onDidOpenTextDocument(function (e) { if (vscode.languages.match("xsharp", e)) { parseFunctions(e); } }); let languageOnDocumentSaved = vscode.workspace.onDidSaveTextDocument(function (e) { if (vscode.languages.match("xsharp", e)) { parseFunctions(e); if (compileOnSave) { compileDocument(e); } } }); let languageHoverProvider = vscode.languages.registerHoverProvider("xsharp", { provideHover(document, position, token) { let text = document.getText(document.getWordRangeAtPosition(position, /\w+/g)); let registers = currentPlatform.Registers; if (registers.some(r => r.Name == text)) { return new vscode.Hover(registers.find(r => r.Name == text).Description); } else { let regexp = new RegExp(Operators.map(o => escapeRegExp(o.Symbol)).join("|")); let operator = document.getText(document.getWordRangeAtPosition(position, regexp)); if (Operators.some(o => o.Symbol == operator)) { return new vscode.Hover(Operators.find(o => o.Symbol == operator).Description); } } } }); let languageCompletionProvider = vscode.languages.registerCompletionItemProvider("xsharp", { provideCompletionItems(document, position, token) { let completionList = new vscode.CompletionList(); currentPlatform.Registers.forEach(r => completionList.items.push(new vscode.CompletionItem(r.Name, vscode.CompletionItemKind.Variable))); functions.forEach(u => u.forEach(f => completionList.items.push(new vscode.CompletionItem(f.Name, vscode.CompletionItemKind.Function)))) return completionList; } }, ""); let languageSymbolDefinitions = vscode.languages.registerDefinitionProvider("xsharp", { provideDefinition(document, position, token) { let functionWordRange = document.getWordRangeAtPosition(position, /\w+(?=\(\))/g); if (functionWordRange != undefined) { let functionName = document.getText(functionWordRange); let xsharpFunction: XSharpFunction; for (let functionsArray of functions.values()) { xsharpFunction = functionsArray.find(f => f.Name == functionName); if (xsharpFunction != undefined) { return xsharpFunction.Location; } } } } }); // let languageOnTypeFormattingEditProvider = vscode.languages.registerOnTypeFormattingEditProvider("xsharp", { // provideOnTypeFormattingEdits(document, position, token) { // let wordRange = document.getWordRangeAtPosition(position, /\/?\*/g); // if (position.isEqual(wordRange.end)) { // let insertSpaces = vscode.window.activeTextEditor.options.insertSpaces; // let tabSize = <number>vscode.window.activeTextEditor.options.tabSize; // let tab = insertSpaces ? " ".repeat(tabSize) : "\t"; // let newLine = EOL; // if (wordRange.start.character > 0) { // if (insertSpaces) { // newLine += " ".repeat(wordRange.start.character + 1); // } // else { // // needs testing // newLine += "\t".repeat((wordRange.start.character + 1) / tabSize) + // " ".repeat((wordRange.start.character + 1) % tabSize); // } // } // return [new vscode.TextEdit(new vscode.Range(new vscode.Position(position.line + 1, (newLine + tab).length), // new vscode.Position(position.line + 1, (newLine + tab).length)), newLine + tab + newLine + "*/")]; // } // } // }, "*", EOL); context.subscriptions.push(languageOnActiveTextEditorChanged); context.subscriptions.push(languageOnTextSelectionChanged); context.subscriptions.push(languageOnDocumentOpened); context.subscriptions.push(languageOnDocumentSaved); context.subscriptions.push(languageHoverProvider); context.subscriptions.push(languageCompletionProvider); context.subscriptions.push(languageSymbolDefinitions); //context.subscriptions.push(languageOnTypeFormattingEditProvider); } async function checkCompilerPathSet() { compilerPath = vscode.workspace.getConfiguration("xsharp").get("compilerPath"); while (compilerPath == "") { compilerPath = await vscode.window.showInputBox({prompt:"Path to compiler", ignoreFocusOut: true}); } vscode.workspace.getConfiguration("xsharp").update("compilerPath", compilerPath); } export function deactivate() : void{ if (taskProvider) { taskProvider.dispose(); } } function updateCurrentPlatform(e: vscode.TextEditor) { // currently X# only supports x86 if (e.document.languageId == "xsharp") { let firstLine = e.document.lineAt(0).text; if (firstLine.startsWith("#define Platform ")) { let platform = Platform[firstLine.replace("#define Platform ", "").trim()]; if (platform != undefined) { currentPlatform = platform; } } } } function parseFunctions(document: vscode.TextDocument) { if (functions.has(document.uri)) { functions.get(document.uri).length = 0; } else { functions.set(document.uri, []); } for (var i = 0; i < document.lineCount; i++) { let line = document.lineAt(i); let regexp = /function (\w+)/g; var result: RegExpExecArray; while ((result = regexp.exec(line.text)) !== null) { functions.get(document.uri).push(new XSharpFunction(result[1], new vscode.Location(document.uri, new vscode.Position(i, result.index + "function ".length)))); regexp.lastIndex++; } } } function compileDocument(document: vscode.TextDocument, unsaved: boolean = false) { let inputPath: string; if (unsaved) { if (!fs.existsSync(storagePath)) { fs.mkdirSync(storagePath); } let i: number = 1; while (fs.existsSync(inputPath = path.join(storagePath, "temp_" + i + ".xs"))) { i++; } fs.writeFileSync(inputPath, document.getText()); } else { inputPath = document.uri.fsPath; } if (!fs.existsSync(compileOutputPath)) { fs.mkdirSync(compileOutputPath); } let passed : boolean = false; try { var command = compilerPath + " " + inputPath + " -Out:" + path.join(compileOutputPath, path.basename(document.fileName).replace(".xs", ".asm")) + " -Gen2 -CPU:X86"; cp.exec(command, (error, stdout, sterr) => { if(error != null){ console.log("error: " + error.name + error.message) vscode.window.showErrorMessage("Error while compiling: " + error.message); } else{ passed = true; } }); } catch (e){ console.log("error:" + e); } finally { if (unsaved && passed) { fs.unlinkSync(inputPath); } } } class XSharpFunction { Name: string; Location: vscode.Location; constructor(name: string, location: vscode.Location) { this.Name = name; this.Location = location; } } function escapeRegExp(str: string) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }
the_stack
import { CancellationToken } from 'vscode-languageserver'; import { getFileInfo } from '../analyzer/analyzerNodeInfo'; import { Declaration, isAliasDeclaration, isClassDeclaration, isFunctionDeclaration, isParameterDeclaration, isVariableDeclaration, ModuleLoaderActions, } from '../analyzer/declaration'; import { createSynthesizedAliasDeclaration, getNameFromDeclaration, isDefinedInFile, } from '../analyzer/declarationUtils'; import { ImportResolver } from '../analyzer/importResolver'; import { getRelativeModuleName, getTextEditsForAutoImportInsertions, getTextEditsForAutoImportSymbolAddition, getTopLevelImports, ImportNameInfo, ImportNameWithModuleInfo, ImportStatements, } from '../analyzer/importStatementUtils'; import { getDottedName, getDottedNameWithGivenNodeAsLastName, isLastNameOfDottedName, } from '../analyzer/parseTreeUtils'; import { ParseTreeWalker } from '../analyzer/parseTreeWalker'; import { ScopeType } from '../analyzer/scope'; import { getScopeForNode } from '../analyzer/scopeUtils'; import { TypeEvaluator } from '../analyzer/typeEvaluatorTypes'; import { throwIfCancellationRequested } from '../common/cancellationUtils'; import { addIfUnique, createMapFromItems, getOrAdd, removeArrayElements } from '../common/collectionUtils'; import { ConfigOptions } from '../common/configOptions'; import { TextEditAction } from '../common/editAction'; import { getDirectoryPath } from '../common/pathUtils'; import { convertOffsetToPosition } from '../common/positionUtils'; import { TextRange } from '../common/textRange'; import { ModuleNameNode, NameNode, ParseNode, ParseNodeType } from '../parser/parseNodes'; import { ParseResults } from '../parser/parser'; export interface ImportData { containsUnreferenceableSymbols: boolean; declarations: Map<Declaration, NameNode[]>; } export class ImportAdder { constructor( private _configOptions: ConfigOptions, private _importResolver: ImportResolver, private _evaluator: TypeEvaluator ) {} collectImportsForSymbolsUsed(parseResults: ParseResults, range: TextRange, token: CancellationToken): ImportData { const collector = new NameCollector(this._evaluator, parseResults, range, token); collector.walk(parseResults.parseTree); return { containsUnreferenceableSymbols: collector.containsUnreferenceableSymbols, declarations: collector.declsForSymbols, }; } applyImports( result: ImportData, parseResults: ParseResults, insertionPosition: number, token: CancellationToken ): TextEditAction[] { throwIfCancellationRequested(token); const filePath = getFileInfo(parseResults.parseTree).filePath; const importStatements = getTopLevelImports(parseResults.parseTree); const execEnv = this._configOptions.findExecEnvironment(filePath); const importNameInfo: ImportNameWithModuleInfo[] = []; for (const decl of result.declarations.keys() ?? []) { const importInfo = this._getImportInfo(decl, filePath); if (!importInfo) { continue; } const moduleAndType = this._importResolver.getModuleNameForImport(importInfo.filePath, execEnv); if (!moduleAndType.moduleName) { if (!importInfo.nameInfo.name) { continue; } // module can't be addressed by absolute path in "from import" statement. // ex) namespace package at [workspace root] or [workspace root]\__init__.py(i) // use relative path moduleAndType.moduleName = getRelativeModuleName( this._importResolver.fileSystem, filePath, importInfo.filePath ); } addIfUnique( importNameInfo, { module: moduleAndType, name: importInfo.nameInfo.name, alias: importInfo.nameInfo.alias }, (a, b) => this._areSame(a, b) ); } const edits: TextEditAction[] = []; const newNameInfo: ImportNameWithModuleInfo[] = []; for (const moduleAndInfo of createMapFromItems(importNameInfo, (i) => i.module.moduleName)) { if (!this._tryProcessExistingImports(moduleAndInfo, importStatements, parseResults, edits)) { newNameInfo.push(...moduleAndInfo[1]); continue; } } edits.push( ...getTextEditsForAutoImportInsertions( newNameInfo, importStatements, parseResults, convertOffsetToPosition(insertionPosition, parseResults.tokenizerOutput.lines) ) ); return edits; } private _tryProcessExistingImports( moduleAndInfo: [string, ImportNameWithModuleInfo[]], importStatements: ImportStatements, parseResults: ParseResults, edits: TextEditAction[] ) { for (const kindAndImports of createMapFromItems( importStatements.orderedImports.filter((i) => i.moduleName === moduleAndInfo[0]), (i) => (i.node.nodeType === ParseNodeType.Import ? 'import' : 'importFrom') )) { if (kindAndImports[0] === 'importFrom') { // We can't merge to "from module import *" statement. const imported = kindAndImports[1].filter( (i) => i.node.nodeType === ParseNodeType.ImportFrom && !i.node.isWildcardImport ); if (imported.length === 0) { // No regular from import statement. continue; } // get name info that don't exist in any of existing import statements. const info = moduleAndInfo[1].filter( (m) => !imported.some( (n) => n.node.nodeType === ParseNodeType.ImportFrom && n.node.imports.some((i) => i.name.value === m.name && i.alias?.value === m.alias) ) ); edits.push(...getTextEditsForAutoImportSymbolAddition(info, imported[0], parseResults)); return true; } if (kindAndImports[0] === 'import') { // import statement already exists. skip those module info. removeArrayElements( moduleAndInfo[1], (i) => !i.name && kindAndImports[1].some((n) => i.alias === n.subnode?.alias?.value) ); continue; } } return false; } private _getImportInfo( decl: Declaration, destFilePath: string ): { filePath: string; nameInfo: ImportNameInfo } | undefined { if (isAliasDeclaration(decl)) { if (!decl.node) { // This is synthesized decl for implicit module case such as "import a.b" return { filePath: decl.path, nameInfo: {} }; } if (decl.node.nodeType === ParseNodeType.ImportAs) { const importDecl = this._evaluator.getDeclarationsForNameNode( decl.node.module.nameParts[decl.node.module.nameParts.length - 1] ); if (!importDecl || importDecl.length === 0) { // We have no idea where it came from. // ex) from unknown import unknown return undefined; } return { filePath: importDecl[0].path, nameInfo: { alias: decl.usesLocalName ? decl.node.alias?.value : undefined }, }; } if (decl.node.nodeType === ParseNodeType.ImportFromAs) { let path: string | undefined = decl.path; if (!path) { // Check submodule case with no __init__ if (decl.submoduleFallback) { path = getDirectoryPath(decl.submoduleFallback.path); } } if (!path) { // We have no idea where it came from. // ex) from unknown import unknown return undefined; } if (path === destFilePath && !decl.usesLocalName && !decl.submoduleFallback) { // Don't create import for the symbol (not module) defined in the current file // unless alias is used. // // We don't check insertion point since we don't create type alias for decl defined later // anyway. but in future, we could consider either rewrite or creating type alias for symbols // defined after insertion point. return undefined; } return { filePath: path, nameInfo: { name: decl.symbolName, alias: decl.usesLocalName ? decl.node.alias?.value : undefined, }, }; } if (decl.node.nodeType === ParseNodeType.ImportFrom) { return { filePath: decl.path, nameInfo: { name: decl.symbolName }, }; } } if (isVariableDeclaration(decl) || isFunctionDeclaration(decl) || isClassDeclaration(decl)) { const name = getNameFromDeclaration(decl); if (!name) { return undefined; } return { filePath: decl.path, nameInfo: { name }, }; } return undefined; } private _areSame(a: ImportNameWithModuleInfo, b: ImportNameWithModuleInfo) { return ( a.alias === b.alias && a.name === b.name && a.module.importType === b.module.importType && a.module.isLocalTypingsFile === b.module.isLocalTypingsFile && a.module.moduleName === b.module.moduleName ); } } class NameCollector extends ParseTreeWalker { private readonly _filePath: string; // Hold onto names that we need to move imports. readonly declsForSymbols = new Map<Declaration, NameNode[]>(); containsUnreferenceableSymbols = false; constructor( private _evaluator: TypeEvaluator, private _parseResults: ParseResults, private _range: TextRange, private _token: CancellationToken ) { super(); this._filePath = getFileInfo(this._parseResults.parseTree).filePath; // For now, we assume the given range is at right boundary such as statement, statements, expression or expressions. // In future, we might consider validating the range and adjusting it to the right boundary if needed. } override walk(node: ParseNode) { if (!TextRange.overlapsRange(this._range, node)) { return; } super.walk(node); } override visitModuleName(node: ModuleNameNode) { // We only care about references to module symbols. not decls. return false; } override visitName(name: NameNode) { throwIfCancellationRequested(this._token); // We process dotted name as a whole rather than // process each part of dotted name. if (!isLastNameOfDottedName(name)) { return false; } const dottedName = getDottedName(getDottedNameWithGivenNodeAsLastName(name)); if (!dottedName) { // Not dotted name // ex) foo().[var] return false; } // See whether the first dotted name bound to symbols defined in current file. const firstName = dottedName[0]; const firstNameDecls = this._getDeclarationsInModule(firstName); if (!firstNameDecls || firstNameDecls.length === 0) { return false; } // Simple case. // ex) import os // [os] if (dottedName.length === 1) { this._handleName(firstName, firstNameDecls); return false; } for (const firstNameDecl of firstNameDecls) { if (!isAliasDeclaration(firstNameDecl) || firstNameDecl.node.nodeType !== ParseNodeType.ImportAs) { // decls we have is for symbols defined in current module. // ex) [foo]() this._handleName(firstName, [firstNameDecl]); continue; } // Import with alias // ex) import json.encoder as j if (firstNameDecl.usesLocalName) { this._handleName(firstName, [firstNameDecl]); continue; } // Special casing import statement with sub module ex) import a.[b] // It is complex for import a.[b] case since decl for [b] doesn't exist. so // when binding a.[b].foo(), we don't get decl for "import a.[b]", we need to // do some tree walk to find import a.[b] and synthesize decl for it. this._handleImplicitImports(firstNameDecl, dottedName, 1); } return false; } private _getDeclarationsInModule(name: NameNode) { return this._evaluator.getDeclarationsForNameNode(name)?.filter((d) => isDefinedInFile(d, this._filePath)); } private _handleImplicitImports( aliasDecl: { path: string; implicitImports?: Map<string, ModuleLoaderActions> }, dottedName: NameNode[], nameIndex: number ) { if (dottedName.length === nameIndex) { return; } if (!aliasDecl.implicitImports) { this._handleName(dottedName[nameIndex - 1], [createSynthesizedAliasDeclaration(aliasDecl.path)]); return; } const implicitImportDecl = aliasDecl.implicitImports.get(dottedName[nameIndex].value); if (!implicitImportDecl) { this._handleName(dottedName[nameIndex - 1], [createSynthesizedAliasDeclaration(aliasDecl.path)]); return; } this._handleImplicitImports(implicitImportDecl, dottedName, nameIndex + 1); } private _handleName(name: NameNode, decls: Declaration[]) { for (const decl of decls) { if (decl.node && TextRange.containsRange(this._range, decl.node)) { // Make sure our range doesn't already contain them. continue; } if (isParameterDeclaration(decl)) { // Parameter is not referenceable from import statement. this.containsUnreferenceableSymbols = true; continue; } if (isVariableDeclaration(decl) || isFunctionDeclaration(decl) || isClassDeclaration(decl)) { // For now, we will allow private variable to be referenced by import // so that user can fix it up once import is added. // We only support top level variables. const scope = getScopeForNode(name); if (!scope) { this.containsUnreferenceableSymbols = true; continue; } const result = scope.lookUpSymbolRecursive(name.value); if (!result || result.scope.type !== ScopeType.Module) { this.containsUnreferenceableSymbols = true; continue; } } this._addName(decl, name); } } private _addName(decl: Declaration, name: NameNode) { getOrAdd(this.declsForSymbols, decl, () => []).push(name); } }
the_stack
import debugModule from "debug"; const debug = debugModule("codec:storage:allocate"); import * as Compiler from "@truffle/codec/compiler"; import * as Common from "@truffle/codec/common"; import * as Basic from "@truffle/codec/basic"; import type * as Storage from "@truffle/codec/storage/types"; import * as Utils from "@truffle/codec/storage/utils"; import * as Ast from "@truffle/codec/ast"; import type * as Pointer from "@truffle/codec/pointer"; import type { StorageAllocation, StorageAllocations, StorageMemberAllocation, StateAllocation, StateAllocations, StateVariableAllocation } from "./types"; import type { ContractAllocationInfo } from "@truffle/codec/abi-data/allocate"; import type { ImmutableReferences } from "@truffle/contract-schema/spec"; import * as Evm from "@truffle/codec/evm"; import * as Format from "@truffle/codec/format"; import BN from "bn.js"; import partition from "lodash.partition"; export { StorageAllocation, StorageAllocations, StorageMemberAllocation, StateAllocation, StateAllocations, StateVariableAllocation }; export class UnknownBaseContractIdError extends Error { public derivedId: number; public derivedName: string; public derivedKind: string; public baseId: number; constructor( derivedId: number, derivedName: string, derivedKind: string, baseId: number ) { const message = `Cannot locate base contract ID ${baseId} of ${derivedKind} ${derivedName} (ID ${derivedId})`; super(message); this.name = "UnknownBaseContractIdError"; this.derivedId = derivedId; this.derivedName = derivedName; this.derivedKind = derivedKind; this.baseId = baseId; } } interface StorageAllocationInfo { size: Storage.StorageLength; allocations: StorageAllocations; } //contracts contains only the contracts to be allocated; any base classes not //being allocated should just be in referenceDeclarations export function getStorageAllocations( userDefinedTypesByCompilation: Format.Types.TypesByCompilationAndId ): StorageAllocations { let allocations: StorageAllocations = {}; for (const compilation of Object.values(userDefinedTypesByCompilation)) { const { compiler, types: userDefinedTypes } = compilation; for (const dataType of Object.values(compilation.types)) { if (dataType.typeClass === "struct") { try { allocations = allocateStruct( dataType, userDefinedTypes, allocations, compiler ); } catch { //if allocation fails... oh well, allocation fails, we do nothing and just move on :P //note: a better way of handling this would probably be to *mark* it //as failed rather than throwing an exception as that would lead to less //recomputation, but this is simpler and I don't think the recomputation //should really be a problem } } } } return allocations; } /** * This function gets allocations for the state variables of the contracts; * this is distinct from getStorageAllocations, which gets allocations for * storage structs. * * While mostly state variables are kept in storage, constant ones are not. * And immutable ones, once those are introduced, will be kept in code! * (But those don't exist yet so this function doesn't handle them yet.) */ export function getStateAllocations( contracts: ContractAllocationInfo[], referenceDeclarations: { [compilationId: string]: Ast.AstNodes }, userDefinedTypes: Format.Types.TypesById, storageAllocations: StorageAllocations, existingAllocations: StateAllocations = {} ): StateAllocations { let allocations = existingAllocations; for (const contractInfo of contracts) { let { contractNode: contract, immutableReferences, compiler, compilationId } = contractInfo; try { allocations = allocateContractState( contract, immutableReferences, compilationId, compiler, referenceDeclarations[compilationId], userDefinedTypes, storageAllocations, allocations ); } catch { //we're just going to allow failure here and catch the problem elsewhere } } return allocations; } function allocateStruct( dataType: Format.Types.StructType, userDefinedTypes: Format.Types.TypesById, existingAllocations: StorageAllocations, compiler?: Compiler.CompilerVersion ): StorageAllocations { //NOTE: dataType here should be a *stored* type! //it is up to the caller to take care of this return allocateMembers( dataType.id, dataType.memberTypes, userDefinedTypes, existingAllocations, compiler ); } function allocateMembers( parentId: string, members: Format.Types.NameTypePair[], userDefinedTypes: Format.Types.TypesById, existingAllocations: StorageAllocations, compiler?: Compiler.CompilerVersion ): StorageAllocations { let offset: number = 0; //will convert to BN when placing in slot let index: number = Evm.Utils.WORD_SIZE - 1; //don't allocate things that have already been allocated if (parentId in existingAllocations) { return existingAllocations; } let allocations = { ...existingAllocations }; //otherwise, we'll be adding to this, so we better clone //otherwise, we need to allocate let memberAllocations: StorageMemberAllocation[] = []; for (const member of members) { let size: Storage.StorageLength; ({ size, allocations } = storageSizeAndAllocate( member.type, userDefinedTypes, allocations, compiler )); //if it's sized in words (and we're not at the start of slot) we need to start on a new slot //if it's sized in bytes but there's not enough room, we also need a new slot if ( Utils.isWordsLength(size) ? index < Evm.Utils.WORD_SIZE - 1 : size.bytes > index + 1 ) { index = Evm.Utils.WORD_SIZE - 1; offset += 1; } //otherwise, we remain in place let range: Storage.Range; if (Utils.isWordsLength(size)) { //words case range = { from: { slot: { offset: new BN(offset) //start at the current slot... }, index: 0 //...at the beginning of the word. }, to: { slot: { offset: new BN(offset + size.words - 1) //end at the current slot plus # of words minus 1... }, index: Evm.Utils.WORD_SIZE - 1 //...at the end of the word. } }; } else { //bytes case range = { from: { slot: { offset: new BN(offset) //start at the current slot... }, index: index - (size.bytes - 1) //...early enough to fit what's being allocated. }, to: { slot: { offset: new BN(offset) //end at the current slot... }, index: index //...at the current position. } }; } memberAllocations.push({ name: member.name, type: member.type, pointer: { location: "storage", range } }); //finally, adjust the current position. //if it was sized in words, move down that many slots and reset position w/in slot if (Utils.isWordsLength(size)) { offset += size.words; index = Evm.Utils.WORD_SIZE - 1; } //if it was sized in bytes, move down an appropriate number of bytes. else { index -= size.bytes; //but if this puts us into the next word, move to the next word. if (index < 0) { index = Evm.Utils.WORD_SIZE - 1; offset += 1; } } } //finally, let's determine the overall siz; we're dealing with a struct, so //the size is measured in words //it's one plus the last word used, i.e. one plus the current word... unless the //current word remains entirely unused, then it's just the current word //SPECIAL CASE: if *nothing* has been used, allocate a single word (that's how //empty structs behave in versions where they're legal) let totalSize: Storage.StorageLength; if (index === Evm.Utils.WORD_SIZE - 1 && offset !== 0) { totalSize = { words: offset }; } else { totalSize = { words: offset + 1 }; } //having made our allocation, let's add it to allocations! allocations[parentId] = { members: memberAllocations, size: totalSize }; //...and we're done! return allocations; } function getStateVariables(contractNode: Ast.AstNode): Ast.AstNode[] { // process for state variables return contractNode.nodes.filter( (node: Ast.AstNode) => node.nodeType === "VariableDeclaration" && node.stateVariable ); } function allocateContractState( contract: Ast.AstNode, immutableReferences: ImmutableReferences, compilationId: string, compiler: Compiler.CompilerVersion, referenceDeclarations: Ast.AstNodes, userDefinedTypes: Format.Types.TypesById, storageAllocations: StorageAllocations, existingAllocations: StateAllocations = {} ): StateAllocations { //we're going to do a 2-deep clone here let allocations: StateAllocations = Object.assign( {}, ...Object.entries(existingAllocations).map( ([compilationId, compilationAllocations]) => ({ [compilationId]: { ...compilationAllocations } }) ) ); if (!immutableReferences) { immutableReferences = {}; //also, let's set this up for convenience } //base contracts are listed from most derived to most base, so we //have to reverse before processing, but reverse() is in place, so we //clone with slice first let linearizedBaseContractsFromBase: number[] = contract.linearizedBaseContracts .slice() .reverse(); //first, let's get all the variables under consideration let variables = [].concat( ...linearizedBaseContractsFromBase.map((id: number) => { let baseNode = referenceDeclarations[id]; if (baseNode === undefined) { throw new UnknownBaseContractIdError( contract.id, contract.name, contract.contractKind, id ); } return getStateVariables(baseNode).map(definition => ({ definition, definedIn: baseNode })); }) ); //just in case the constant field ever gets removed const isConstant = (definition: Ast.AstNode) => definition.constant || definition.mutability === "constant"; //now: we split the variables into storage, constant, and code let [constantVariables, variableVariables] = partition(variables, variable => isConstant(variable.definition) ); //why use this function instead of just checking //definition.mutability? //because of a bug in Solidity 0.6.5 that causes the mutability field //not to exist. So, we also have to check against immutableReferences. const isImmutable = (definition: Ast.AstNode) => definition.mutability === "immutable" || definition.id.toString() in immutableReferences; let [immutableVariables, storageVariables] = partition( variableVariables, variable => isImmutable(variable.definition) ); //transform storage variables into data types const storageVariableTypes = storageVariables.map(variable => ({ name: variable.definition.name, type: Ast.Import.definitionToType( variable.definition, compilationId, compiler ) })); //let's allocate the storage variables using a fictitious ID const id = "-1"; const storageVariableStorageAllocations = allocateMembers( id, storageVariableTypes, userDefinedTypes, storageAllocations, compiler )[id]; //transform to new format const storageVariableAllocations = storageVariables.map( ({ definition, definedIn }, index) => ({ definition, definedIn, compilationId, pointer: storageVariableStorageAllocations.members[index].pointer }) ); //now let's create allocations for the immutables let immutableVariableAllocations = immutableVariables.map( ({ definition, definedIn }) => { let references = immutableReferences[definition.id.toString()] || []; let pointer: Pointer.CodeFormPointer; if (references.length === 0) { pointer = { location: "nowhere" as const }; } else { pointer = { location: "code" as const, start: references[0].start, length: references[0].length }; } return { definition, definedIn, compilationId, pointer }; } ); //and let's create allocations for the constants let constantVariableAllocations = constantVariables.map( ({ definition, definedIn }) => ({ definition, definedIn, compilationId, pointer: { location: "definition" as const, definition: definition.value } }) ); //now, reweave the three together let contractAllocation: StateVariableAllocation[] = []; for (let variable of variables) { let arrayToGrabFrom = isConstant(variable.definition) ? constantVariableAllocations : isImmutable(variable.definition) ? immutableVariableAllocations : storageVariableAllocations; contractAllocation.push(arrayToGrabFrom.shift()); //note that push and shift both modify! } //finally, set things and return if (!allocations[compilationId]) { allocations[compilationId] = {}; } allocations[compilationId][contract.id] = { members: contractAllocation }; return allocations; } //NOTE: This wrapper function is for use in decoding ONLY, after allocation is done. //The allocator should (and does) instead use a direct call to storageSizeAndAllocate, //not to the wrapper, because it may need the allocations returned. export function storageSize( dataType: Format.Types.Type, userDefinedTypes?: Format.Types.TypesById, allocations?: StorageAllocations, compiler?: Compiler.CompilerVersion ): Storage.StorageLength { return storageSizeAndAllocate( dataType, userDefinedTypes, allocations, compiler ).size; } function storageSizeAndAllocate( dataType: Format.Types.Type, userDefinedTypes?: Format.Types.TypesById, existingAllocations?: StorageAllocations, compiler?: Compiler.CompilerVersion ): StorageAllocationInfo { //we'll only directly handle reference types here; //direct types will be handled by dispatching to Basic.Allocate.byteLength //in the default case switch (dataType.typeClass) { case "bytes": { switch (dataType.kind) { case "static": //really a basic type :) return { size: { bytes: Basic.Allocate.byteLength(dataType, userDefinedTypes) }, //doing the function call for consistency :P allocations: existingAllocations }; case "dynamic": return { size: { words: 1 }, allocations: existingAllocations }; } } case "string": case "mapping": return { size: { words: 1 }, allocations: existingAllocations }; case "array": { switch (dataType.kind) { case "dynamic": return { size: { words: 1 }, allocations: existingAllocations }; case "static": //static array case const length = dataType.length.toNumber(); //warning! but if it's too big we have a problem if (length === 0) { //in versions of Solidity where it's legal, arrays of length 0 still take up 1 word return { size: { words: 1 }, allocations: existingAllocations }; } let { size: baseSize, allocations } = storageSizeAndAllocate( dataType.baseType, userDefinedTypes, existingAllocations ); if (!Utils.isWordsLength(baseSize)) { //bytes case const perWord = Math.floor(Evm.Utils.WORD_SIZE / baseSize.bytes); debug("length %o", length); const numWords = Math.ceil(length / perWord); return { size: { words: numWords }, allocations }; } else { //words case return { size: { words: baseSize.words * length }, allocations }; } } } case "struct": { let allocations: StorageAllocations = existingAllocations; let allocation: StorageAllocation | undefined = allocations[dataType.id]; //may be undefined! if (allocation === undefined) { //if we don't find an allocation, we'll have to do the allocation ourselves const storedType = <Format.Types.StructType>( userDefinedTypes[dataType.id] ); if (!storedType) { throw new Common.UnknownUserDefinedTypeError( dataType.id, Format.Types.typeString(dataType) ); } allocations = allocateStruct( storedType, userDefinedTypes, existingAllocations ); allocation = allocations[dataType.id]; } //having found our allocation, we can just look up its size return { size: allocation.size, allocations }; } case "userDefinedValueType": if (Compiler.Utils.solidityFamily(compiler) === "0.8.7+") { //UDVTs were introduced in Solidity 0.8.8. However, in that version, //and that version only, they have a bug where they always take up a //full word in storage regardless of the size of the underlying type. return { size: { words: 1 }, allocations: existingAllocations }; } //otherwise, treat them normally //DELIBERATE FALL-TRHOUGH default: //otherwise, it's a direct type return { size: { bytes: Basic.Allocate.byteLength(dataType, userDefinedTypes) }, allocations: existingAllocations }; } }
the_stack
import type { Chunk, Chunker } from './chunker'; import { chunkEquals } from './chunker'; const E_END = 'Iterator exhausted before seek ended.'; /** * Abstraction to seek (jump) or read to a position inside a ‘file’ consisting of a * sequence of data chunks. * * This interface is a combination of three interfaces in one: for seeking to a * relative position, an absolute position, or a specific chunk. These three are * defined separately for clarity and flexibility, but normally used together. * * A Seeker internally maintains a pointer to the chunk it is currently ‘in’ and * the offset position within that chunk. * * @typeParam TChunk - Type of chunks the file consists of. * @typeParam TData - Type of data this seeker’s read methods will return (not * necessarily the same as the `TData` parameter of {@link Chunk}, see e.g. * {@link CodePointSeeker}) * * @public */ export interface Seeker< TChunk extends Chunk<any>, TData extends Iterable<any> = string > extends RelativeSeeker<TData>, AbsoluteSeeker<TData>, ChunkSeeker<TChunk, TData> {} /** * Seeks/reads by a given number of characters. * * @public */ export interface RelativeSeeker<TData extends Iterable<any> = string> { /** * Move forward or backward by a number of characters. * * @param length - The number of characters to pass. A negative number moves * backwards in the file. * @throws RangeError if there are not enough characters in the file. The * pointer is left at the end/start of the file. */ seekBy(length: number): void; /** * Read forward or backward by a number of characters. * * Equal to {@link seekBy}, but returning the characters passed. * * @param length - The number of characters to read. A negative number moves * backwards in the file. * @param roundUp - If true, then, after reading the given number of * characters, read further until the end (or start) of the current chunk. * @param lessIsFine - If true, and there are not enough characters in the * file, return the result so far instead of throwing an error. * @returns The characters passed (in their normal order, even when moving * backwards) * @throws RangeError if there are not enough characters in the file (unless * `lessIsFine` is true). The pointer is left at the end/start of the file. */ read(length?: number, roundUp?: boolean, lessIsFine?: boolean): TData; } /** * Seek/read to absolute positions in the file. * * @public */ export interface AbsoluteSeeker<TData extends Iterable<any> = string> { /** * The current position in the file in terms of character count: i.e. the * number of characters before the place currently being pointed at. */ readonly position: number; /** * Move to the given position in the file. * * @param target - The position to end up at. * @throws RangeError if the given position is beyond the end/start of the * file. The pointer is left at the end/start of the file. */ seekTo(target: number): void; /** * Read forward or backward from the current to the given position in the * file, returning the characters that have been passed. * * Equal to {@link seekTo}, but returning the characters passed. * * @param target - The position to end up at. * @param roundUp - If true, then, after reading to the target position, read * further until the end (or start) of the current chunk. * @returns The characters passed (in their normal order, even when moving * backwards) * @throws RangeError if the given position is beyond the end/start of the * file. The pointer is left at the end/start of the file. */ readTo(target: number, roundUp?: boolean): TData; } /** * Seek/read to (and within) specfic chunks the file consists of; and access the * chunk and offset in that chunk corresponding to the current position. * * Note that all offset numbers in this interface are representing units of the * {@link Chunk.data | data type of `TChunk`}; which might differ from that of * `TData`. * * @public */ export interface ChunkSeeker< TChunk extends Chunk<any>, TData extends Iterable<any> = string > { /** * The chunk containing the current position. * * When the position falls at the edge between two chunks, `currentChunk` is * always the later one (thus {@link offsetInChunk} would be zero). Note that * an empty chunk (for which position zero is at both its edges) can * hence never be the current chunk unless it is the last chunk in the file. */ readonly currentChunk: TChunk; /** * The offset inside `currentChunk` corresponding to the current position. * Can be between zero and the length of the chunk (inclusive; but it could * equal the length of the chunk only if currentChunk is the last chunk). */ readonly offsetInChunk: number; /** * Move to the start of a given chunk, or to an offset relative to that. * * @param chunk - The chunk of the file to move to. * @param offset - The offset to move to, relative to the start of `chunk`. * Defaults to zero. * @throws RangeError if the given chunk is not found in the file. */ seekToChunk(chunk: TChunk, offset?: number): void; /** * Read to the start of a given chunk, or to an offset relative to that. * * Equal to {@link seekToChunk}, but returning the characters passed. * * @param chunk - The chunk of the file to move to. * @param offset - The offset to move to, relative to the start of `chunk`. * Defaults to zero. * @returns The characters passed (in their normal order, even when moving * backwards) * @throws RangeError if the given chunk is not found in the file. */ readToChunk(chunk: TChunk, offset?: number): TData; } /** * A TextSeeker is constructed around a {@link Chunker}, to let it be treated as * a continuous sequence of characters. * * Seeking to a given numeric position will cause a `TextSeeker` to pull chunks * from the underlying `Chunker`, counting their lengths until the requested * position is reached. `Chunks` are not stored but simply read again when * seeking backwards. * * The `Chunker` is presumed to read an unchanging file. If a chunk’s length * would change while seeking, a TextSeeker’s absolute positioning would be * incorrect. * * See {@link CodePointSeeker} for a {@link Seeker} that counts Unicode *code * points* instead of Javascript’s ‘normal’ characters. * * @public */ export class TextSeeker<TChunk extends Chunk<string>> implements Seeker<TChunk> { // The chunk containing our current text position. get currentChunk(): TChunk { return this.chunker.currentChunk; } // The index of the first character of the current chunk inside the text. private currentChunkPosition = 0; // The position inside the chunk where the last seek ended up. offsetInChunk = 0; // The current text position (measured in code units) get position(): number { return this.currentChunkPosition + this.offsetInChunk; } constructor(protected chunker: Chunker<TChunk>) { // Walk to the start of the first non-empty chunk inside the scope. this.seekTo(0); } read(length: number, roundUp = false, lessIsFine = false): string { return this._readOrSeekTo( true, this.position + length, roundUp, lessIsFine, ); } readTo(target: number, roundUp = false): string { return this._readOrSeekTo(true, target, roundUp); } seekBy(length: number): void { this.seekTo(this.position + length); } seekTo(target: number): void { this._readOrSeekTo(false, target); } seekToChunk(target: TChunk, offset = 0): void { this._readOrSeekToChunk(false, target, offset); } readToChunk(target: TChunk, offset = 0): string { return this._readOrSeekToChunk(true, target, offset); } private _readOrSeekToChunk( read: true, target: TChunk, offset?: number, ): string; private _readOrSeekToChunk( read: false, target: TChunk, offset?: number, ): void; private _readOrSeekToChunk( read: boolean, target: TChunk, offset = 0, ): string | void { const oldPosition = this.position; let result = ''; // Walk to the requested chunk. if (!this.chunker.precedesCurrentChunk(target)) { // Search forwards. while (!chunkEquals(this.currentChunk, target)) { const [data, nextChunk] = this._readToNextChunk(); if (read) result += data; if (nextChunk === null) throw new RangeError(E_END); } } else { // Search backwards. while (!chunkEquals(this.currentChunk, target)) { const [data, previousChunk] = this._readToPreviousChunk(); if (read) result = data + result; if (previousChunk === null) throw new RangeError(E_END); } } // Now we know where the chunk is, walk to the requested offset. // Note we might have started inside the chunk, and the offset could even // point at a position before or after the chunk. const targetPosition = this.currentChunkPosition + offset; if (!read) { this.seekTo(targetPosition); } else { if (targetPosition >= this.position) { // Read further until the target. result += this.readTo(targetPosition); } else if (targetPosition >= oldPosition) { // We passed by our target position: step back. this.seekTo(targetPosition); result = result.slice(0, targetPosition - oldPosition); } else { // The target precedes our starting position: read backwards from there. this.seekTo(oldPosition); result = this.readTo(targetPosition); } return result; } } private _readOrSeekTo( read: true, target: number, roundUp?: boolean, lessIsFine?: boolean, ): string; private _readOrSeekTo( read: false, target: number, roundUp?: boolean, lessIsFine?: boolean, ): void; private _readOrSeekTo( read: boolean, target: number, roundUp = false, lessIsFine = false, ): string | void { let result = ''; if (this.position <= target) { while (true) { const endOfChunk = this.currentChunkPosition + this.currentChunk.data.length; if (endOfChunk <= target) { // The target is beyond the current chunk. // (we use ≤ not <: if the target is *at* the end of the chunk, possibly // because the current chunk is empty, we prefer to take the next chunk) const [data, nextChunk] = this._readToNextChunk(); if (read) result += data; if (nextChunk === null) { if (this.position === target || lessIsFine) break; else throw new RangeError(E_END); } } else { // The target is within the current chunk. const newOffset = roundUp ? this.currentChunk.data.length : target - this.currentChunkPosition; if (read) result += this.currentChunk.data.substring( this.offsetInChunk, newOffset, ); this.offsetInChunk = newOffset; // If we finish end at the end of the chunk, seek to the start of the next non-empty node. // (TODO decide: should we keep this guarantee of not finishing at the end of a chunk?) if (roundUp) this.seekBy(0); break; } } } else { // Similar to the if-block, but moving backward in the text. while (this.position > target) { if (this.currentChunkPosition <= target) { // The target is within the current chunk. const newOffset = roundUp ? 0 : target - this.currentChunkPosition; if (read) result = this.currentChunk.data.substring(newOffset, this.offsetInChunk) + result; this.offsetInChunk = newOffset; break; } else { const [data, previousChunk] = this._readToPreviousChunk(); if (read) result = data + result; if (previousChunk === null) { if (lessIsFine) break; else throw new RangeError(E_END); } } } } if (read) return result; } // Read to the start of the next chunk, if any; otherwise to the end of the current chunk. _readToNextChunk(): [string, TChunk | null] { const data = this.currentChunk.data.substring(this.offsetInChunk); const chunkLength = this.currentChunk.data.length; const nextChunk = this.chunker.nextChunk(); if (nextChunk !== null) { this.currentChunkPosition += chunkLength; this.offsetInChunk = 0; } else { this.offsetInChunk = chunkLength; } return [data, nextChunk]; } // Read backwards to the end of the previous chunk, if any; otherwise to the start of the current chunk. _readToPreviousChunk(): [string, TChunk | null] { const data = this.currentChunk.data.substring(0, this.offsetInChunk); const previousChunk = this.chunker.previousChunk(); if (previousChunk !== null) { this.currentChunkPosition -= this.currentChunk.data.length; this.offsetInChunk = this.currentChunk.data.length; } else { this.offsetInChunk = 0; } return [data, previousChunk]; } }
the_stack
* Created by juheeko on 2017. 11. 14.. */ import {AfterViewInit, Component, ElementRef, Injector, Input, OnDestroy, OnInit} from '@angular/core'; import {BaseChart, PivotTableInfo} from '../base-chart'; import { CHART_STRING_DELIMITER, ChartColorList, ChartColorType, ChartType, ColorCustomMode, ColorRangeType, Position, SeriesType, ShelveFieldType, ShelveType, SymbolType, UIChartDataLabelDisplayType } from '../option/define/common'; import {OptionGenerator} from '../option/util/option-generator'; import {Series} from '../option/define/series'; import * as _ from 'lodash'; import {Pivot} from '@domain/workbook/configurations/pivot'; import {Alert} from '@common/util/alert.util'; import {BaseOption} from '../option/base-option'; import {UIChartColorByDimension, UIChartColorByValue, UIChartFormat, UIOption} from '../option/ui-option'; import {FormatOptionConverter} from '../option/converter/format-option-converter'; import {ColorRange, UIChartColor} from '../option/ui-option/ui-color'; import {UIScatterChart} from '../option/ui-option/ui-scatter-chart'; import {DIRECTION, Sort} from '@domain/workbook/configurations/sort'; import optGen = OptionGenerator; import UI = OptionGenerator.UI; @Component({ selector: 'gauge-chart', template: '<div class="chartCanvas" style="width: 100%; height: 100%; display: block;"></div>' }) export class GaugeChartComponent extends BaseChart<UIOption> implements OnInit, AfterViewInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Input('sorts') private sorts: Sort[]; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor( protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { super.ngOnInit(); } // Destroy public ngOnDestroy() { super.ngOnDestroy(); } // After View Init public ngAfterViewInit(): void { super.ngAfterViewInit(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 선반정보를 기반으로 차트를 그릴수 있는지 여부를 체크 * * @param shelve */ public isValid(shelve: Pivot): boolean { return ((this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.DIMENSION) + this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.TIMESTAMP)) > 0) && ((this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.MEASURE) + this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.CALCULATED)) === 1) && (this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.MEASURE) === 0 && this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.CALCULATED) === 0) && (this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.DIMENSION) === 0 && this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.TIMESTAMP) === 0) } /** * gauge차트에서만 쓰이는 uiOption설정 * @param isKeepRange */ public draw(isKeepRange?: boolean): void { // 음수값 있는지 체크 // minValue값이 음수인경우 선반에서 measure값을 제거하고 this.removeNegative(); // uiOption 설정 // stacked의 최대값 최소값 설정 this.uiOption.stackedMaxvalue = 100; this.uiOption.stackedMinValue = 0; // 게이지 data 설정 this.data = this.setGaugeChartData(isKeepRange); // 게이지 data 설정이후에 uiData값 설정 this.data.columns = this.setUIData(); // pivot cols, rows 초기화 const rows: string[] = []; _.each(this.data.columns, (series) => { _.each(series, (column) => { // 최대값 최소값 설정 this.data.info.maxValue = column.value > this.data.info.maxValue ? column.value : this.data.info.maxValue; this.data.info.minValue = this.data.info.minValue > column.value ? column.value : this.data.info.minValue; const columnName: string = _.split(column.name, CHART_STRING_DELIMITER)[1]; // pivotInfo데이터의 rows 데이터 설정 (범례, 색상에서 사용) rows.push(columnName); }) }); // setDataInfo를 게이지 데이터 정제후 재실행 this.setDataInfo(); // dimension의 data리스트 this.uiOption.fieldDimensionDataList = rows; // pivotInfo 설정 this.pivotInfo = new PivotTableInfo([], rows, this.fieldInfo.aggs); // gauge차트의 mapping값 설정 // this.uiOption.color = this.gaugeSetMapping(rows); super.draw(isKeepRange); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * color by measure의 range값 리턴 * @returns {any} */ protected setMeasureColorRange(schema): ColorRange[] { // return value const rangeList = []; // set color list matching this schema const colorList = ChartColorList[schema]; // bring the data that have the longest length const rowsList = _.max(this.data.columns) as any; const rowsListLength = rowsList.length; // if rows length is less than colorList length, set rows length instead 5(default) const colorListLength = colorList.length > rowsListLength ? rowsListLength - 1 : colorList.length - 1; // less than 0, set minValue const minValue = this.uiOption.minValue >= 0 ? 0 : _.cloneDeep(this.uiOption.minValue); const addValue = (this.uiOption.maxValue - minValue) / colorListLength; let maxValue = _.cloneDeep(this.uiOption.maxValue); let shape; if ((this.uiOption as UIScatterChart).pointShape) { shape = (this.uiOption as UIScatterChart).pointShape.toString().toLowerCase(); } // set ranges for (let index = colorListLength; index >= 0; index--) { const color = colorList[index]; // set the biggest value in min(gt) if (colorListLength === index) { rangeList.push(UI.Range.colorRange(ColorRangeType.SECTION, color, parseFloat(maxValue.toFixed(1)), null, parseFloat(maxValue.toFixed(1)), null, shape)); } else { // if it's the last value, set null in min(gt) let min = 0 === index ? null : parseFloat((maxValue - addValue).toFixed(1)); // if value if lower than minValue, set it as minValue if (min < this.uiOption.minValue && min < 0) min = _.cloneDeep(parseInt(this.uiOption.minValue.toFixed(1), 10)); rangeList.push(UI.Range.colorRange(ColorRangeType.SECTION, color, min, parseFloat(maxValue.toFixed(1)), min, parseFloat(maxValue.toFixed(1)), shape)); maxValue = min; } } return rangeList; } /** * 차트별 시리즈 추가정보 * - 반드시 각 차트에서 Override * @returns {BaseOption} */ protected convertSeriesData(): BaseOption { const objData = this.data; // pivot cols, rows 초기화 const rows: string[] = []; let columnLength = _.max(objData.columns)['length']; // series 초기화 this.chartOption.series = []; // series 배열값 _.each(objData.columns, (series) => { // 시리즈 설정 const seriesData = series.map((column) => { const seriesName: string = column.name; // 각각의 데이터 이름 const columnName: string = _.split(seriesName, CHART_STRING_DELIMITER)[1]; // pivotInfo데이터의 rows 데이터 설정 (범례, 색상에서 사용) rows.push(columnName); // 시리즈 생성 let resultSeries: Series; resultSeries = { type: SeriesType.BAR, name: ChartType.GAUGE.toString(), data: [{ value: column.percentage, name: column.name, selected: false, itemStyle: optGen.ItemStyle.opacity1() }], uiData: column, originData: [], itemStyle: optGen.ItemStyle.auto(), label: optGen.LabelStyle.defaultLabelStyle(true, Position.INSIDE) }; return resultSeries; }); // series가 1개인경우 데이터의 100까지 기준보다 높게 기준점이 나오므로 시리즈 한개더 추가 if (1 === columnLength) columnLength = 2; // series data 개수를 맞춰주어야 하므로 가장 긴 column 값에 length를 맞추기 for (let index = 0; index < columnLength; index++) { // 해당 값이 없는경우 let item = seriesData[index]; // 값 init if (!item) { item = { type: SeriesType.BAR, name: ChartType.GAUGE.toString(), // uiData: {}, data: [{ value: 0, name: '', label: { normal: { formatter: '' } } }], originData: [], itemStyle: optGen.ItemStyle.auto(), label: optGen.LabelStyle.defaultLabelStyle(true, Position.INSIDE) }; } // 기존에 series값이 있는경우 if (this.chartOption.series[index]) { const singleSeries = this.chartOption.series[index]; // 데이터 설정 this.chartOption.series[index].data = singleSeries.data.concat(item.data); // origin 데이터 설정 this.chartOption.series[index].originData = _.cloneDeep(singleSeries.data); // 명칭 설정 this.chartOption.series[index].name = singleSeries.name + CHART_STRING_DELIMITER + item.name; // 기존 series값이 없는경우 } else { // series column의 데이터 위치에 맞게 data length 설정 if (index > 0 && this.chartOption.series[0].data.length > item.data.length) { const lengthDiff = this.chartOption.series[0].data.length - item.data.length; for (let num = 0; num < lengthDiff; num++) { item.data.splice(0, 0, ({value: 0})); } } // originData에 설정 item.originData = _.cloneDeep(item.data); this.chartOption.series.push(item); } this.chartOption.series[index].data.forEach((dataItem, dataIndex) => { // uiData가 없는경우 if (!dataItem['uiData']) { dataItem['uiData'] = _.find(objData.columns[dataIndex], {name: dataItem.name}); } }); } }); return this.chartOption; } /** * 시리즈 정보를 변환한다. * - 필요시 각 차트에서 Override * @returns {BaseOption} */ protected convertSeries(): BaseOption { // Base Call this.chartOption = super.convertSeries(); // Gradient Color Change if (_.eq(this.uiOption.color.type, ChartColorType.MEASURE) && this.uiOption.color['customMode'] && ColorCustomMode.GRADIENT === this.uiOption.color['customMode']) { _.each(this.data.columns, (column, columnIndex) => { // Series Total Value const totalValue: number = column.categoryValue; _.each(this.chartOption.series, (series) => { const data = series.data[columnIndex]; // Validate if (!this.uiOption.color['ranges']) { return false; } // Base Data let value: number = null; if (data && isNaN(data)) { value = data.value; } else { value = data; } const maxValue: number = this.data.info.maxValue; const rangePercent: number = (maxValue / totalValue) * 100; const codes: string[] = _.cloneDeep(this.chartOption.visualMap.color).reverse(); let index: number = Math.round(value / rangePercent * codes.length); index = index === codes.length ? codes.length - 1 : index; series.data[columnIndex].itemStyle = { normal: { color: codes[index] } }; }); }); delete this.chartOption.visualMap; } // Default Color Change else if (_.eq(this.uiOption.color.type, ChartColorType.MEASURE)) { _.each(this.data.columns, (column, columnIndex) => { // Series Total Value const totalValue: number = column.categoryValue; _.each(this.chartOption.series, (series) => { const data = series.data[columnIndex]; // Validate if (!this.uiOption.color['ranges']) { return false; } // Base Data let value: number = null; if (data && isNaN(data)) { value = data.value; } else { value = data; } const originalValue: number = totalValue * (value / 100); const ranges = _.cloneDeep((this.uiOption.color as UIChartColorByValue).ranges); let index: number = 0; _.each(this.uiOption.color['ranges'], (range, rangeIndex) => { const min: number = range.fixMin != null ? range.fixMin : 0; const max: number = range.fixMax != null ? range.fixMax : min; if (originalValue >= min && originalValue <= max) { index = Number(rangeIndex); return false; } }); series.data[columnIndex].itemStyle = { normal: { color: ranges[index].color } }; }); }); delete this.chartOption.visualMap; } return this.chartOption; } /** * 셀렉션 이벤트를 등록한다. * - 필요시 각 차트에서 Override */ protected selection(): void { this.addChartSelectEventListener(); } /** * 게이지차트의 series값으로 설정되는 부분 */ protected additionalSeries(): BaseOption { // 라벨 방향 설정 this.chartOption = this.convertLabelRotate(); this.chartOption = this.convertGaugeFormatSeries(this.chartOption, this.uiOption); return this.chartOption; } /** * 게이지차트의 legend 설정 */ protected additionalLegend(): BaseOption { // dimension일때 게이지차트 색상 설정 const series = this.chartOption.series; const legendData = this.chartOption.legend.data; const schema = this.uiOption.color['schema']; const list = _.cloneDeep(ChartColorList[schema]) as any; // userCodes가 있는경우 codes대신 userCodes를 설정한다 if ((this.uiOption.color as UIChartColorByDimension).mapping) { Object.keys((this.uiOption.color as UIChartColorByDimension).mapping).forEach((key, index) => { const mappingValue = (this.uiOption.color as UIChartColorByDimension).mapping[key]; if (mappingValue) list[index] = (this.uiOption.color as UIChartColorByDimension).mapping[key]; }); } if (ChartColorType.DIMENSION === this.uiOption.color.type) { _.each(series, (obj) => { obj.itemStyle.normal.color = ((params: any) => { let name: string; // 이름을 data의 name으로 변경 name = _.split(params.data.name, CHART_STRING_DELIMITER)[1]; let colorIdx = _.indexOf(legendData, name); colorIdx = colorIdx >= list.length ? colorIdx % list.length : colorIdx; return list[colorIdx]; }) }); } return this.chartOption; } /** * 게이지차트의 tooltip 설정 * @returns {BaseOption} */ protected additionalTooltip(): BaseOption { /////////////////////////// // UI 옵션에서 값 추출 /////////////////////////// let format: UIChartFormat = this.uiOption.valueFormat; // 축의 포멧이 있는경우 축의 포멧으로 설정 const axisFormat = FormatOptionConverter.getlabelAxisScaleFormatTooltip(this.uiOption); if (axisFormat) format = axisFormat; if (_.isUndefined(this.chartOption.tooltip)) { this.chartOption.tooltip = {}; } this.chartOption.tooltip.formatter = ((params): any => { const option = this.chartOption.series[params.seriesIndex]; let uiData = _.cloneDeep(option.data[params.dataIndex]['uiData']); if (!uiData) uiData = _.cloneDeep(option['uiData']); return this.getFormatGaugeValueSeriesTooltip(params, format, this.uiOption, option, uiData); }); return this.chartOption; } /** * 차트의 기본 옵션을 생성한다. * - 각 차트에서 Override */ protected initOption(): BaseOption { return { type: ChartType.GAUGE, grid: [OptionGenerator.Grid.verticalMode(17, 10, 0, 10, false, false, false)], xAxis: [OptionGenerator.Axis.valueAxis(Position.MIDDLE, null, false, false, true, true, true)], yAxis: [OptionGenerator.Axis.categoryAxis(Position.MIDDLE, null, true, true, true, true)], legend: OptionGenerator.Legend.custom(false, false, Position.LEFT, SymbolType.CIRCLE, '100%', 20, 5), tooltip: OptionGenerator.Tooltip.itemTooltip(), toolbox: OptionGenerator.Toolbox.hiddenToolbox(), brush: OptionGenerator.Brush.selectBrush(), series: [] }; } /** * uiData에 설정될 columns데이터 설정 */ protected setUIData(): any { // rows 축의 개수만큼 넣어줌 // _.each(this.data.columns, (data) => { // // data.categoryValue = 0; // data.categoryPercent = 0; // // // category의 합을 설정 // for (const item of data) { // data.categoryPercent += item.percentage; // data.categoryValue += item.value; // } // // data.categoryPercent = _.cloneDeep(Math.round(data.categoryPercent)); // data.categoryValue = _.cloneDeep(Math.round(data.categoryValue)); // // // 해당 property에 값 설정 // for (const item of data) { // item['categoryPercent'] = _.cloneDeep(Math.round(data.categoryPercent)); // item['categoryValue'] = _.cloneDeep(Math.round(data.categoryValue)); // } // }); return this.data.columns; } /** * setMapping값에서 설정 x, gaugeSetMapping에서 따로설정 * @returns {UIChartColor} */ protected setMapping(): UIChartColor { return this.uiOption.color; } /** * dataLabel, tooltip 중첩에 따라서 설정 * @returns {UIOption} */ protected setDataLabel(): UIOption { if (!this.pivot || !this.pivot.rows) return this.uiOption; const spliceCategoryTypeList = ((categoryTypeList, dataLabel: any): any => { // 미리보기 리스트가 빈값인지 체크 const previewFl = !!dataLabel.previewList; let index: number; for (const item of categoryTypeList) { index = dataLabel.displayTypes.indexOf(item); if (-1 !== index) { // 라벨에서 제거 dataLabel.displayTypes[index] = null; // previewList가 있는경우 if (previewFl) { // 미리보기리스트에서 제거 _.remove(dataLabel.previewList, {value: item}); } } } return dataLabel; }); // dimension이 1개일때에는 카테고리명 제거 if (this.pivot.rows.length < 2) { const categoryTypeList = [UIChartDataLabelDisplayType.CATEGORY_NAME]; // 데이터라벨에서 series관련 설정제거 if (this.uiOption.dataLabel && this.uiOption.dataLabel.displayTypes) this.uiOption.dataLabel = spliceCategoryTypeList(categoryTypeList, this.uiOption.dataLabel); // 툴팁의 series관련 설정제거 if (this.uiOption.toolTip && this.uiOption.toolTip.displayTypes) this.uiOption.toolTip = spliceCategoryTypeList(categoryTypeList, this.uiOption.toolTip); } return this.uiOption; } /** * 게이지차트의 그리드 정보를 변환 * @returns {BaseOption} */ protected additionalGrid(): BaseOption { // dataZoom이 없는축의 레이블표시가 off일때 잘리는 echart 에러 => grid값 늘려주기 this.chartOption.grid.map((obj) => { // x축 레이블 표시가 false이면서 축제목이 true인 경우 if (false === this.uiOption.xAxis.showLabel && true === this.uiOption.xAxis.showName) { obj.bottom = (obj.bottom as number) + 20; } }); return this.chartOption; } /** * 게이지차트의 x축 max값 설정 * @returns {BaseOption} */ protected additionalXAxis(): BaseOption { // x축값의 max를 100으로 설정하여 축이 100이상 나오지 않게 설정 this.chartOption.xAxis.map((obj) => { obj.max = 100; }); return this.chartOption; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // /** // * gauge차트의 color의 mapping, mappingArray값 설정 // */ // private gaugeSetMapping(gaugeDimensionList: string[]): UIChartColor { // // if (!this.uiOption.color) return; // // if (!(this.uiOption.color as UIChartColorByDimension).mapping) (this.uiOption.color as UIChartColorByDimension).mapping = {}; // // // color mapping값이 있는경우 // if ((this.uiOption.color as UIChartColorByDimension).schema) { // // // mapping값이 제거된경우 이후 색상값을 초기화 // let colorChangedFl: boolean = false; // // // fieldMeasureList에서 제거된 값 제거 // for (const key in (this.uiOption.color as UIChartColorByDimension).mapping) { // if( key ) { // // const index = _.findIndex(gaugeDimensionList, key); // const index = _.findIndex(gaugeDimensionList, (data) => { // return data === key; // }); // // // fieldMeasureList에서 없는 리스트이거나 이전의 값이 제거된경우 색상 초기화를 위해 제거 // if (-1 === index || colorChangedFl) { // delete (this.uiOption.color as UIChartColorByDimension).mapping[key]; // colorChangedFl = true; // } // } // } // // gaugeDimensionList.forEach((item, index) => { // // 해당 alias값이 없을때에만 기본색상설정 // if ((this.uiOption.color as UIChartColorByDimension).schema && !(this.uiOption.color as UIChartColorByDimension).mapping[item]) { // // const colorListLength = ChartColorList[(this.uiOption.color as UIChartColorBySeries).schema].length; // // 색상리스트보다 gaugeDimensionList가 큰경우 색상 반복되게 설정 // const editIndex = index >= colorListLength ? index % colorListLength : index; // (this.uiOption.color as UIChartColorByDimension).mapping[item] = ChartColorList[(this.uiOption.color as UIChartColorByDimension).schema][editIndex]; // } // }); // // // mapping map array로 변경 // (this.uiOption.color as UIChartColorByDimension).mappingArray = []; // // Object.keys((this.uiOption.color as UIChartColorByDimension).mapping).forEach((key) => { // // (this.uiOption.color as UIChartColorByDimension).mappingArray.push({ // alias: key, // color: (this.uiOption.color as UIChartColorByDimension).mapping[key] // }); // }); // } // // return this.uiOption.color; // } /** * 게이지차트 series의 data label rotate 변경시 * @returns {BaseOption} */ private convertLabelRotate(): BaseOption { // 가로 / 세로에 따라서 rotate값 설정 let rotate: number; if (!this.uiOption.dataLabel.enableRotation) { rotate = 0; } else if (this.uiOption.dataLabel.enableRotation) { rotate = 90; } const series = this.chartOption.series; // series의 label normal 값에 rotate 설정 series.map((item) => { if (item.label && item.label.normal) item.label.normal.rotate = rotate; }); return this.chartOption; } /** * 게이지 차트 데이터 형식으로 변경 * @param {boolean} isKeepRange true일때 uiOption으로 인해서 변경된경우 데이터 설정을 바꾸지 않음 * @returns {any} */ private setGaugeChartData(isKeepRange?: boolean): any { // isKeepRange가 true인경우 (uiOption으로 인해서 변경된경우 데이터 설정을 바꾸지 않음 if (isKeepRange) return this.data; const shelve = this.pivot; const data = this.data; // 해당 dimension의 리스트 가져오기 const rowsList = shelve.rows.map((item) => { return item.alias }); let value = []; let percentage = []; // 행선반에 올린 dimension개수만큼 데이터 설정 const columnList = rowsList.map((rowData, rowIdx) => { // 행의 dimension 값가져오기 const rowDuplicateList = data.rows.map((rowValue) => { return _.split(rowValue, CHART_STRING_DELIMITER)[rowIdx]; }); // 중복된값을 제거한 리스트 가져오기 const uniqRows = _.uniq(rowDuplicateList); // dimension의 key, value값 가져오기 let column = uniqRows.map((uniqRow) => { value = []; percentage = []; rowDuplicateList.forEach((item, index) => { // value값 리스트 설정 value.push(uniqRow === item ? data.columns[0].value[index] : 0); // percent값 리스트 설정 percentage.push(uniqRow === item ? data.columns[0].percentage[index] : 0); }); let sumData = value.reduce((sum, current) => { return sum + current }); const sumPercent = percentage.reduce((sum, current) => { return sum + current }); sumData = Math.floor(sumData * 1000000) / 1000000; // column data 값 설정 return { name: rowData + CHART_STRING_DELIMITER + uniqRow + CHART_STRING_DELIMITER + data.columns[0].name, value: sumData, percentage: sumPercent }; }); // set sort by first sort if (this.sorts && this.sorts.length > 0) { let sortFl: boolean = false; for (const sort of this.sorts) { _.sortBy(column, (item) => { // sort by dimension if (item.name.split(CHART_STRING_DELIMITER)[0] === sort.field) { column = _.sortBy(column, 'name'); sortFl = true; // sort by measure } else if (item.name.split(CHART_STRING_DELIMITER)[2] === sort.field) { column = _.sortBy(column, 'value'); sortFl = true; } }); // when array is sorted, skip next sorts if (sortFl) { // asc, desc if (DIRECTION.DESC === sort.direction) column = column.sort().reverse(); break; } } } return column; }); // data에 해당 리스트 설정 data.rows = rowsList; data.columns = columnList; return data; } /** * minValue값이 음수인경우 선반에서 measure값을 제거 */ private removeNegative(): void { if (this.data.info.minValue < 0) { // 선반에서 aggregation 측정값 제거 this.changePivotData.emit({ shelveTypeList: [ShelveType.AGGREGATIONS], shelveFieldTypeList: [String(ShelveFieldType.MEASURE), String(ShelveFieldType.CALCULATED)] }); // show guide 이벤트 발생 this.showGuide.emit(); // Alert Alert.info(this.translateService.instant('msg.page.gauge.chart.negative.value')); return; } } /** * Tooltip: 포맷을 변경한다. * @param params * @param {UIOption} uiOption * @param {PivotTableInfo} fieldInfo * @param {Pivot} _pivot * @returns {string} */ private getFormatValueTooltip(params: any, uiOption: UIOption, fieldInfo: PivotTableInfo, _pivot: Pivot): string { // Variable const format: UIChartFormat = uiOption.valueFormat; const colorType: ChartColorType = uiOption.color.type; const targetField: string = (uiOption.color as UIChartColorByDimension).targetField; // 기준선 일때 if (params.componentType === 'markLine') { return params.seriesName + '<br />' + params.data.value; } else if (params.componentType === 'series') { // 시리즈 일때 // 툴팁에 표시할 생상 정보 const colorEl = params.marker; // 툴팁에 표시할 범례명 let legendName = ''; // 데이터 천단위마다 콤마 표시 // 데이터가 배열 형식이라면 가장 마지막 요소의 값을 변환 if (_.isUndefined(params.value)) return ''; let value = _.isArray(params.value) ? _.last(params.value) : params.value; if (_.isNull(value)) return; ////////////////////////////////////////////////// // 공통포멧 ////////////////////////////////////////////////// if (format && format.isAll) { // 포맷 적용 value = FormatOptionConverter.getFormatValue(value, format); } ////////////////////////////////////////////////// // 포멧 정보가 없을경우 ////////////////////////////////////////////////// else { value = value.toLocaleString(); } // 해당하는 데이터의 시리즈명 let seriesName = ''; // 게이지 차트의경우 시리즈 각각데이터별로 명칭이 다르므로 data name값으로 설정 if (-1 < params.seriesName.indexOf(ChartType.GAUGE)) { seriesName = params.data.name; } // 첫번째 라인은 색상정보/범례명/수치 표현 // 두번째 라인은 차원값/측정값 의 조합 switch (colorType) { // color by dimension case ChartColorType.DIMENSION : // 어떤 선반에 몇번째 필드인지 확인 let fieldIdx = _.indexOf(fieldInfo.cols, targetField); const nameArr = fieldIdx < 0 ? _.split(params.seriesName, CHART_STRING_DELIMITER) : _.split(params.name, CHART_STRING_DELIMITER); if (fieldIdx < 0) fieldIdx = _.indexOf(fieldInfo.rows, targetField); // 해당하는 dimension 요소 이름 legendName = nameArr[fieldIdx]; break; // color by value case ChartColorType.MEASURE : // 범례상의 이름이 없기때문에 공백처리 legendName = ''; break; } // data의 data value, name이 있는경우 nameArr는 해당 데이터로 설정 if (params && params.data.name && params.data.value) legendName = _.last(_.split(params.data.name, CHART_STRING_DELIMITER)); // 범례값이 있는경우에만 : 값을 넣어주기 if (legendName && '' !== legendName) value = ' : ' + value; return colorEl + legendName + value + '<br />' + seriesName; } } /** * Series: 포맷에 해당하는 옵션을 모두 적용한다. * @param chartOption * @param uiOption * @returns {BaseOption} */ private convertGaugeFormatSeries(chartOption: BaseOption, uiOption: UIOption): BaseOption { /////////////////////////// // UI 옵션에서 값 추출 /////////////////////////// let format: UIChartFormat = uiOption.valueFormat; if (_.isUndefined(format)) { return chartOption } // 축의 포멧이 있는경우 축의 포멧으로 설정 const axisFormat = FormatOptionConverter.getlabelAxisScaleFormat(uiOption); if (axisFormat) format = axisFormat; /////////////////////////// // 차트 옵션에 적용 // - 시리즈 /////////////////////////// // 시리즈 const series: Series[] = chartOption.series; // 적용 _.each(series, (option) => { if (_.isUndefined(option.label)) { option.label = {normal: {}}; } if (_.isUndefined(option.label.normal)) { option.label.normal = {} } // 적용 option.label.normal.formatter = ((params): any => { let uiData = _.cloneDeep(option.data[params.dataIndex]['uiData']); if (!uiData) uiData = _.cloneDeep(option['uiData']); return this.getFormatGaugeValueSeries(params, format, uiOption, option, uiData); }); }); // 반환 return chartOption; } /** * 레이더의 포멧레이블 설정 * @param params * @param format * @param uiOption * @param series * @param uiData * @returns {any} */ private getFormatGaugeValueSeries(params: any, format: UIChartFormat, uiOption?: UIOption, series?: any, uiData?: any): string { // UI 데이터 정보가 있을경우 if (uiData) { if (!uiOption.dataLabel || !uiOption.dataLabel.displayTypes) return ''; // UI 데이터 가공 let isUiData: boolean = false; const result: string[] = []; if (this.pivot.rows.length > 1 && -1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_NAME)) { result.push(_.split(params.data.name, CHART_STRING_DELIMITER)[0]); isUiData = true; } if (-1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_VALUE)) { result.push(FormatOptionConverter.getFormatValue(uiData['categoryValue'], format)); isUiData = true; } if (-1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_PERCENT)) { let value = uiData['categoryPercent']; value = Math.floor(Number(value) * (Math.pow(10, format.decimal))) / Math.pow(10, format.decimal); result.push(value + '%'); isUiData = true; } // 해당 dataIndex 데이터애로 뿌려줌 if (-1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_NAME)) { result.push(_.split(params.data.name, CHART_STRING_DELIMITER)[1]); isUiData = true; } if (-1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_VALUE)) { result.push(FormatOptionConverter.getFormatValue(uiData.value, format)); isUiData = true; } if (-1 !== uiOption.dataLabel.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_PERCENT)) { const percentValue = Math.floor(Number(uiData.percentage) * (Math.pow(10, format.decimal))) / Math.pow(10, format.decimal); result.push(percentValue + '%'); isUiData = true; } let label: string = ''; // UI 데이터기반 레이블 반환 if (isUiData) { for (let num: number = 0; num < result.length; num++) { if (num > 0) { label += '\n'; } if (series.label && series.label.normal && series.label.normal.rich) { label += '{align|' + result[num] + '}'; } else { label += result[num]; } } return label; // 선택된 display label이 없는경우 빈값 리턴 } else { return label; } } return FormatOptionConverter.noUIDataFormat(params, format); } /** * 게이지차트의 포멧툴팁 설정 * @param params * @param format * @param uiOption * @param _series * @param uiData * @returns {any} */ private getFormatGaugeValueSeriesTooltip(params: any, format: UIChartFormat, uiOption?: UIOption, _series?: any, uiData?: any): string { // UI 데이터 정보가 있을경우 if (uiData) { if (!uiOption.toolTip) uiOption.toolTip = {}; if (!uiOption.toolTip.displayTypes) uiOption.toolTip.displayTypes = FormatOptionConverter.setDisplayTypes(uiOption.type); // UI 데이터 가공 const result: string[] = []; if (this.pivot.rows.length > 1 && -1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_NAME)) { const categoryNameList = _.split(params.data.name, CHART_STRING_DELIMITER); result.push(categoryNameList[0]); } if (-1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_VALUE)) { const splitValue = _.split(params.data.name, CHART_STRING_DELIMITER); const name = splitValue[splitValue.length - 1]; let categoryValue = FormatOptionConverter.getTooltipValue(name, this.pivot.aggregations, format, uiData['categoryValue']); // category percent가 있는경우 if (-1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_PERCENT)) { let value = uiData['categoryPercent']; value = Math.floor(Number(value) * (Math.pow(10, format.decimal))) / Math.pow(10, format.decimal); categoryValue += ' (' + value + '%)'; } result.push(categoryValue); } if (-1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_PERCENT)) { // category value가 선택된지 않은경우 if (-1 === uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_VALUE)) { const splitValue = _.split(params.data.name, CHART_STRING_DELIMITER); const name = splitValue[splitValue.length - 1]; let categoryValue = FormatOptionConverter.getTooltipValue(name, this.pivot.aggregations, format, uiData['categoryPercent']); categoryValue += '%'; result.push(categoryValue); } } // 해당 dataIndex 데이터애로 뿌려줌 if (-1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_NAME)) { const categoryNameList = _.split(params.data.name, CHART_STRING_DELIMITER); result.push(categoryNameList[0] + ' : ' + categoryNameList[1]); } if (-1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_VALUE)) { const splitValue = _.split(params.data.name, CHART_STRING_DELIMITER); const name = splitValue[splitValue.length - 1]; let seriesValue = FormatOptionConverter.getTooltipValue(name, this.pivot.aggregations, format, uiData['value']); // series percent가 있는경우 if (-1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_PERCENT)) { const value = Math.floor(Number(uiData['percentage']) * (Math.pow(10, format.decimal))) / Math.pow(10, format.decimal); seriesValue += ' (' + value + '%)'; } result.push(seriesValue); } if (-1 !== uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_PERCENT)) { // series value가 선택된지 않은경우 if (-1 === uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.SERIES_VALUE)) { const splitValue = _.split(params.data.name, CHART_STRING_DELIMITER); const name = splitValue[splitValue.length - 1]; let seriesValue = FormatOptionConverter.getTooltipValue(name, this.pivot.aggregations, format, uiData['value']); seriesValue += '%'; result.push(seriesValue); } } return result.join('<br/>'); } return this.getFormatValueTooltip(params, uiOption, this.fieldInfo, this.pivot); } }
the_stack
import React from 'react'; import { mount, shallow } from 'enzyme'; import assert from 'assert'; import sinon from 'sinon'; import { filterTypes, rejectTypes } from '../../util/component-types'; import _ from 'lodash'; import { common } from '../../util/generic-tests'; import { SearchableSelectDumb as SearchableSelect } from './SearchableSelect'; import { DropMenuDumb as DropMenu } from '../DropMenu/DropMenu'; const { Placeholder, Option, OptionGroup, SearchField } = SearchableSelect as any; describe('SearchableSelect', () => { common(SearchableSelect, { exemptFunctionProps: ['optionFilter', 'richChildRenderer'] as any, }); describe('render', () => { it('should render a DropMenu', () => { const wrapper = shallow( <SearchableSelect> <Placeholder>control</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); assert.equal(wrapper.find('DropMenu').length, 1); }); }); describe('props', () => { describe('children', () => { it('should not render any direct child elements which are not SearchableSelect-specific', () => { const wrapper = shallow( <SearchableSelect> <button>button</button> <Placeholder> control<i>italic</i> </Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> <h1>header</h1> </SearchableSelect> ); assert.equal(wrapper.find('button').length, 0); assert.equal(wrapper.find('h1').length, 0); assert.equal(wrapper.find('i').length, 1); }); }); describe('hasReset', () => { let wrapper: any; afterEach(() => { if (wrapper) { wrapper.unmount(); } }); it('should render the placeholder option as the first one in the menu and be a null option', () => { wrapper = mount( <SearchableSelect hasReset={true} selectedIndex={1} DropMenu={{ isExpanded: true }} > <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const menuDOMNode: any = document.querySelector( '.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); assert( _.includes( menuDOMNode.children[0].className, 'lucid-DropMenu-Option-is-null' ) ); }); it('should not render the placeholder null option as the first one in the menu', () => { wrapper = mount( <SearchableSelect hasReset={false} selectedIndex={1} DropMenu={{ isExpanded: true }} > <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const menuDOMNode: any = document.querySelector( '.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); assert( !_.includes( menuDOMNode.children[0].className, 'lucid-DropMenu-Option-is-null' ) ); }); }); describe('isDisabled', () => { it('should pass the `isDisabled` prop thru to the underlying DropMenu', () => { const wrapper = shallow( <SearchableSelect isDisabled={true}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const dropMenuWrapper = wrapper.find('DropMenu'); assert.equal(dropMenuWrapper.prop('isDisabled'), true); }); it('should apply the appropriate classNames to the control', () => { const wrapper = shallow( <SearchableSelect isDisabled={true} selectedIndex={2}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const controlWrapper = wrapper.find('.lucid-SearchableSelect-Control'); assert( controlWrapper.hasClass('lucid-SearchableSelect-Control-is-disabled') ); assert( !controlWrapper.hasClass('lucid-SearchableSelect-Control-is-selected') ); }); }); describe('isLoading', () => { it('should render a &-Loading Option and disable all Options', () => { const wrapper = shallow( <SearchableSelect isLoading> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const options = wrapper .find(DropMenu) .shallow() .find('.lucid-DropMenu-Option'); // first option should be the loading indicator. assert(options.at(0).hasClass('lucid-SearchableSelect-Loading')); assert(options.every('.lucid-DropMenu-Option-is-disabled')); }); }); describe('isSelectionHighlighted', () => { describe('default', () => { it('should apply the appropriate classNames to the control', () => { const wrapper = shallow( <SearchableSelect selectedIndex={2}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const controlWrapper = wrapper.find( '.lucid-SearchableSelect-Control' ); assert( controlWrapper.hasClass( 'lucid-SearchableSelect-Control-is-selected' ) ); assert( controlWrapper.hasClass( 'lucid-SearchableSelect-Control-is-highlighted' ) ); }); }); describe('false', () => { it('should apply the appropriate classNames to the control', () => { const wrapper = shallow( <SearchableSelect isSelectionHighlighted={false} selectedIndex={2}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const controlWrapper = wrapper.find( '.lucid-SearchableSelect-Control' ); assert( !controlWrapper.hasClass( 'lucid-SearchableSelect-Control-is-selected' ) ); assert( !controlWrapper.hasClass( 'lucid-SearchableSelect-Control-is-highlighted' ) ); }); }); }); describe('selectedIndex', () => { it('should pass the selectedIndex in an array of 1 to the underlying DropMenu', () => { const wrapper = shallow( <SearchableSelect selectedIndex={2}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const dropMenuWrapper = wrapper.find('DropMenu'); assert(_.isEqual(dropMenuWrapper.prop('selectedIndices'), [2])); }); it('should render selected option in the control', () => { const wrapper = shallow( <SearchableSelect selectedIndex={2}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const dropMenuControlWrapper = wrapper.find('DropMenu').childAt(0); assert.equal( 'option c', dropMenuControlWrapper .find('.lucid-SearchableSelect-Control-content') .text() ); }); }); describe('maxMenuHeight', () => { it('should pass through to DropMenu prop `optionContainerStyle.maxHeight`', () => { const wrapper = shallow( <SearchableSelect maxMenuHeight={123}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const dropMenuWrapper = wrapper.find(DropMenu); const optionContainerStyle: any = dropMenuWrapper.prop( 'optionContainerStyle' ); assert.equal( 123, optionContainerStyle.maxHeight, 'must match prop value' ); }); }); describe('onSelect', () => { /* eslint-disable no-console */ let error: any, wrapper: any; beforeEach(() => { error = console.error; console.error = jest.fn(); }); afterEach(() => { if (wrapper) { wrapper.unmount(); } console.error = error; }); it('should be called when an option is selected with the appropriate arguments', () => { const onSelect: any = sinon.spy(); wrapper = mount( <SearchableSelect onSelect={onSelect} DropMenu={{ isExpanded: true }}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option testProp='foo'>option c</Option> </SearchableSelect> ); const menuDOMNode: any = document.querySelector( '.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); menuDOMNode.children[2].click(); assert(onSelect.called); const [optionIndex, { props, event }] = onSelect.lastCall.args; assert.equal(optionIndex, 2); assert(props); assert.equal(props.testProp, 'foo'); assert(event); }); /* eslint-enable no-console */ }); describe('onSearch', () => { it('should be called when a new value is entered into the search input', () => { const onSearch = sinon.spy(); const wrapper = shallow( <SearchableSelect onSearch={onSearch} DropMenu={{ isExpanded: true }}> <Placeholder>select one</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option testProp='foo'>option c</Option> </SearchableSelect> ); const searchFieldWrapper = wrapper.find(SearchField); searchFieldWrapper.simulate('change', 'asdf', { event: {} }); assert(onSearch.calledWith('asdf')); }); }); describe('DropMenu', () => { it('should pass thru all DropMenu props to the underlying DropMenu', () => { const explicitDropMenuProps: any = { isExpanded: true, direction: 'up', focusedIndex: 2, }; const wrapper = shallow( <SearchableSelect DropMenu={explicitDropMenuProps}> <Placeholder>control</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const dropMenuProps: any = wrapper.find('DropMenu').props(); _.forEach(explicitDropMenuProps, (value, key) => { assert(_.isEqual(dropMenuProps[key], value)); }); }); }); describe('Error', () => { it('should pass the error class if the Error prop is passed', () => { const wrapper = shallow( <SearchableSelect Error={'Error message'}> <Placeholder>control</Placeholder> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </SearchableSelect> ); const searchWrapper = wrapper.find( '.lucid-SearchableSelect-Control-is-error' ); const errorWrapper = wrapper.find( '.lucid-SearchableSelect-error-content' ); expect(errorWrapper.exists()).toBeTruthy(); expect(searchWrapper.exists()).toBeTruthy(); expect(errorWrapper.text()).toEqual('Error message'); }); }); }); describe('child elements', () => { describe('SearchField', () => { it('should pass the searchfield props through to the underlying SearchField element', () => { const wrapper = shallow( <SearchableSelect DropMenu={{ isExpanded: true }}> <SearchField placeholder='custom' /> <Option name='OptionA'>option a</Option> <Option name='OptionB'>option b</Option> <Option name='OptionC'>option c</Option> </SearchableSelect> ); const dropMenuHeader = wrapper.childAt(0).childAt(1); const searchFieldWrapper = dropMenuHeader.childAt(0); assert.equal(searchFieldWrapper.prop('placeholder'), 'custom'); }); }); describe('Placeholder', () => { it('should pass the placeholder thru to the underlying DropMenu Control when no option is selected', () => { const wrapper = shallow( <SearchableSelect selectedIndex={null}> <Placeholder>select one</Placeholder> <Option name='OptionA'>option a</Option> <Option name='OptionB'>option b</Option> <Option name='OptionC'>option c</Option> </SearchableSelect> ); // navigate down the virutal DOM tree to find the Control content const dropMenuWrapper = wrapper.find('DropMenu'); const dropMenuChildren = dropMenuWrapper.prop('children'); const controlProps = _.first( _.map(filterTypes(dropMenuChildren, DropMenu.Control), 'props') ); const dropMenuControlChildElement: any = _.first( React.Children.toArray(controlProps.children) ); const SearchableSelectControlChildren = React.Children.toArray( dropMenuControlChildElement.props.children ); const SearchableSelectControlContent: any = SearchableSelectControlChildren[0]; assert.equal( React.Children.toArray( SearchableSelectControlContent.props.children )[0], 'select one' ); }); it('should pass the placeholder thru to the underlying DropMenu NullOption when an option is selected', () => { const wrapper = shallow( <SearchableSelect selectedIndex={1}> <Placeholder>select one</Placeholder> <Option name='OptionA'>option a</Option> <Option name='OptionB'>option b</Option> <Option name='OptionC'>option c</Option> </SearchableSelect> ); // navigate down the virutal DOM tree to find the Control content const dropMenuWrapper = wrapper.find('DropMenu'); const dropMenuChildren = dropMenuWrapper.prop('children'); const nullOptionProps = _.first( _.map(filterTypes(dropMenuChildren, DropMenu.NullOption), 'props') ); assert.equal( React.Children.toArray(nullOptionProps.children)[0], 'select one' ); }); }); describe('Option', () => { it('should pass options thru to the underlying DropMenu', () => { const wrapper = shallow( <SearchableSelect> <Placeholder>select one</Placeholder> <Option name='OptionA'>option a</Option> <Option name='OptionB'>option b</Option> <Option name='OptionC'>option c</Option> </SearchableSelect> ); const dropMenuWrapper = wrapper.find('DropMenu'); const dropMenuChildren = dropMenuWrapper.prop('children'); const optionsProps = _.map( filterTypes(dropMenuChildren, DropMenu.Option), 'props' ); assert.equal(_.size(optionsProps), 3); assert( _.isEqual(optionsProps[0], { name: 'OptionA', children: 'option a', isDisabled: false, isHidden: false, isWrapped: true, }) ); assert( _.isEqual(optionsProps[1], { name: 'OptionB', children: 'option b', isDisabled: false, isHidden: false, isWrapped: true, }) ); assert( _.isEqual(optionsProps[2], { name: 'OptionC', children: 'option c', isDisabled: false, isHidden: false, isWrapped: true, }) ); }); it('should render Option.Selected in the Placeholder area', () => { expect( shallow( <SearchableSelect selectedIndex={1}> <Placeholder>select one</Placeholder> <Option name='OptionA' Selected='option a'> <div style={{ display: 'flex' }}> <div style={{ width: 100 }}>id</div> <div>option a</div> </div> </Option> <Option name='OptionB' Selected='option b'> <div style={{ display: 'flex' }}> <div style={{ width: 100 }}>id</div> <div>option b</div> </div> </Option> <Option name='OptionC' Selected='option c'> <div style={{ display: 'flex' }}> <div style={{ width: 100 }}>id</div> <div>option c</div> </div> </Option> </SearchableSelect> ) ).toMatchSnapshot(); }); it('should render Option child function by passing in {searchText}, setting filterText on each option and using a custom optionFilter', () => { const optionFilter = (searchText: any, { filterText }: any) => { if (filterText) { return new RegExp(_.escapeRegExp(searchText), 'i').test(filterText); } return true; }; expect( shallow( <SearchableSelect optionFilter={optionFilter} searchText='tion'> <Placeholder>select one</Placeholder> <Option name='OptionA' Selected='option a' filterText='option a'> {({ searchText }: any) => ( <div style={{ display: 'flex' }}> <div style={{ width: 100 }}>{searchText}</div> <div>option a</div> </div> )} </Option> <Option name='OptionB' Selected='option b' filterText='option b'> {({ searchText }: any) => ( <div style={{ display: 'flex' }}> <div style={{ width: 100 }}>{searchText}</div> <div>option b</div> </div> )} </Option> <Option name='OptionC' Selected='option c' filterText='option c'> {({ searchText }: any) => ( <div style={{ display: 'flex' }}> <div style={{ width: 100 }}>{searchText}</div> <div>option c</div> </div> )} </Option> </SearchableSelect> ) ).toMatchSnapshot(); }); }); describe('OptionGroup', () => { let wrapper: any; let dropMenuWrapper; let dropMenuChildren; let optionGroupProps: any; beforeEach(() => { wrapper = shallow( <SearchableSelect> <Placeholder>select one</Placeholder> <OptionGroup name='TestGroup'> Group Label <Option name='OptionA'>option a</Option> <Option name='OptionB'>option b</Option> <Option name='OptionC'>option c</Option> </OptionGroup> </SearchableSelect> ); dropMenuWrapper = wrapper.find('DropMenu'); dropMenuChildren = dropMenuWrapper.prop('children'); optionGroupProps = _.first( _.map(filterTypes(dropMenuChildren, DropMenu.OptionGroup), 'props') ); }); it('should pass thru all props to the underlying DropMenu OptionGroup', () => { assert.equal(optionGroupProps.name, 'TestGroup'); }); it('should pass options thru to the underlying DropMenu OptionGroup Options', () => { const optionsProps = _.map( filterTypes(optionGroupProps.children, DropMenu.Option), 'props' ); assert.equal(_.size(optionsProps), 3); assert( _.isEqual(optionsProps[0], { name: 'OptionA', children: 'option a', isDisabled: false, isHidden: false, isWrapped: true, }) ); assert( _.isEqual(optionsProps[1], { name: 'OptionB', children: 'option b', isDisabled: false, isHidden: false, isWrapped: true, }) ); assert( _.isEqual(optionsProps[2], { name: 'OptionC', children: 'option c', isDisabled: false, isHidden: false, isWrapped: true, }) ); }); it('should pass all other elemens thru to the underlying DropMenu OptionGroup', () => { const otherOptionGroupChildren = rejectTypes( optionGroupProps.children, [Placeholder, Option, OptionGroup] ); assert.equal(_.first(otherOptionGroupChildren), 'Group Label'); }); }); }); });
the_stack
export namespace Photos { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The application's top-level scripting object. */ export interface Application { /** * The name of the application. */ name(): string; /** * Is this the active application? */ frontmost(): boolean; /** * The version number of the application. */ version(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A media item, such as a photo or video. */ export interface MediaItem { /** * A list of keywords to associate with a media item */ keywords(): any; /** * The name (title) of the media item. */ name(): string; /** * A description of the media item. */ description(): string; /** * Whether the media item has been favorited. */ favorite(): boolean; /** * The date of the media item */ date(): any; /** * The unique ID of the media item */ id(): string; /** * The height of the media item in pixels. */ height(): number; /** * The width of the media item in pixels. */ width(): number; /** * The name of the file on disk. */ filename(): string; /** * The GPS altitude in meters. */ altitude(): any; /** * The GPS latitude and longitude, in an ordered list of 2 numbers. Latitude in range -90.0 to 90.0, longitude in range -180.0 to 180.0. */ location(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Base class for collections that contains other items, such as albums and folders */ export interface Container { /** * The unique ID of this container. */ id(): string; /** * The name of this container. */ name(): string; /** * This container's parent folder, if any. */ parent(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An album. A container that holds media items */ export interface Album {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A folder. A container that holds albums and other folders, but not media items */ export interface Folder {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A set of media items that represents a Moment. */ export interface Moment { /** * The unique ID of the Moment. */ id(): string; /** * The name of the Moment. */ name(): string; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The top level scripting object for Photos. */ export interface Application { /** * The currently selected media items in the application */ selection(): any; /** * Favorited media items album. */ favoritesAlbum(): any; /** * Last import album. */ lastImportAlbum(): any; /** * Returns true if a slideshow is currently running. */ slideshowRunning(): boolean; /** * The set of recently deleted media items */ recentlyDeletedAlbum(): any; } // Records // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CountOptionalParameter { /** * The class of objects to be counted. */ each?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ImportOptionalParameter { /** * The album to import into. */ into?: any; /** * Skip duplicate checking and import everything, defaults to false. */ skipCheckDuplicates?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ExportOptionalParameter { /** * The destination of the export. */ to: any; /** * Export the original files if true, otherwise export rendered jpgs. defaults to false. */ usingOriginals?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MakeOptionalParameter { /** * The class of the new object, allowed values are album or folder */ new: any; /** * The name of the new object. */ named?: string; /** * The parent folder for the new object. */ at?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface AddOptionalParameter { /** * The album to add to. */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface StartSlideshowOptionalParameter { /** * The media items to show. */ using: any; } } export interface Photos extends Photos.Application { // Functions /** * Return the number of elements of a particular class within an object. * @param directParameter The objects to be counted. * @param option * @return The count. */ count(directParameter: any, option?: Photos.CountOptionalParameter): number; /** * Verify that an object exists. * @param directParameter The object(s) to check. * @return Did the object(s) exist? */ exists(directParameter: any, ): boolean; /** * Open a photo library * @param directParameter The photo library to be opened. * */ open(directParameter: {}, ): void; /** * Quit the application. * */ quit(): void; /** * Import files into the library * @param directParameter The list of files to copy. * @param option * @return The imported media items in an array */ import(directParameter: {}, option?: Photos.ImportOptionalParameter): void; /** * Export media items to the specified location as files * @param directParameter The list of media items to export. * @param option * */ export(directParameter: {}, option?: Photos.ExportOptionalParameter): void; /** * Duplicate an object. Only media items can be duplicated * @param directParameter The media item to duplicate * @return The duplicated media item */ duplicate(directParameter: {}, ): Photos.MediaItem; /** * Create a new object. Only new albums and folders can be created. * @param option * @return The new object. */ make(option?: Photos.MakeOptionalParameter): void; /** * Delete an object. Only albums and folders can be deleted. * @param directParameter The album or folder to delete. * */ delete(directParameter: {}, ): void; /** * Add media items to an album. * @param directParameter The list of media items to add. * @param option * */ add(directParameter: {}, option?: Photos.AddOptionalParameter): void; /** * Display an ad-hoc slide show from a list of media items, an album, a folder, or a moment * @param option * */ startSlideshow(option?: Photos.StartSlideshowOptionalParameter): void; /** * End the currently-playing slideshow. * */ stopSlideshow(): void; /** * Skip to next slide in currently-playing slideshow. * */ nextSlide(): void; /** * Skip to previous slide in currently-playing slideshow. * */ previousSlide(): void; /** * Pause the currently-playing slideshow. * */ pauseSlideshow(): void; /** * Resume the currently-playing slideshow. * */ resumeSlideshow(): void; /** * Show the image at path in the application, used to show spotlight search results * @param directParameter The full path to the image * */ spotlight(directParameter: {}, ): void; }
the_stack
import * as assert from "assert"; import * as clipboardy from "clipboardy"; import * as path from "path"; import * as vscode from "vscode"; import { Commands, ContainerNode, contextManager, DependencyExplorer, IMainClassInfo, INodeData, NodeKind, PackageNode, PackageRootNode, PrimaryTypeNode, ProjectNode } from "../../extension.bundle"; import { fsPath, setupTestEnv, Uris } from "../shared"; import { sleep } from "../util"; // tslint:disable: only-arrow-functions suite("Maven Project View Tests", () => { suiteSetup(setupTestEnv); test("Can node render correctly in hierarchical view", async function() { await vscode.workspace.getConfiguration("java.dependency").update("packagePresentation", "hierarchical"); await vscode.commands.executeCommand(Commands.VIEW_PACKAGE_CHANGETOHIERARCHICALPACKAGEVIEW); await vscode.commands.executeCommand(Commands.VIEW_PACKAGE_REFRESH); const explorer = DependencyExplorer.getInstance(contextManager.context); const roots = await explorer.dataProvider.getChildren(); assert.equal(roots?.length, 1, "Number of root node should be 1"); const projectNode = roots![0] as ProjectNode; assert.equal(projectNode.name, "my-app", "Project name should be \"my-app\""); const packageRoots = await projectNode.getChildren(); assert.equal(packageRoots.length, 4, "Number of root packages should be 4"); const mainPackage = packageRoots[0] as PackageRootNode; assert.equal(mainPackage.name, "src/main/java", "Package name should be \"src/main/java\""); const primarySubPackages = await mainPackage.getChildren(); assert.equal(primarySubPackages.length, 1, "Number of primary subpackages should be 1"); const primarySubPackage = primarySubPackages[0] as PackageNode; assert.equal(primarySubPackage.name, "com.mycompany", "Name of primary subpackage should be \"com.mycompany\""); const secondarySubPackages = await primarySubPackage.getChildren(); assert.equal(secondarySubPackages.length, 2, "Number of secondary subpackages should be 1"); const firstSecondarySubPackage = secondarySubPackages[0] as PackageNode; const secondSecondarySubPackage = secondarySubPackages[1] as PackageNode; assert.equal(firstSecondarySubPackage.nodeData.displayName, "app", "Name of first secondary subpackage should be \"app\""); assert.equal(secondSecondarySubPackage.nodeData.displayName, "app1", "Name of first secondary subpackage should be \"app1\""); // validate innermost layer nodes const classes = await firstSecondarySubPackage.getChildren(); assert.equal(classes.length, 3, "Number of main classes of first package should be 3"); const firstClass = classes[0] as PrimaryTypeNode; const secondClass = classes[1] as PrimaryTypeNode; const thirdClass = classes[2] as PrimaryTypeNode; assert.equal(firstClass.name, "App", "Name of first class should be \"App\""); assert.equal(secondClass.name, "AppToDelete", "Name of second class should be \"AppToDelete\""); assert.equal(thirdClass.name, "AppToRename", "Name of third class should be \"AppToRename\""); }); test("Can node render correctly in flat view", async function() { await vscode.workspace.getConfiguration("java.dependency").update("packagePresentation", "flat"); await vscode.commands.executeCommand(Commands.VIEW_PACKAGE_CHANGETOFLATPACKAGEVIEW); await vscode.commands.executeCommand(Commands.VIEW_PACKAGE_REFRESH); const explorer = DependencyExplorer.getInstance(contextManager.context); // validate root nodes const roots = await explorer.dataProvider.getChildren(); assert.equal(roots?.length, 1, "Number of root node should be 1"); const projectNode = roots![0] as ProjectNode; assert.equal(projectNode.name, "my-app", "Project name should be \"my-app\""); // validate package root/dependency nodes const packageRoots = await projectNode.getChildren(); assert.equal(packageRoots.length, 4, "Number of root packages should be 4"); const mainPackage = packageRoots[0] as PackageRootNode; const testPackage = packageRoots[1] as PackageRootNode; assert.equal(mainPackage.name, "src/main/java", "Package name should be \"src/main/java\""); assert.equal(testPackage.name, "src/test/java", "Package name should be \"src/test/java\""); const systemLibrary = packageRoots[2] as ContainerNode; const mavenDependency = packageRoots[3] as ContainerNode; // only match prefix of system library since JDK version may differ assert.ok(systemLibrary.name.startsWith("JRE System Library"), "Container name should start with JRE System Library"); assert.equal(mavenDependency.name, "Maven Dependencies", "Container name should be \"Maven Dependencies\""); // validate package nodes const mainSubPackages = await mainPackage.getChildren(); const testSubPackages = await testPackage.getChildren(); assert.equal(mainSubPackages.length, 2, "Number of main sub packages should be 2"); assert.equal(testSubPackages.length, 1, "Number of test sub packages should be 1"); const firstMainSubPackage = mainSubPackages[0] as PackageNode; const secondMainSubPackage = mainSubPackages[1] as PackageNode; const testSubPackage = testSubPackages[0] as PackageNode; assert.equal(firstMainSubPackage.name, "com.mycompany.app", "Name of first main subpackage should be \"com.mycompany.app\""); assert.equal(secondMainSubPackage.name, "com.mycompany.app1", "Name of second main subpackage should be \"com.mycompany.app1\""); assert.equal(testSubPackage.name, "com.mycompany.app", "Name of test subpackage should be \"com.mycompany.app\""); // validate innermost layer nodes const mainClasses = await firstMainSubPackage.getChildren(); const testClasses = await testSubPackage.getChildren(); assert.equal(mainClasses.length, 3, "Number of main classes of first package should be 3"); assert.equal(testClasses.length, 1, "Number of test classes should be 1"); const firstMainClass = mainClasses[0] as PrimaryTypeNode; const secondMainClass = mainClasses[1] as PrimaryTypeNode; const thirdMainClass = mainClasses[2] as PrimaryTypeNode; const testClass = testClasses[0] as PrimaryTypeNode; assert.equal(firstMainClass.name, "App", "Name of first class should be \"App\""); assert.equal(secondMainClass.name, "AppToDelete", "Name of second class should be \"AppToDelete\""); assert.equal(thirdMainClass.name, "AppToRename", "Name of third class should be \"AppToRename\""); assert.equal(testClass.name, "AppTest", "Name of test class should be \"AppTest\""); }); test("Can node have correct uri", async function() { const explorer = DependencyExplorer.getInstance(contextManager.context); const projectNode = (await explorer.dataProvider.getChildren())![0] as ProjectNode; const packageRoots = await projectNode.getChildren(); const mainPackage = packageRoots[0] as PackageRootNode; const testPackage = packageRoots[1] as PackageRootNode; const mainSubPackage = (await mainPackage.getChildren())[0] as PackageNode; const testSubPackage = (await testPackage.getChildren())[0] as PackageNode; const mainClass = (await mainSubPackage.getChildren())[0] as PrimaryTypeNode; const testClass = (await testSubPackage.getChildren())[0] as PrimaryTypeNode; assert.equal(fsPath(projectNode), Uris.MAVEN_PROJECT_NODE, "Project uri incorrect"); assert.equal(fsPath(mainPackage), Uris.MAVEN_MAIN_PACKAGE, "Main root package uri incorrect"); assert.equal(fsPath(testPackage), Uris.MAVEN_TEST_PACKAGE, "Test root package uri incorrect"); assert.equal(fsPath(mainSubPackage), Uris.MAVEN_MAIN_SUBPACKAGE, "Main subpackage uri incorrect"); assert.equal(fsPath(testSubPackage), Uris.MAVEN_TEST_SUBPACKAGE, "Test subpackage uri incorrect"); assert.equal(fsPath(mainClass), Uris.MAVEN_MAIN_CLASS, "Main class uri incorrect"); assert.equal(fsPath(testClass), Uris.MAVEN_TEST_CLASS, "Test class uri incorrect"); }); test("Can execute command java.view.package.copyFilePath correctly", async function() { const explorer = DependencyExplorer.getInstance(contextManager.context); const projectNode = (await explorer.dataProvider.getChildren())![0] as ProjectNode; const packageRoots = await projectNode.getChildren(); const mainPackage = packageRoots[0] as PackageRootNode; const mainSubPackage = (await mainPackage.getChildren())[0] as PackageNode; const mainClass = (await mainSubPackage.getChildren())[0] as PrimaryTypeNode; await vscode.commands.executeCommand(Commands.VIEW_PACKAGE_COPY_FILE_PATH, mainClass); await sleep(1000); const content = await clipboardy.read(); const contentUri = vscode.Uri.file(content); const dataUri = mainClass.nodeData.uri; assert.ok(dataUri, `Class node should have correct uri`); const expectedUri = vscode.Uri.parse(dataUri!); assert.equal(contentUri.fsPath, expectedUri.fsPath, `File path should be copied correctly`); }); test("Can execute command java.view.package.copyRelativeFilePath correctly", async function() { const explorer = DependencyExplorer.getInstance(contextManager.context); const projectNode = (await explorer.dataProvider.getChildren())![0] as ProjectNode; const packageRoots = await projectNode.getChildren(); const mainPackage = packageRoots[0] as PackageRootNode; const mainSubPackage = (await mainPackage.getChildren())[0] as PackageNode; const mainClass = (await mainSubPackage.getChildren())[0] as PrimaryTypeNode; await vscode.commands.executeCommand(Commands.VIEW_PACKAGE_COPY_RELATIVE_FILE_PATH, mainClass); await sleep(1000); const content = await clipboardy.read(); const dataUri = mainClass.nodeData.uri; assert.ok(dataUri, `Class node should have correct uri`); const expectedUri = vscode.Uri.parse(dataUri!); const workspaceFolders = vscode.workspace.workspaceFolders; assert.ok(workspaceFolders, `There should be valid workspace folders`); const relativePath = path.relative(workspaceFolders![0].uri.fsPath, expectedUri.fsPath); assert.equal(content, relativePath, `Relative file path should be copied correctly`); }); test("Can execute command java.project.list correctly", async function() { const workspaceFolders = vscode.workspace.workspaceFolders; assert.ok(workspaceFolders, `There should be valid workspace folders`); const projects = await vscode.commands.executeCommand<INodeData[]>(Commands.EXECUTE_WORKSPACE_COMMAND, Commands.JAVA_PROJECT_LIST, workspaceFolders![0].uri.toString()); assert.equal(projects?.length, 1, "project's length should be 1"); assert.equal(projects![0].name, "my-app", "project should be my-app"); }); test("Can execute command java.getPackageData correctly", async function() { const explorer = DependencyExplorer.getInstance(contextManager.context); const projectNode = (await explorer.dataProvider.getChildren())![0] as ProjectNode; const packageRoots = await projectNode.getChildren(); const mainPackage = packageRoots[0] as PackageRootNode; const workspaceFolders = vscode.workspace.workspaceFolders; assert.ok(workspaceFolders, `There should be valid workspace folders`); const packages = await vscode.commands.executeCommand<INodeData[]>(Commands.EXECUTE_WORKSPACE_COMMAND, Commands.JAVA_GETPACKAGEDATA, { kind: NodeKind.PackageRoot, projectUri: workspaceFolders![0].uri.toString(), path: mainPackage.nodeData.name, handlerIdentifier: mainPackage.nodeData.handlerIdentifier, }); assert.equal(packages?.length, 2, "packages' length should be 2"); assert.equal(packages![0].name, "com.mycompany.app", "package[0]'s name should be com.mycompany.app"); assert.equal(packages![1].name, "com.mycompany.app1", "package[1]'s name should be com.mycompany.app1"); }); test("Can execute command java.resolvePath correctly", async function() { const explorer = DependencyExplorer.getInstance(contextManager.context); const projectNode = (await explorer.dataProvider.getChildren())![0] as ProjectNode; const packageRoots = await projectNode.getChildren(); const mainPackage = packageRoots[0] as PackageRootNode; const paths = await vscode.commands.executeCommand<INodeData[]>(Commands.EXECUTE_WORKSPACE_COMMAND, Commands.JAVA_RESOLVEPATH, mainPackage.nodeData.uri); assert.equal(paths?.length, 3, "paths' length should be 3"); assert.equal(paths![0].name, "src", "path[0]'s name should be src"); assert.equal(paths![1].name, "main", "path[1]'s name should be main"); assert.equal(paths![2].name, "java", "path[2]'s name should be java"); }); test("Can execute command java.project.getMainClasses correctly", async function() { const workspaceFolders = vscode.workspace.workspaceFolders; assert.ok(workspaceFolders, `There should be valid workspace folders`); const mainClasses = await vscode.commands.executeCommand<IMainClassInfo[]>(Commands.EXECUTE_WORKSPACE_COMMAND, Commands.JAVA_PROJECT_GETMAINCLASSES, workspaceFolders![0].uri.toString()); assert.equal(mainClasses?.length, 1, "mainClasses' length should be 1"); assert.equal(mainClasses![0].name, "com.mycompany.app.App", "mainClasses[0]'s name should be com.mycompany.app.App"); }); });
the_stack
import { getAzureResourceIdentifiers, getAzureResourceIdentifier } from './azureResourceIdentifierService'; import { AzureResourceIdentifierType } from '../models/azureResourceIdentifierType'; import { HttpError } from '../../api/models/httpError'; import { HTTP_OPERATION_TYPES, APPLICATION_JSON } from '../../constants/apiConstants'; describe('getAzureResourceIdentifiers', () => { it('calls fetch with specificed parameters', () => { getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); const resourceUrl = `https://managementEndpoint/providers/Microsoft.ResourcesGraph/resources?api-version=2019-04-01`; const serviceRequestParams = { body: JSON.stringify({ query: `where type =~ 'microsoft.devices/iothubs' | project id,name,type,location,resourceGroup,subscriptionId`, subscriptions: ['sub1', 'sub2'], }), headers: new Headers({ 'Accept': APPLICATION_JSON, 'Authorization': `Bearer token`, 'Content-Type': APPLICATION_JSON }), method: HTTP_OPERATION_TYPES.Post }; expect(fetch).toHaveBeenLastCalledWith(resourceUrl, serviceRequestParams); }); it('calls fetch with specificed parameters when continuation token provided', () => { getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, continuationToken: 'continuationToken', resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); const resourceUrl = `https://managementEndpoint/providers/Microsoft.ResourcesGraph/resources?api-version=2019-04-01`; const serviceRequestParams = { body: JSON.stringify({ query: `where type =~ 'microsoft.devices/iothubs' | project id,name,type,location,resourceGroup,subscriptionId`, subscriptions: ['sub1', 'sub2'], // tslint:disable-next-line:object-literal-sort-keys options: { $skipToken: 'continuationToken' } }), headers: new Headers({ 'Accept': APPLICATION_JSON, 'Authorization': `Bearer token`, 'Content-Type': APPLICATION_JSON }), method: HTTP_OPERATION_TYPES.Post }; expect(fetch).toHaveBeenLastCalledWith(resourceUrl, serviceRequestParams); }); it('throws exception when response.ok is false', async () => { const httpError = new HttpError(0); jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return {}; }, ok: false, } as any); // tslint:disable-line:no-any await expect(getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] })).rejects.toThrow(httpError); }); it('returns empty array when no data object present', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return {}; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual({ continuationToken: undefined, resultSet: [] }); }); it('returns empty array when no data.rows object present', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return { data: { } }; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual({ continuationToken: undefined, resultSet: [] }); }); it('returns empty array when no data.rows is empty array', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return { data: { rows: [] } }; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual({ continuationToken: undefined, resultSet: [] }); }); it ('returns expected entries when rows returned', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return { data: { rows: [ [ 'id1', 'name1', 'type1', 'location1', 'resourceGroup1', 'sub1'], [ 'id2', 'name2', 'type1', 'location2', 'resourceGroup2', 'sub2'] ] } }; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual({ continuationToken: undefined, resultSet: [ { id: 'id1', location: 'location1', name: 'name1', resourceGroup: 'resourceGroup1', subscriptionId: 'sub1', type: 'type1', }, { id: 'id2', location: 'location2', name: 'name2', resourceGroup: 'resourceGroup2', subscriptionId: 'sub2', type: 'type1', }, ] }); }); it ('returns continuationToken when defined', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return { $skipToken: 'skipToken', data: { rows: [ [ 'id1', 'name1', 'type1', 'location1', 'resourceGroup1', 'sub1'], [ 'id2', 'name2', 'type1', 'location2', 'resourceGroup2', 'sub2'] ] } }; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifiers({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual({ continuationToken: 'skipToken', resultSet: [ { id: 'id1', location: 'location1', name: 'name1', resourceGroup: 'resourceGroup1', subscriptionId: 'sub1', type: 'type1', }, { id: 'id2', location: 'location2', name: 'name2', resourceGroup: 'resourceGroup2', subscriptionId: 'sub2', type: 'type1', }, ] }); }); }); describe('getAzureResourceIdentifier', () => { it('calls fetch with specificed parameters', () => { getAzureResourceIdentifier({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceName: 'resourceName', resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); const resourceUrl = `https://managementEndpoint/providers/Microsoft.ResourcesGraph/resources?api-version=2019-04-01`; const serviceRequestParams = { body: JSON.stringify({ query: `where type =~ 'microsoft.devices/iothubs' and name =~ 'resourceName' | project id,name,type,location,resourceGroup,subscriptionId`, subscriptions: ['sub1', 'sub2'], }), headers: new Headers({ 'Accept': APPLICATION_JSON, 'Authorization': `Bearer token`, 'Content-Type': APPLICATION_JSON }), method: HTTP_OPERATION_TYPES.Post }; expect(fetch).toHaveBeenLastCalledWith(resourceUrl, serviceRequestParams); }); it('throws exception when response.ok is false', async () => { const httpError = new HttpError(0); jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return {}; }, ok: false, } as any); // tslint:disable-line:no-any await expect(getAzureResourceIdentifier({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceName: 'resourceName', resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] })).rejects.toThrow(httpError); }); it('returns undefined when no data returned', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return { data: { } }; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifier({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceName: 'resourceName', resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual(undefined); }); it('returns undefined when rows empty array', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return { data: { rows: [] } }; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifier({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceName: 'resourceName', resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual(undefined); }); it('returns first entry of results', async () => { jest.spyOn(window, 'fetch').mockResolvedValue({ json: () => { return { data: { rows: [ [ 'id1', 'name1', 'type1', 'location1', 'resourceGroup1', 'sub1'], [ 'id2', 'name2', 'type1', 'location2', 'resourceGroup2', 'sub2'] ] } }; }, ok: true, } as any); // tslint:disable-line:no-any const result = await getAzureResourceIdentifier({ azureResourceManagementEndpoint: { authorizationToken: 'token', endpoint: 'managementEndpoint' }, resourceName: 'resourceName', resourceType: AzureResourceIdentifierType.IotHub, subscriptionIds: ['sub1', 'sub2'] }); expect(result).toEqual({ id: 'id1', location: 'location1', name: 'name1', resourceGroup: 'resourceGroup1', subscriptionId: 'sub1', type: 'type1', }); }); });
the_stack
module ApimanPageLifecycle { export var pageTitles = { "page.title.admin-gateways": "apiman - Admin - Gateways", "page.title.admin-plugins": "apiman - Admin - Plugins", "page.title.admin-roles": "apiman - Admin - Roles", "page.title.admin-policyDefs": "apiman - Admin - Policy Definitions", "page.title.admin-export": "apiman - Admin - Export/Import", "page.title.api-catalog": "apiman - API Catalog", "page.title.api-catalog-def": "apiman - API Definition", "page.title.client-activity": "apiman - {0} (Change Log)", "page.title.client-apis": "apiman - {0} (APIs)", "page.title.client-contracts": "apiman - {0} (Contracts)", "page.title.client-metrics": "apiman - {0} (Metrics)", "page.title.client-overview": "apiman - {0} (Overview)", "page.title.client-policies": "apiman - {0} (Policies)", "page.title.consumer-org": "apiman - Organization {0}", "page.title.consumer-orgs": "apiman - Organizations", "page.title.consumer-api": "apiman - API {0}", "page.title.consumer-api-def": "apiman - API {0} - Definition", "page.title.consumer-apis": "apiman - APIs", "page.title.dashboard": "apiman - Home", "page.title.about": "apiman - About", "page.title.edit-gateway": "apiman - Edit Gateway", "page.title.edit-policy": "apiman - Edit Policy", "page.title.edit-policyDef": "apiman - Edit Policy Definition", "page.title.edit-role": "apiman - Edit Role", "page.title.import-policyDefs": "apiman - Import Policy Definition(s)", "page.title.import-apis": "apiman - Import API(s)", "page.title.new-client": "apiman - New Client App", "page.title.new-client-version": "apiman - New Client App Version", "page.title.new-contract": "apiman - New Contract", "page.title.new-gateway": "apiman - New Gateway", "page.title.new-member": "apiman - Add Member", "page.title.new-org": "apiman - New Organization", "page.title.new-plan": "apiman - New Plan", "page.title.new-plan-version": "apiman - New Plan Version", "page.title.new-plugin": "apiman - Add Plugin", "page.title.new-policy": "apiman - Add Policy", "page.title.new-role": "apiman - New Role", "page.title.new-api": "apiman - New API", "page.title.new-api-version": "apiman - New API Version", "page.title.manager-rest-def": "apiman - REST API", "page.title.org-activity": "apiman - {0} (Change Log)", "page.title.org-clients": "apiman - {0} (Client Apps)", "page.title.org-manage-members": "apiman - {0} (Manage Members)", "page.title.org-members": "apiman - {0} (Members)", "page.title.org-plans": "apiman - {0} (Plans)", "page.title.org-apis": "apiman - {0} (APIs)", "page.title.plan-activity": "apiman - {0} (Change Log)", "page.title.plan-overview": "apiman - {0} (Overview)", "page.title.plan-policies": "apiman - {0} (Policies)", "page.title.plugin-details": "apiman - Plugin Details", "page.title.policy-defs": "apiman - Admin - Policy Definitions", "page.title.api-activity": "apiman - {0} (Change Log)", "page.title.api-contracts": "apiman - {0} (Contracts)", "page.title.api-endpoint": "apiman - {0} (Endpoint)", "page.title.api-metrics": "apiman - {0} (Metrics)", "page.title.api-impl": "apiman - {0} (Implementation)", "page.title.api-def": "apiman - {0} (Definition)", "page.title.api-overview": "apiman - {0} (Overview)", "page.title.api-plans": "apiman - {0} (Plans)", "page.title.api-policies": "apiman - {0} (Policies)", "page.title.user-activity": "apiman - {0} (Change Log)", "page.title.user-clients": "apiman - {0} (Client Apps)", "page.title.user-orgs": "apiman - {0} (Organizations)", "page.title.user-profile": "apiman - User Profile", "page.title.user-apis": "apiman - {0} (APIs)", "page.title.error": "apiman - {0} Error", }; var formatMessage = function(theArgs) { var now = new Date(); var msg = theArgs[0]; if (theArgs.length > 1) { for (var i = 1; i < theArgs.length; i++) { msg = msg.replace('{'+(i-1)+'}', theArgs[i]); } } return msg; }; export var _module = angular.module("ApimanPageLifecycle", []); export var PageLifecycle = _module.factory('PageLifecycle', ['$q', '$timeout', 'Logger', '$rootScope', '$location', 'CurrentUserSvcs', 'Configuration', 'TranslationSvc', '$window', 'CurrentUser', ($q, $timeout, Logger, $rootScope, $location, CurrentUserSvcs, Configuration, TranslationSvc, $window, CurrentUser) => { var header = 'community'; if (Configuration.ui && Configuration.ui.header) { header = Configuration.ui.header; } if (header == 'apiman') { header = 'community'; } $rootScope.headerInclude = 'plugins/api-manager/html/headers/' + header + '.include'; console.log('Using header: ' + $rootScope.headerInclude); let redirectWrongPermission = function () { Logger.info('Detected a 404 error.'); $location.url(Apiman.pluginName + '/errors/404').replace(); return; }; var processCurrentUser = function(currentUser) { $rootScope.currentUser = currentUser; var permissions = {}; var memberships = {}; if (currentUser.permissions) { for (var i = 0; i < currentUser.permissions.length; i++) { var perm = currentUser.permissions[i]; var permid = perm.organizationId + '||' + perm.name; permissions[permid] = true; memberships[perm.organizationId] = true; } } Logger.info('Updating permissions now {0}', permissions); $rootScope.permissions = permissions; $rootScope.memberships = memberships; $rootScope.isAdmin = currentUser.admin; }; var handleError = function(error) { $rootScope.pageState = 'error'; $rootScope.pageError = error; if (error.status == 400) { Logger.info('Detected an error {0}, redirecting to 400.', error.status); $location.url(Apiman.pluginName + '/errors/400').replace(); } else if (error.status == 401) { Logger.info('Detected an error 401, reloading the page.'); $window.location.reload(); } else if (error.status == 403) { Logger.info('Detected an error {0}, redirecting to 403.', error.status); $location.url(Apiman.pluginName + '/errors/403').replace(); } else if (error.status == 404) { Logger.info('Detected an error {0}, redirecting to 404.', error.status); $location.url(Apiman.pluginName + '/errors/404').replace(); } else if (error.status == 409) { Logger.info('Detected an error {0}, redirecting to 409.', error.status); var errorUri = '409'; Logger.info('=====> {0}', error); Logger.info('=====> error code: {0}', error.data.errorCode); if (error.data.errorCode && error.data.errorCode == 8002) { errorUri = '409-8002'; } $location.url(Apiman.pluginName + '/errors/' + errorUri).replace(); } else if (error.status == 0) { Logger.info('Detected an error {0}, redirecting to CORS error page.', error.status); $location.url(Apiman.pluginName + '/errors/invalid_server').replace(); } else { // TODO: if the error data starts with <html> then redirect to a more generic html-into-div based error page Logger.info('Detected an error {0}, redirecting to 500.', error.status); $location.url(Apiman.pluginName + '/errors/500').replace(); } }; return { setPageTitle: function(titleKey, params) { var key = 'page.title.' + titleKey; var pattern = pageTitles[key]; pattern = TranslationSvc.translate(key, pattern); if (pattern) { var args = []; args.push(pattern); args = args.concat(params); var title = formatMessage(args); document.title = title; } else { document.title = pattern; } }, handleError: handleError, forwardTo: function() { var path = '/' + Apiman.pluginName + formatMessage(arguments); Logger.info('Forwarding to page {0}', path); $location.url(path).replace(); }, redirectTo: function() { var path = '/' + Apiman.pluginName + formatMessage(arguments); Logger.info('Redirecting to page {0}', path); $location.url(path); }, loadPage: function(pageName, requiredPermission, pageData, $scope, handler) { Logger.log("|{0}| >> Loading page.", pageName); $rootScope.pageState = 'loading'; $rootScope.isDirty = false; var currentUser = $q(function(resolve, reject) { if ($rootScope.currentUser) { Logger.log("|{0}| >> Using cached current user from $rootScope.", pageName); resolve($rootScope.currentUser); } else { return CurrentUserSvcs.get({ what: 'info' }, function(currentUser) { processCurrentUser(currentUser); resolve(currentUser); }, reject); } }); // Now resolve the data as a promise (wait for all data packets to be fetched) return currentUser.then(function (){ return $q.all(pageData); }).then(function(data) { // Make sure the user has permission to view this page. if ( (requiredPermission && requiredPermission == 'orgView' && !CurrentUser.isMember($scope.organizationId)) || ( requiredPermission && requiredPermission != 'orgView' && !CurrentUser.hasPermission($scope.organizationId, requiredPermission)) ) { redirectWrongPermission(); } // Now process all the data packets and bind them to the $scope. var count = 0; angular.forEach(data, function(value, key) { Logger.debug("|{0}| >> Binding {1} to $scope.", pageName, key); this[key] = value; count++; }, $scope); $timeout(function() { $rootScope.pageState = 'loaded'; Logger.log("|{0}| >> Page successfully loaded: {1} data packets loaded", pageName, count); if (handler) { $timeout(function() { Logger.log("|{0}| >> Calling Page onLoaded handler", pageName); handler(); }, 20); } }, 50); }, function(reason) { Logger.error("|{0}| >> Page load failed: {1}", pageName, reason); handleError(reason); }); }, loadErrorPage: function(pageName, $scope, handler) { Logger.log("|{0}| >> Loading error page.", pageName); $rootScope.pageState = 'loading'; // Nothing to do asynchronously for the error pages! $rootScope.pageState = 'loaded'; if (handler) { handler(); } Logger.log("|{0}| >> Error page successfully loaded", pageName); } } }]); }
the_stack
import * as vscode from 'vscode'; import {Labels, SourceFileEntry} from './labels/labels'; //import {Log} from './log'; //import { Settings } from './settings'; import {Disassembly, DisassemblyClass} from './misc/disassembly'; import {UnifiedPath} from './misc/unifiedpath'; import {Utility} from './misc/utility'; /// Is a singleton. Initialize in 'activate'. export let Decoration: DecorationClass; /** * Each decoration type (coverage, reverse debug, break) gets its own * instance of DecorationFileMap. */ class DecorationFileMap { /// The decoration type for covered lines. public decoType: vscode.TextEditorDecorationType; /// Holds a map with filenames associated with the lines. public fileMap: Map<string, Array<vscode.Range> | Array<vscode.DecorationOptions>>; } /** * A singleton that holds the editor decorations for code coverage, * reverse debugging andother decorations, e.g. 'break'. * * Decorations are tedious to handle. * If an editor becomes inactive (hidden) it looses its decorations * therefore it is necessary * - to watch for changes of the active editor * - and to store the decorations for each document/editor * This means: decoration are added to the editor as soon as they occur and also * whenever the active editor changes. * What makes it even more complicated is the fact that the disasm.asm file may not even exist * when a decoration comes in. And, furthermore, the file may exist already but change * its contents. * The disasm.asm is created during the stackTraceRequest. * It requires decoration (like the other files) of * - coverage (green background) * - historySpot (the index numbers) * - revDbg history (gray background) * - break reason (text) * 'coverage' is a special case as here only the delta addresses are reported. * Therefore it is necessary to store all addresses that do not belong to any other * (ordinary) file (in unassignedCodeCoverageAddresses). * Also 'coverage' is not emitted in case of reverse debugging. * 'historySpot', 'revDbg' and 'break' always contain the complete decoration information. * All those calls are delayed in the debugAdapter until the disasm.asm file is created in the * stackTraceRequest. This is already done in the debugAdapter. */ export class DecorationClass { // Names to identify the decorations. protected COVERAGE = "Coverage"; protected REVERSE_DEBUG = "RevDbg"; protected BREAK = "Break"; protected HISTORY_SPOT = "HistorySpot"; // Holds the decorations for coverage, reverse debug and breakpoints. protected decorationFileMaps: Map<string, DecorationFileMap>; // Collects the coverage addresses that are not assigned yet to any file. protected unassignedCodeCoverageAddresses: Set<number>; /// Initialize. Call from 'activate' to set the icon paths. public static Initialize() { // Create new singleton Decoration = new DecorationClass(); } /** * Register for a change of the text editor to decorate it with the * covered lines. */ constructor() { // Create the decoration types. const coverageDecoType = vscode.window.createTextEditorDecorationType({ isWholeLine: true, gutterIconSize: 'auto', light: { // this color will be used in light color themes backgroundColor: '#d5efc3a0', }, dark: { // this color will be used in dark color themes backgroundColor: '#09300390', } /* light: { // this color will be used in light color themes backgroundColor: '#B0E090', }, dark: { // this color will be used in dark color themes backgroundColor: '#0C4004', } */ }); // For the short history decoration type. const historySpotDecoType = vscode.window.createTextEditorDecorationType({ isWholeLine: true, gutterIconSize: 'auto', light: { // this color will be used in light color themes // backgroundColor: '#89C2D3', after: { color: "#808080", } }, dark: { // this color will be used in dark color themes // backgroundColor: '#022031', after: { color: "#808080", } }, }); // Decoration for reverse debugging. const revDbgDecoType = vscode.window.createTextEditorDecorationType({ isWholeLine: true, gutterIconSize: 'auto', /* This gives a bad performance, it's better to change just the color. borderWidth: '1px', borderStyle: 'dashed', //'solid', borderRadius: '5px', */ light: { // this color will be used in light color themes //backgroundColor: '#A9E2F3', backgroundColor: '#C7C7C7', }, dark: { // this color will be used in dark color themes //backgroundColor: '#033563', backgroundColor: '#353535', } }); // Decoration for 'Breaks' const breakDecoType = vscode.window.createTextEditorDecorationType({ isWholeLine: true, gutterIconSize: 'auto', light: { after: { color: "black", } }, dark: { after: { color: "#808080", } } }); // Create the map this.decorationFileMaps = new Map<string, DecorationFileMap>(); let decoFileMap = new DecorationFileMap(); decoFileMap.decoType = coverageDecoType; decoFileMap.fileMap = new Map<string, Array<vscode.Range>>(); this.decorationFileMaps.set(this.COVERAGE, decoFileMap); decoFileMap = new DecorationFileMap(); decoFileMap.decoType = revDbgDecoType; decoFileMap.fileMap = new Map<string, Array<vscode.Range>>(); this.decorationFileMaps.set(this.REVERSE_DEBUG, decoFileMap); decoFileMap = new DecorationFileMap(); decoFileMap.decoType = breakDecoType; decoFileMap.fileMap = new Map<string, Array<vscode.DecorationOptions>>(); this.decorationFileMaps.set(this.BREAK, decoFileMap); decoFileMap = new DecorationFileMap(); decoFileMap.decoType = historySpotDecoType; decoFileMap.fileMap = new Map<string, Array<vscode.DecorationOptions>>(); this.decorationFileMaps.set(this.HISTORY_SPOT, decoFileMap); this.unassignedCodeCoverageAddresses = new Set<number>(); // Watch the text editors to decorate them. vscode.window.onDidChangeActiveTextEditor(editor => { // This is called for the editor that is going to hide and for the editor // that is shown. // Unfortunately there is no way to differentiate so both are handled. // Note: Editors forget the decorations when they are hidden. I.e. decorations have to be re-applied here. this.setAllDecorations(editor); }); } /** * Loops through all active editors and clear the coverage decorations. */ public clearCodeCoverage() { this.clearDecorations(this.COVERAGE); } /** * Loops through all active editors and clears the reverse debug decorations. */ public clearRevDbgHistory() { this.clearDecorations(this.REVERSE_DEBUG); } /** * Loops through all active editors and clears the 'Break' decorations. */ public clearBreak() { this.clearDecorations(this.BREAK); } /** * Loops through all active editors and clears the 'historySpot' decorations. */ public clearHistorySpot() { this.clearDecorations(this.HISTORY_SPOT); } /** * Loops through all active editors and clear the decorations. * @param mapName E.g. COVERAGE, REVERSE_DEBUG, SHORT_HISTORY or BREAK. */ protected clearDecorations(mapName: string) { const map = this.decorationFileMaps.get(mapName) as DecorationFileMap; map.fileMap.clear(); const editors = vscode.window.visibleTextEditors; for (const editor of editors) { editor.setDecorations(map.decoType, []); } // Additionally clear array if (mapName == this.COVERAGE) this.unassignedCodeCoverageAddresses.clear(); } /** * Clears all decorations for all editors. */ public clearAllDecorations() { for (const [, map] of this.decorationFileMaps) { map.fileMap.clear(); const editors = vscode.window.visibleTextEditors; for (const editor of editors) { editor.setDecorations(map.decoType, []); } } // Additionally clear array this.unassignedCodeCoverageAddresses.clear(); } /** * Clears all decorations but the code coverage decorations for all editors. */ public clearAllButCodeCoverageDecorations() { for (const [name, map] of this.decorationFileMaps) { if (name != this.COVERAGE) { map.fileMap.clear(); const editors = vscode.window.visibleTextEditors; for (const editor of editors) { editor.setDecorations(map.decoType, []); } } } } /** * Sets decorations for all types. * Coverage, revers debug, breaks, short history. */ protected setAllDecorations(editor: vscode.TextEditor | undefined) { if (!editor) return; // Go through all coverage maps for (const [fileMapName,] of this.decorationFileMaps) { this.setDecorations(editor, fileMapName); } } /** * Sets decorations for a specific type. * Coverage, revers debug, breaks. * @param fileMapName E.g. COVERAGE, REVERSE_DEBUG, HISTORY_SPOT or BREAK. */ protected setDecorations(editor: vscode.TextEditor, fileMapName: string) { // Get filename const edFilename = UnifiedPath.getUnifiedPath(editor.document.fileName); // Special case for disassembly file and coverage. if (fileMapName == this.COVERAGE) { if (edFilename == DisassemblyClass.getAbsFilePath()) { // Handle disassembly file this.setDisasmCoverageDecoration(editor); return; // Skip normal case } } // Get file map const decoMap = this.decorationFileMaps.get(fileMapName) as DecorationFileMap; Utility.assert(decoMap); // Get lines const fileMap = decoMap.fileMap; const decorations = fileMap.get(edFilename); if (decorations) { // Set decorations editor.setDecorations(decoMap.decoType, decorations); } } /** * Sets the decorations for the disassembler temp file. */ public setDisasmCoverageDecoration(editor: vscode.TextEditor) { // Coverage const lines = Disassembly.getLinesForAddresses(this.unassignedCodeCoverageAddresses); const decorations = lines.map(lineNr => new vscode.Range(lineNr, 0, lineNr, 1000)); if (decorations) { // Set decorations const decoMap = this.decorationFileMaps.get(this.COVERAGE) as DecorationFileMap; editor.setDecorations(decoMap.decoType, decorations); } } /** * Shows (adds) the code coverage of the passed addresses. * The active editors are decorated. * The set is added to the existing ones to decorate another editor when the focus changes. * Is called when the event 'covered' has been emitted by the Emulator. * @param coveredAddresses All addresses to add (all covered addresses) */ public showCodeCoverage(coveredAddresses: Set<number>) { // Get map name const mapName = this.COVERAGE; // Loop over all addresses const decoMap = this.decorationFileMaps.get(mapName) as DecorationFileMap; const fileMap = decoMap.fileMap; //fileMap.clear(); coveredAddresses.forEach(addr => { // Get file location for address let location = Labels.getFileAndLineForAddress(addr); let filename = location.fileName; if (filename.length == 0) { // No file found, so remember address this.unassignedCodeCoverageAddresses.add(addr); return; } // Get filename set let lines = fileMap.get(filename) as Array<vscode.Range>; if (!lines) { // Create a new lines = new Array<vscode.Range>(); fileMap.set(filename, lines); } const lineNr = location.lineNr; // REMARK: Could be optimized. Here it is possible that coverage for that line already exists and would then be added 2 or more times. const range = new vscode.Range(lineNr, 0, lineNr, 1000); // Add address to set lines.push(range); }); // Loop through all open editors. const editors = vscode.window.visibleTextEditors; for (const editor of editors) { this.setDecorations(editor, this.COVERAGE); } } /** * Is called whenever the reverse debug history changes. * Will set the decoration. * @param addresses The addresses to decorate. */ public showRevDbgHistory(addresses: Set<number>) { // Clear decorations this.clearRevDbgHistory(); // Get file map const decoMap = this.decorationFileMaps.get(this.REVERSE_DEBUG) as DecorationFileMap; const fileMap = decoMap.fileMap; // Loop over all addresses addresses.forEach(addr => { // Get file location for address const location = this.getFileAndLineForAddress(addr); const filename = location.fileName; if (filename.length == 0) return; // Get filename set let lines = fileMap.get(filename) as Array<vscode.Range>; if (!lines) { // Create a new lines = new Array<vscode.Range>(); fileMap.set(filename, lines); } // Add address to set const lineNr = location.lineNr; const range = new vscode.Range(lineNr, 0, lineNr, 1000); // Add address to set lines.push(range); }); // Loop through all open editors. const editors = vscode.window.visibleTextEditors; for (const editor of editors) { this.setDecorations(editor, this.REVERSE_DEBUG); } } /** * Is called when a new 'break' should be shown. * This happens during continue, continueReverse, stepOut, stepOver. * The break decoration is cleared before all those actions. * @param pc The address to decorate. Used to find the source line. * @param text The text to show. */ public showBreak(pc: number, text: string) { // Get file map const decoMap = this.decorationFileMaps.get(this.BREAK) as DecorationFileMap; const fileMap = decoMap.fileMap; fileMap.clear(); // Get file location for pc const location = this.getFileAndLineForAddress(pc); const filename = location.fileName; if (filename.length > 0) { // Get filename set let lines = fileMap.get(filename) as Array<vscode.DecorationOptions>; if (!lines) { // Create a new lines = new Array<vscode.DecorationOptions>(); fileMap.set(filename, lines); } const lineNr = location.lineNr; const deco = { range: new vscode.Range(lineNr, 0, lineNr, 1000), hoverMessage: undefined, renderOptions: { after: { contentText: text, margin: "1.5em" }, }, }; // Add address to set lines.push(deco); } // Loop through all open editors. const editors = vscode.window.visibleTextEditors; for (const editor of editors) { this.setDecorations(editor, this.BREAK); } } /** * Is called whenever the short history changes. * Will set the decoration. * @param startIndex * @param addresses The addresses to decorate. Is an ordered list. * The youngest address (instruction) is at index 0. * @param registers An array that correspondents to 'addresses' and * includes the values of the changed registers as text. * It is shown together with the index in the decoration. * Is undefined if 'spotShowRegisters' is false. */ public showHistorySpot(startIndex, addresses: Array<number>, registers: Array<string>) { // Clear decorations this.clearHistorySpot(); // Get file map const decoMap = this.decorationFileMaps.get(this.HISTORY_SPOT) as DecorationFileMap; const fileMap = decoMap.fileMap; // Check if addresses are used more than once const addressMap = new Map<string, {regText: string, indexText: string}>(); let index = -startIndex - 1; addresses.forEach((addr, k) => { const location = this.getFileAndLineForAddress(addr); const locString = location.lineNr + ';' + location.fileName; let entry = addressMap.get(locString); if (!entry) { // Show registers only for the first entry // Add changed registers entry = {regText: registers[k] || '', indexText: index.toString()}; addressMap.set(locString, entry); } else { // But show all indices entry.indexText += ", " + index.toString(); } // Next index--; }); // Loop over all addresses for (const [locString, entry] of addressMap) { // Get file location for address //const location = Labels.getFileAndLineForAddress(addr); const k = locString.indexOf(';'); const filename = locString.substr(k + 1); if (filename.length == 0) break; // Get filename set let lines = fileMap.get(filename) as Array<vscode.DecorationOptions>; if (!lines) { // Create a new lines = new Array<vscode.DecorationOptions>(); fileMap.set(filename, lines); } // Add address to set const lineNr = parseInt(locString); const deco = { range: new vscode.Range(lineNr, 0, lineNr, 1000), hoverMessage: undefined, renderOptions: { after: { contentText: "[" + entry.indexText + "] " + entry.regText, margin: "2.5em", //height: "5px", //fontWeight: "4em", //width: "4em", //fontStyle: "italic", }, }, }; // If changes register is available: /* if (entry.regText) { deco.renderOptions.before = { contentText: "[" + entry.regText + "]", margin: "2.5em", }; } */ // Add address to set lines.push(deco); } // Loop through all open editors. const editors = vscode.window.visibleTextEditors; for (const editor of editors) { this.setDecorations(editor, this.HISTORY_SPOT); } } /** * Returns the location of addr. Either from asm file(s) or from the disassembly file. * @param addr The address to convert. */ protected getFileAndLineForAddress(addr: number): SourceFileEntry { const location = Labels.getFileAndLineForAddress(addr); if (location.fileName.length == 0) { // Try disasm file const lineNr = Disassembly.getLineForAddress(addr); if (lineNr != undefined) { // Use disassembly file location.fileName = DisassemblyClass.getAbsFilePath(); location.lineNr = lineNr; } } return location; } }
the_stack
type View = import("@nativescript/core/ui/core/view").View; type NavigationButton = import("@nativescript/core/ui/action-bar").NavigationButton; type ActionItems = import("@nativescript/core/ui/action-bar").ActionItems; type AndroidActionBarSettings = import("@nativescript/core/ui/action-bar").AndroidActionBarSettings; type LengthDipUnit = import("@nativescript/core/ui/styling/style-properties").LengthDipUnit; type LengthPxUnit = import("@nativescript/core/ui/styling/style-properties").LengthPxUnit; type PropertyChangeData = import("@nativescript/core/data/observable").PropertyChangeData; type Color = import("@nativescript/core/color").Color; type LinearGradient = import("@nativescript/core/ui/styling/gradient").LinearGradient; type LengthPercentUnit = import("@nativescript/core/ui/styling/style-properties").LengthPercentUnit; // type DoubleTapGestureEventData = import("@nativescript/core/ui/gestures/gestures").DoubleTapGestureEventData; type DoubleTapGestureEventData = import("@nativescript/core/ui/gestures").GestureEventData; type PinchGestureEventData = import("@nativescript/core/ui/gestures").PinchGestureEventData; type PanGestureEventData = import("@nativescript/core/ui/gestures").PanGestureEventData; type SwipeGestureEventData = import("@nativescript/core/ui/gestures").SwipeGestureEventData; type RotationGestureEventData = import("@nativescript/core/ui/gestures").RotationGestureEventData; type GestureEventData = import("@nativescript/core/ui/gestures").GestureEventData; type TouchGestureEventData = import("@nativescript/core/ui/gestures").TouchGestureEventData; type EventData = import("@nativescript/core/data/observable").EventData; type ShownModallyData = import("@nativescript/core/ui/core/view").ShownModallyData; type ViewCommon = import("@nativescript/core/ui/core/view/view-common").ViewCommon; type DOMNode = import("@nativescript/core/debugger/dom-node").DOMNode; type ViewBase = import("@nativescript/core/ui/core/view-base").ViewBase; type Page = import("@nativescript/core/ui/page").Page; type Style = import("@nativescript/core/ui/styling/style").Style; type ActionBar = import("@nativescript/core/ui/action-bar").ActionBar; type IOSActionItemSettings = import("@nativescript/core/ui/action-bar").IOSActionItemSettings; type AndroidActionItemSettings = import("@nativescript/core/ui/action-bar").AndroidActionItemSettings; type TabContentItem = import("@nativescript/core/ui/tab-navigation-base/tab-content-item").TabContentItem; type TabStrip = import("@nativescript/core/ui/tab-navigation-base/tab-strip").TabStrip; type SelectedIndexChangedEventData = import("@nativescript/core/ui/bottom-navigation").SelectedIndexChangedEventData; type TabNavigationBaseSelectedIndexChangedEventData = import("@nativescript/core/ui/tab-navigation-base/tab-navigation-base").SelectedIndexChangedEventData; type FormattedString = import("@nativescript/core/ui/text-base/formatted-string").FormattedString; type BackstackEntry = import("@nativescript/core/ui/frame").BackstackEntry; type NavigationEntry = import("@nativescript/core/ui/frame").NavigationEntry; type NavigationTransition = import("@nativescript/core/ui/frame").NavigationTransition; type AndroidFrame = import("@nativescript/core/ui/frame").AndroidFrame; type iOSFrame = import("@nativescript/core/ui/frame").iOSFrame; type ImageSource = import("@nativescript/core/image-source").ImageSource; type ItemsSource = import("@nativescript/core/ui/list-picker/list-picker-common").ItemsSource; type ListViewItemsSource = import("@nativescript/core/ui/list-view").ItemsSource; type Template = import("@nativescript/core/ui/core/view").Template; type KeyedTemplate = import("@nativescript/core/ui/core/view").KeyedTemplate; type ItemEventData = import("@nativescript/core/ui/list-view").ItemEventData; type Frame = import("@nativescript/core/ui/frame").Frame; type NavigatedData = import("@nativescript/core/ui/page").NavigatedData; type CreateViewEventData = import("@nativescript/core/ui/placeholder").CreateViewEventData; type ScrollEventData = import("@nativescript/core/ui/scroll-view").ScrollEventData; type SegmentedBarItem = import("@nativescript/core/ui/segmented-bar").SegmentedBarItem; type SegmentedBarSelectedIndexChangedEventData = import("@nativescript/core/ui/segmented-bar").SelectedIndexChangedEventData; type TabViewItem = import("@nativescript/core/ui/tab-view").TabViewItem; type TabViewSelectedIndexChangedEventData = import("@nativescript/core/ui/tab-view").SelectedIndexChangedEventData; type LoadEventData = import("@nativescript/core/ui/web-view").LoadEventData; type TabStripItem = import("@nativescript/core/ui/tab-navigation-base/tab-strip-item").TabStripItem; type TabStripItemEventData = import("@nativescript/core/ui/tab-navigation-base/tab-strip").TabStripItemEventData; type Label = import("@nativescript/core/ui/label").Label; type Image = import("@nativescript/core/ui/image").Image; type Span = import("@nativescript/core/ui/text-base/span").Span; type ObservableArray<Span> = import("@nativescript/core/data/observable-array").ObservableArray<Span>; // ui/action-bar/action-bar.d.ts export type ActionBarAttributes = ViewAttributes & { actionItems?: ActionItems; android?: AndroidActionBarSettings; androidContentInset?: string | number | LengthDipUnit | LengthPxUnit; androidContentInsetLeft?: string | number | "auto" | LengthDipUnit | LengthPxUnit; androidContentInsetRight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; effectiveContentInsetLeft?: number; effectiveContentInsetRight?: number; flat?: string | false | true; ios?: any; iosIconRenderingMode?: "automatic" | "alwaysOriginal" | "alwaysTemplate"; navigationButton?: NavigationButton; onFlatChange?: (args: PropertyChangeData) => void; onIosIconRenderingModeChange?: (args: PropertyChangeData) => void; onTitleChange?: (args: PropertyChangeData) => void; title?: string; titleView?: View; }; // ui/core/view/view.d.ts export type ViewAttributes = ViewBaseAttributes & { android?: any; androidDynamicElevationOffset?: string | number; androidElevation?: string | number; automationText?: string; background?: string; backgroundColor?: string | Color; backgroundImage?: string | LinearGradient; backgroundPosition?: string; backgroundRepeat?: "repeat" | "repeat-x" | "repeat-y" | "no-repeat"; backgroundSize?: string; bindingContext?: any; borderBottomColor?: string | Color; borderBottomLeftRadius?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderBottomRightRadius?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderBottomWidth?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderColor?: string | Color; borderLeftColor?: string | Color; borderLeftWidth?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderRadius?: string | number | LengthDipUnit | LengthPxUnit; borderRightColor?: string | Color; borderRightWidth?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderTopColor?: string | Color; borderTopLeftRadius?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderTopRightRadius?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderTopWidth?: string | number | "auto" | LengthDipUnit | LengthPxUnit; borderWidth?: string | number | LengthDipUnit | LengthPxUnit; color?: string | Color; column?: string | number; columnSpan?: string | number; css?: string; cssClasses?: Set<string>; cssPseudoClasses?: Set<string>; cssType?: string; dock?: "left" | "top" | "right" | "bottom"; height?: string | number | "auto" | LengthDipUnit | LengthPxUnit | LengthPercentUnit; horizontalAlignment?: "left" | "right" | "center" | "stretch"; ios?: any; iosOverflowSafeArea?: false | true; iosOverflowSafeAreaEnabled?: false | true; isEnabled?: false | true; isLayoutRequired?: false | true; isLayoutValid?: false | true; isUserInteractionEnabled?: false | true; left?: string | number | "auto" | LengthDipUnit | LengthPxUnit; margin?: string | number | LengthDipUnit | LengthPxUnit | LengthPercentUnit; marginBottom?: string | number | "auto" | LengthDipUnit | LengthPxUnit | LengthPercentUnit; marginLeft?: string | number | "auto" | LengthDipUnit | LengthPxUnit | LengthPercentUnit; marginRight?: string | number | "auto" | LengthDipUnit | LengthPxUnit | LengthPercentUnit; marginTop?: string | number | "auto" | LengthDipUnit | LengthPxUnit | LengthPercentUnit; minHeight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; minWidth?: string | number | "auto" | LengthDipUnit | LengthPxUnit; modal?: View; onAndroidBackPressed?: (args: EventData) => void; onColumnChange?: (args: PropertyChangeData) => void; onColumnSpanChange?: (args: PropertyChangeData) => void; onDockChange?: (args: PropertyChangeData) => void; onDoubleTap?: (arg: DoubleTapGestureEventData) => any; onLeftChange?: (args: PropertyChangeData) => void; onLoaded?: (args: EventData) => void; onLongPress?: (arg: GestureEventData) => any; onPan?: (arg: PanGestureEventData) => any; onPinch?: (arg: PinchGestureEventData) => any; onRotation?: (arg: RotationGestureEventData) => any; onRowChange?: (args: PropertyChangeData) => void; onRowSpanChange?: (args: PropertyChangeData) => void; onShowingModally?: (args: ShownModallyData) => void; onShownModally?: (args: ShownModallyData) => void; /** Added manually. */ onLayoutChanged?: (args: EventData) => void; onSwipe?: (arg: SwipeGestureEventData) => any; onTap?: (arg: DoubleTapGestureEventData) => any; onTopChange?: (args: PropertyChangeData) => void; onTouch?: (arg: TouchGestureEventData) => any; onUnloaded?: (args: EventData) => void; opacity?: string | number; originX?: number; originY?: number; perspective?: string | number; rotate?: string | number; rotateX?: string | number; rotateY?: string | number; row?: string | number; rowSpan?: string | number; scaleX?: string | number; scaleY?: string | number; /** TODO: add RNS-synthesised "style" property. */ textTransform?: "none" | "initial" | "capitalize" | "uppercase" | "lowercase"; top?: string | number | "auto" | LengthDipUnit | LengthPxUnit; translateX?: string | number; translateY?: string | number; verticalAlignment?: "top" | "bottom" | "stretch" | "middle"; visibility?: "visible" | "hidden" | "collapse"; width?: string | number | "auto" | LengthDipUnit | LengthPxUnit | LengthPercentUnit; }; // ui/core/view-base/view-base.d.ts export type ViewBaseAttributes = ObservableAttributes & { alignSelf?: "auto" | "flex-start" | "flex-end" | "center" | "baseline" | "stretch"; android?: any; automationText?: string; bindingContext?: string | any; className?: string; col?: number; colSpan?: number; column?: number; columnSpan?: number; cssClasses?: Set<string>; cssPseudoClasses?: Set<string>; dock?: "left" | "top" | "right" | "bottom"; domNode?: DOMNode; effectiveBorderBottomWidth?: number; effectiveBorderLeftWidth?: number; effectiveBorderRightWidth?: number; effectiveBorderTopWidth?: number; effectiveHeight?: number; effectiveLeft?: number; effectiveMarginBottom?: number; effectiveMarginLeft?: number; effectiveMarginRight?: number; effectiveMarginTop?: number; effectiveMinHeight?: number; effectiveMinWidth?: number; effectivePaddingBottom?: number; effectivePaddingLeft?: number; effectivePaddingRight?: number; effectivePaddingTop?: number; effectiveTop?: number; effectiveWidth?: number; flexGrow?: number; flexShrink?: number; flexWrapBefore?: false | true; id?: string; ios?: any; iosOverflowSafeArea?: string | false | true; iosOverflowSafeAreaEnabled?: string | false | true; isCollapsed?: false | true; isEnabled?: string | false | true; isLoaded?: false | true; isUserInteractionEnabled?: string | false | true; left?: number | "auto" | LengthDipUnit | LengthPxUnit; nativeView?: any; onAutomationTextChange?: (args: PropertyChangeData) => void; onBindingContextChange?: (args: PropertyChangeData) => void; onClassNameChange?: (args: PropertyChangeData) => void; onIdChange?: (args: PropertyChangeData) => void; onIosOverflowSafeAreaChange?: (args: PropertyChangeData) => void; onIosOverflowSafeAreaEnabledChange?: (args: PropertyChangeData) => void; onIsEnabledChange?: (args: PropertyChangeData) => void; onIsUserInteractionEnabledChange?: (args: PropertyChangeData) => void; onOriginXChange?: (args: PropertyChangeData) => void; onOriginYChange?: (args: PropertyChangeData) => void; order?: number; originX?: string | number; originY?: string | number; page?: Page; parent?: ViewBase; parentNode?: ViewBase; recycleNativeView?: "always" | "never" | "auto"; row?: number; rowSpan?: number; top?: number | "auto" | LengthDipUnit | LengthPxUnit; typeName?: string; viewController?: any; }; // data/observable/observable.d.ts export type ObservableAttributes = { onPropertyChange?: (data: EventData) => void; }; // ui/action-bar/action-bar.d.ts export type ActionItemAttributes = ViewBaseAttributes & { actionBar?: ActionBar; actionView?: View; android?: AndroidActionItemSettings; icon?: string; ios?: IOSActionItemSettings; onIconChange?: (args: PropertyChangeData) => void; onTap?: (args: EventData) => void; onTextChange?: (args: PropertyChangeData) => void; onVisibilityChange?: (args: PropertyChangeData) => void; text?: string; visibility?: string; }; // ui/action-bar/action-bar.d.ts export type NavigationButtonAttributes = ActionItemAttributes & { }; // ui/activity-indicator/activity-indicator.d.ts export type ActivityIndicatorAttributes = ViewAttributes & { android?: any; busy?: string | false | true; ios?: any; onBusyChange?: (args: PropertyChangeData) => void; }; // ui/border/border.d.ts export type BorderAttributes = ContentViewAttributes & { cornerRadius?: number; }; // ui/content-view/content-view.d.ts export type ContentViewAttributes = ViewAttributes & { content?: View; layoutView?: View; }; // ui/bottom-navigation/bottom-navigation.d.ts export type BottomNavigationAttributes = TabNavigationBaseAttributes & { android?: any; ios?: any; items?: TabContentItem[]; onSelectedIndexChanged?: (args: SelectedIndexChangedEventData) => void; selectedIndex?: number; tabStrip?: TabStrip; }; // ui/tab-navigation-base/tab-navigation-base/tab-navigation-base.d.ts export type TabNavigationBaseAttributes = ViewAttributes & { android?: any; ios?: any; items?: string | TabContentItem[]; onItemsChange?: (args: PropertyChangeData) => void; onSelectedIndexChange?: (args: PropertyChangeData) => void; onSelectedIndexChanged?: (args: TabNavigationBaseSelectedIndexChangedEventData) => void; onTabStripChange?: (args: PropertyChangeData) => void; selectedIndex?: string | number; tabStrip?: string | TabStrip; }; // ui/button/button.d.ts export type ButtonAttributes = TextBaseAttributes & { android?: any; ios?: any; onTap?: (args: EventData) => void; textWrap?: false | true; }; // ui/text-base/text-base.d.ts export type TextBaseAttributes = ViewAttributes & { fontFamily?: string; fontSize?: string | number; fontStyle?: "normal" | "italic"; fontWeight?: "normal" | "100" | "200" | "300" | "400" | "500" | "600" | "bold" | "700" | "800" | "900"; formattedText?: string | FormattedString; letterSpacing?: string | number; lineHeight?: string | number; onFormattedTextChange?: (args: PropertyChangeData) => void; onTextChange?: (args: PropertyChangeData) => void; padding?: string | number | LengthDipUnit | LengthPxUnit; paddingBottom?: string | number | "auto" | LengthDipUnit | LengthPxUnit; paddingLeft?: string | number | "auto" | LengthDipUnit | LengthPxUnit; paddingRight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; paddingTop?: string | number | "auto" | LengthDipUnit | LengthPxUnit; text?: string; textAlignment?: "left" | "right" | "center" | "initial"; textDecoration?: "none" | "underline" | "line-through" | "underline line-through"; textTransform?: "none" | "initial" | "capitalize" | "uppercase" | "lowercase"; whiteSpace?: "initial" | "normal" | "nowrap"; }; // ui/date-picker/date-picker.d.ts export type DatePickerAttributes = ViewAttributes & { android?: any; date?: string | Date; day?: string | number; ios?: any; maxDate?: string | Date; minDate?: string | Date; month?: string | number; onDateChange?: (args: PropertyChangeData) => void; onDayChange?: (args: PropertyChangeData) => void; onMaxDateChange?: (args: PropertyChangeData) => void; onMinDateChange?: (args: PropertyChangeData) => void; onMonthChange?: (args: PropertyChangeData) => void; onYearChange?: (args: PropertyChangeData) => void; year?: string | number; }; // ui/frame/frame.d.ts export type FrameAttributes = ViewAttributes & { actionBarVisibility?: "always" | "never" | "auto"; android?: AndroidFrame; animated?: false | true; backStack?: BackstackEntry[]; currentEntry?: NavigationEntry; currentPage?: Page; defaultPage?: string; ios?: iOSFrame; navigationBarHeight?: number; onActionBarVisibilityChange?: (args: PropertyChangeData) => void; onDefaultPageChange?: (args: PropertyChangeData) => void; transition?: NavigationTransition; }; // ui/html-view/html-view.d.ts export type HtmlViewAttributes = ViewAttributes & { android?: any; html?: string; ios?: any; onHtmlChange?: (args: PropertyChangeData) => void; }; // ui/image/image.d.ts export type ImageAttributes = ViewAttributes & { android?: any; decodeHeight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; decodeWidth?: string | number | "auto" | LengthDipUnit | LengthPxUnit; imageSource?: string | ImageSource; ios?: any; isLoading?: string | false | true; loadMode?: "sync" | "async"; onDecodeHeightChange?: (args: PropertyChangeData) => void; onDecodeWidthChange?: (args: PropertyChangeData) => void; onImageSourceChange?: (args: PropertyChangeData) => void; onIsLoadingChange?: (args: PropertyChangeData) => void; onLoadModeChange?: (args: PropertyChangeData) => void; onSrcChange?: (args: PropertyChangeData) => void; onStretchChange?: (args: PropertyChangeData) => void; src?: string | any; stretch?: "none" | "aspectFill" | "aspectFit" | "fill"; tintColor?: string | Color; }; // ui/label/label.d.ts export type LabelAttributes = TextBaseAttributes & { android?: any; ios?: any; textWrap?: string | false | true; }; // ui/list-picker/list-picker.d.ts export type ListPickerAttributes = ViewAttributes & { android?: any; ios?: any; isItemsSource?: false | true; items?: string | any[] | ItemsSource; onItemsChange?: (args: PropertyChangeData) => void; onSelectedIndexChange?: (args: PropertyChangeData) => void; onSelectedValueChange?: (args: PropertyChangeData) => void; onTextFieldChange?: (args: PropertyChangeData) => void; onValueFieldChange?: (args: PropertyChangeData) => void; selectedIndex?: string | number; selectedValue?: string; textField?: string; valueField?: string; }; // ui/list-view/list-view.d.ts export type ListViewAttributes = ViewAttributes & { android?: any; ios?: any; iosEstimatedRowHeight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; itemIdGenerator?: (item: any, index: number, items: any) => number; itemTemplate?: string | Template; itemTemplateSelector?: string | ((item: any, index: number, items: any) => string); itemTemplates?: string | KeyedTemplate[]; items?: string | any[] | ListViewItemsSource; onIosEstimatedRowHeightChange?: (args: PropertyChangeData) => void; onItemLoading?: (args: ItemEventData) => void; onItemTap?: (args: ItemEventData) => void; onItemTemplateChange?: (args: PropertyChangeData) => void; onItemTemplatesChange?: (args: PropertyChangeData) => void; onItemsChange?: (args: PropertyChangeData) => void; onLoadMoreItems?: (args: EventData) => void; onRowHeightChange?: (args: PropertyChangeData) => void; rowHeight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; separatorColor?: string | Color; }; // ui/page/page.d.ts export type PageAttributes = ContentViewAttributes & { actionBar?: ActionBar; actionBarHidden?: string | false | true; androidStatusBarBackground?: string | Color; backgroundSpanUnderStatusBar?: string | false | true; enableSwipeBackNavigation?: string | false | true; frame?: Frame; hasActionBar?: false | true; navigationContext?: any; onActionBarHiddenChange?: (args: PropertyChangeData) => void; onBackgroundSpanUnderStatusBarChange?: (args: PropertyChangeData) => void; onEnableSwipeBackNavigationChange?: (args: PropertyChangeData) => void; onNavigatedFrom?: (args: NavigatedData) => void; onNavigatedTo?: (args: NavigatedData) => void; onNavigatingFrom?: (args: NavigatedData) => void; onNavigatingTo?: (args: NavigatedData) => void; page?: Page; statusBarStyle?: "light" | "dark"; }; // ui/placeholder/placeholder.d.ts export type PlaceholderAttributes = ViewAttributes & { onCreatingView?: (args: CreateViewEventData) => void; }; // ui/progress/progress.d.ts export type ProgressAttributes = ViewAttributes & { android?: any; ios?: any; maxValue?: string | number; onMaxValueChange?: (args: PropertyChangeData) => void; onValueChange?: (args: PropertyChangeData) => void; value?: string | number; }; // ui/proxy-view-container/proxy-view-container.d.ts export type ProxyViewContainerAttributes = LayoutBaseAttributes & { onProxyChange?: (args: PropertyChangeData) => void; proxy?: string; }; // ui/layouts/layout-base.d.ts export type LayoutBaseAttributes = CustomLayoutViewAttributes & { clipToBounds?: string | false | true; isPassThroughParentEnabled?: string | false | true; onClipToBoundsChange?: (args: PropertyChangeData) => void; onIsPassThroughParentEnabledChange?: (args: PropertyChangeData) => void; padding?: string | number | LengthDipUnit | LengthPxUnit; paddingBottom?: string | number | "auto" | LengthDipUnit | LengthPxUnit; paddingLeft?: string | number | "auto" | LengthDipUnit | LengthPxUnit; paddingRight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; paddingTop?: string | number | "auto" | LengthDipUnit | LengthPxUnit; }; // ui/core/view/view.d.ts export type CustomLayoutViewAttributes = ContainerViewAttributes & { }; // ui/core/view/view.d.ts export type ContainerViewAttributes = ViewAttributes & { iosOverflowSafeArea?: false | true; }; // ui/scroll-view/scroll-view.d.ts export type ScrollViewAttributes = ContentViewAttributes & { horizontalOffset?: number; isScrollEnabled?: string | false | true; onIsScrollEnabledChange?: (args: PropertyChangeData) => void; onOrientationChange?: (args: PropertyChangeData) => void; onScroll?: (args: ScrollEventData) => void; onScrollBarIndicatorVisibleChange?: (args: PropertyChangeData) => void; orientation?: "horizontal" | "vertical"; scrollBarIndicatorVisible?: string | false | true; scrollableHeight?: number; scrollableWidth?: number; verticalOffset?: number; }; // ui/search-bar/search-bar.d.ts export type SearchBarAttributes = ViewAttributes & { android?: any; hint?: string; ios?: any; onClose?: (args: EventData) => void; onHintChange?: (args: PropertyChangeData) => void; onSubmit?: (args: EventData) => void; onTextChange?: (args: PropertyChangeData) => void; onTextFieldBackgroundColorChange?: (args: PropertyChangeData) => void; onTextFieldHintColorChange?: (args: PropertyChangeData) => void; text?: string; textFieldBackgroundColor?: string | Color; textFieldHintColor?: string | Color; }; // ui/segmented-bar/segmented-bar.d.ts export type SegmentedBarItemAttributes = ViewBaseAttributes & { title?: string; }; // ui/segmented-bar/segmented-bar.d.ts export type SegmentedBarAttributes = ViewAttributes & { items?: string | SegmentedBarItem[]; onItemsChange?: (args: PropertyChangeData) => void; onSelectedIndexChange?: (args: PropertyChangeData) => void; onSelectedIndexChanged?: (args: SegmentedBarSelectedIndexChangedEventData) => void; selectedBackgroundColor?: string | Color; selectedIndex?: string | number; }; // ui/slider/slider.d.ts export type SliderAttributes = ViewAttributes & { android?: any; ios?: any; maxValue?: string | number; minValue?: string | number; onMaxValueChange?: (args: PropertyChangeData) => void; onMinValueChange?: (args: PropertyChangeData) => void; onValueChange?: (args: PropertyChangeData) => void; value?: string | number; }; // ui/switch/switch.d.ts export type SwitchAttributes = ViewAttributes & { android?: any; checked?: string | false | true; ios?: any; offBackgroundColor?: string | Color; onCheckedChange?: (args: PropertyChangeData) => void; onOffBackgroundColorChange?: (args: PropertyChangeData) => void; }; // ui/tab-view/tab-view.d.ts export type TabViewItemAttributes = ViewBaseAttributes & { canBeLoaded?: false | true; iconSource?: string; textTransform?: "none" | "initial" | "capitalize" | "uppercase" | "lowercase"; title?: string; view?: View; }; // ui/tab-view/tab-view.d.ts export type TabViewAttributes = ViewAttributes & { android?: any; androidOffscreenTabLimit?: string | number; androidSelectedTabHighlightColor?: string | Color; androidSwipeEnabled?: string | false | true; androidTabsPosition?: "top" | "bottom"; ios?: any; iosIconRenderingMode?: "automatic" | "alwaysOriginal" | "alwaysTemplate"; items?: string | TabViewItem[]; onAndroidOffscreenTabLimitChange?: (args: PropertyChangeData) => void; onAndroidSwipeEnabledChange?: (args: PropertyChangeData) => void; onAndroidTabsPositionChange?: (args: PropertyChangeData) => void; onIosIconRenderingModeChange?: (args: PropertyChangeData) => void; onItemsChange?: (args: PropertyChangeData) => void; onSelectedIndexChange?: (args: PropertyChangeData) => void; onSelectedIndexChanged?: (args: TabViewSelectedIndexChangedEventData) => void; selectedIndex?: string | number; selectedTabTextColor?: string | Color; tabBackgroundColor?: string | Color; tabTextColor?: string | Color; tabTextFontSize?: string | number; }; // ui/tabs/tabs.d.ts export type TabsAttributes = TabNavigationBaseAttributes & { android?: any; iOSTabBarItemsAlignment?: "center" | "leading" | "justified" | "centerSelected"; ios?: any; items?: TabContentItem[]; offscreenTabLimit?: string | number; onIOsTabBarItemsAlignmentChange?: (args: PropertyChangeData) => void; onOffscreenTabLimitChange?: (args: PropertyChangeData) => void; onSelectedIndexChanged?: (args: TabNavigationBaseSelectedIndexChangedEventData) => void; onSwipeEnabledChange?: (args: PropertyChangeData) => void; onTabsPositionChange?: (args: PropertyChangeData) => void; selectedIndex?: number; swipeEnabled?: string | false | true; tabStrip?: TabStrip; tabsPosition?: "top" | "bottom"; }; // ui/text-field/text-field.d.ts export type TextFieldAttributes = EditableTextBaseAttributes & { android?: any; ios?: any; onSecureChange?: (args: PropertyChangeData) => void; secure?: string | false | true; }; // ui/editable-text-base/editable-text-base.d.ts export type EditableTextBaseAttributes = TextBaseAttributes & { autocapitalizationType?: "none" | "words" | "sentences" | "allcharacters"; autocorrect?: string | false | true; editable?: string | false | true; hint?: string; keyboardType?: "number" | "datetime" | "phone" | "url" | "email" | "integer"; maxLength?: string | number; maxLines?: string | number; onAutocapitalizationTypeChange?: (args: PropertyChangeData) => void; onAutocorrectChange?: (args: PropertyChangeData) => void; onEditableChange?: (args: PropertyChangeData) => void; onHintChange?: (args: PropertyChangeData) => void; onKeyboardTypeChange?: (args: PropertyChangeData) => void; onMaxLengthChange?: (args: PropertyChangeData) => void; onMaxLinesChange?: (args: PropertyChangeData) => void; onReturnKeyTypeChange?: (args: PropertyChangeData) => void; onUpdateTextTriggerChange?: (args: PropertyChangeData) => void; returnKeyType?: "done" | "next" | "go" | "search" | "send"; updateTextTrigger?: "focusLost" | "textChanged"; }; // ui/text-view/text-view.d.ts export type TextViewAttributes = EditableTextBaseAttributes & { android?: any; ios?: any; maxLines?: number; }; // ui/time-picker/time-picker.d.ts export type TimePickerAttributes = ViewAttributes & { android?: any; hour?: string | number; ios?: any; maxHour?: string | number; maxMinute?: string | number; minHour?: string | number; minMinute?: string | number; minute?: string | number; minuteInterval?: string | number; onHourChange?: (args: PropertyChangeData) => void; onMaxHourChange?: (args: PropertyChangeData) => void; onMaxMinuteChange?: (args: PropertyChangeData) => void; onMinHourChange?: (args: PropertyChangeData) => void; onMinMinuteChange?: (args: PropertyChangeData) => void; onMinuteChange?: (args: PropertyChangeData) => void; onMinuteIntervalChange?: (args: PropertyChangeData) => void; onTimeChange?: (args: PropertyChangeData) => void; time?: string | Date; }; // ui/web-view/web-view.d.ts export type WebViewAttributes = ViewAttributes & { android?: any; canGoBack?: false | true; canGoForward?: false | true; ios?: any; /* AddedManually */ onSrcChange?: (args: PropertyChangeData) => void; onLoadFinished?: (args: LoadEventData) => void; onLoadStarted?: (args: LoadEventData) => void; src?: string; }; // ui/layouts/absolute-layout/absolute-layout.d.ts export type AbsoluteLayoutAttributes = LayoutBaseAttributes & { }; // ui/layouts/dock-layout/dock-layout.d.ts export type DockLayoutAttributes = LayoutBaseAttributes & { onStretchLastChildChange?: (args: PropertyChangeData) => void; stretchLastChild?: string | false | true; }; // ui/layouts/flexbox-layout/flexbox-layout.d.ts export type FlexboxLayoutAttributes = LayoutBaseAttributes & { alignContent?: "flex-start" | "flex-end" | "center" | "stretch" | "space-between" | "space-around"; alignItems?: "flex-start" | "flex-end" | "center" | "baseline" | "stretch"; flexDirection?: "row" | "column" | "row-reverse" | "column-reverse"; flexWrap?: "nowrap" | "wrap" | "wrap-reverse"; justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; }; // ui/layouts/grid-layout/grid-layout.d.ts export type GridLayoutAttributes = LayoutBaseAttributes & { columns?: string; rows?: string; }; // ui/layouts/stack-layout/stack-layout.d.ts export type StackLayoutAttributes = LayoutBaseAttributes & { onOrientationChange?: (args: PropertyChangeData) => void; orientation?: "horizontal" | "vertical"; }; // ui/layouts/wrap-layout/wrap-layout.d.ts export type WrapLayoutAttributes = LayoutBaseAttributes & { effectiveItemHeight?: number; effectiveItemWidth?: number; itemHeight?: string | number | "auto" | LengthDipUnit | LengthPxUnit; itemWidth?: string | number | "auto" | LengthDipUnit | LengthPxUnit; onItemHeightChange?: (args: PropertyChangeData) => void; onItemWidthChange?: (args: PropertyChangeData) => void; onOrientationChange?: (args: PropertyChangeData) => void; orientation?: "horizontal" | "vertical"; }; // ui/tab-navigation-base/tab-content-item/tab-content-item.d.ts export type TabContentItemAttributes = ContentViewAttributes & { canBeLoaded?: false | true; }; // ui/tab-navigation-base/tab-strip/tab-strip.d.ts export type TabStripAttributes = ViewAttributes & { highlightColor?: string | Color; iosIconRenderingMode?: "automatic" | "alwaysOriginal" | "alwaysTemplate"; isIconSizeFixed?: string | false | true; items?: string | TabStripItem[]; onHighlightColorChange?: (args: PropertyChangeData) => void; onIosIconRenderingModeChange?: (args: PropertyChangeData) => void; onIsIconSizeFixedChange?: (args: PropertyChangeData) => void; onItemTap?: (args: TabStripItemEventData) => void; onItemsChange?: (args: PropertyChangeData) => void; onSelectedItemColorChange?: (args: PropertyChangeData) => void; onUnSelectedItemColorChange?: (args: PropertyChangeData) => void; selectedItemColor?: string | Color; unSelectedItemColor?: string | Color; }; // ui/tab-navigation-base/tab-strip-item/tab-strip-item.d.ts export type TabStripItemAttributes = ViewAttributes & { iconClass?: string; iconSource?: string; image?: Image; label?: Label; onTap?: (args: EventData) => void; title?: string; }; // ui/text-base/formatted-string.ts export type FormattedStringAttributes = ViewBaseAttributes & { backgroundColor?: string | Color; color?: string | Color; fontFamily?: string; fontSize?: string | number; fontStyle?: "normal" | "italic"; fontWeight?: "normal" | "100" | "200" | "300" | "400" | "500" | "600" | "bold" | "700" | "800" | "900"; spans?: ObservableArray<Span>; textDecoration?: "none" | "underline" | "line-through" | "underline line-through"; }; // ui/text-base/span.ts export type SpanAttributes = ViewBaseAttributes & { backgroundColor?: string | Color; color?: string | Color; fontFamily?: string; fontSize?: string | number; fontStyle?: "normal" | "italic"; fontWeight?: "normal" | "100" | "200" | "300" | "400" | "500" | "600" | "bold" | "700" | "800" | "900"; text?: string; textDecoration?: "none" | "underline" | "line-through" | "underline line-through"; };
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { BasicShapeModel } from '../../../src/diagram/objects/node-model'; import { Node } from '../../../src/diagram/objects/node'; import { NodeModel } from '../../../src/diagram/objects/node-model'; import { IDataLoadedEventArgs } from '../../../src/diagram/objects/interface/IElement'; import { ConnectorModel, } from '../../../src/diagram/objects/connector-model'; import { Segments } from '../../../src/diagram/enum/enum'; import { DataManager, Query } from '@syncfusion/ej2-data'; import { DataBinding } from '../../../src/diagram/index'; import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec'; Diagram.Inject(DataBinding); /** * Data Source Spec */ describe('Diagram Control', () => { describe('Data Binding', () => { let diagram: Diagram; let ele: HTMLElement; 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 data: DataManager = new DataManager(); diagram = new Diagram({ width: 1000, height: 1000, dataSourceSettings: { dataSource: data }, layout: { type: 'HierarchicalTree' } }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking empty data', (done: Function) => { expect(diagram.nodes.length === 0 && diagram.connectors.length === 0).toBe(true); done(); }); }); describe('Data Binding', () => { let diagram: Diagram; let ele: HTMLElement; 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 data: object[] = [{ 'Name': 'Director' }, { 'Name': 'Manager', 'ReportingPerson': 'Director' }, { 'Name': 'TeamLead', 'ReportingPerson': 'Director' }, { 'Name': 'Software Developer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Software Developer', 'ReportingPerson': 'Manager' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'Manager' }]; let items: DataManager = new DataManager(data as JSON[]); let i: number = 1; diagram = new Diagram({ width: 1000, height: 1000, dataSourceSettings: { id: 'Name', parentId: 'ReportingPerson', dataSource: items, doBinding: (node: NodeModel, dataSource: object, diagram: Diagram) => { node.annotations = [{ content: dataSource['Name'] }]; } }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking local data binding', (done: Function) => { expect(diagram.nodes.length === 7 && diagram.connectors.length === 6).toBe(true); expect((diagram.nodes[0] as NodeModel).annotations.length).toBe(1); done(); }); }); describe('Data Binding using string function', () => { let diagram: Diagram; let ele: HTMLElement; 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: 'diagrammo' }); document.body.appendChild(ele); let data: object[] = [{ 'Name': 'Director' }, { 'Name': 'Manager', 'ReportingPerson': 'Director' }, { 'Name': 'TeamLead', 'ReportingPerson': 'Director' }, { 'Name': 'Software Developer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Software Developer', 'ReportingPerson': 'Manager' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'Manager' }]; let items: DataManager = new DataManager(data as JSON[]); let i: number = 1; diagram = new Diagram({ width: 1000, height: 1000, dataSourceSettings: { id: 'Name', parentId: 'ReportingPerson', dataSource: items, doBinding: (node: NodeModel, dataSource: object, diagram: Diagram) => { node.annotations = [{ content: dataSource['Name'] }]; } }, getNodeDefaults: 'getNodeDefaults', getConnectorDefaults: 'getConnectorDefaults' }); diagram.appendTo('#diagrammo'); window['getNodeDefaults'] = function (node: Node): NodeModel { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; } window['getConnectorDefaults'] = function (obj: ConnectorModel, diagram: Diagram): ConnectorModel { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking local data binding', (done: Function) => { expect(diagram.nodes.length === 7 && diagram.connectors.length === 6).toBe(true); expect((diagram.nodes[0] as NodeModel).annotations.length).toBe(1); done(); }); }); describe('Data Binding', () => { let diagram: Diagram; let ele: HTMLElement; 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); const SERVICE_URI = 'https://mvc.syncfusion.com/Services/Northwnd.svc'; let items: DataManager = new DataManager({ url: SERVICE_URI }, new Query().from('Employees'). select('EmployeeID, ReportsTo, FirstName')); let i: number = 1; diagram = new Diagram({ width: 1500, height: 1500, dataSourceSettings: { id: 'EmployeeID', parentId: 'ReportsTo', dataSource: items }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking remote data binding', (done: Function) => { done(); diagram.dataLoaded = (args: IDataLoadedEventArgs) => { expect(diagram.nodes.length === 10 && diagram.connectors.length === 8).toBe(true); done(); }; }); }); describe('Data Binding ', () => { let diagram: Diagram; let ele: HTMLElement; 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 data: object[] = [{ 'Name': 'Customer Support', 'fillColor': '#0f688d' }, { 'Name': 'OEM Support', 'fillColor': '#0f688d' }, { 'Name': 'Customer Care', 'ReportingPerson': ['Customer Support', 'OEM Support'], 'fillColor': '#14ad85' }, { 'Name': 'Central Region', 'fillColor': '#0f688d' }, { 'Name': 'Eastern Region', 'fillColor': '#0f688d' }, { 'Name': 'ServiceCare', 'ReportingPerson': ['Central Region', 'Eastern Region'], 'fillColor': '#14ad85' }, { 'Name': 'National Channel Marketing', 'fillColor': '#0f688d' }, { 'Name': 'Retail Channel Marketing', 'fillColor': '#0f688d' }, { 'Name': 'Channel Marketing', 'ReportingPerson': ['National Channel Marketing', 'Retail Channel Marketing'], 'fillColor': '#14ad85' }, { 'Name': 'Northern Region', 'fillColor': '#0f688d' }, { 'Name': 'Western Region', 'fillColor': '#0f688d' }, { 'Name': 'Channel Field Sales', 'ReportingPerson': ['Northern Region', 'Western Region'], 'fillColor': '#14ad85' }, { 'Name': 'Customer', 'ReportingPerson': ['Customer Care', 'ServiceCare'], 'fillColor': '#0aa6ce' }, { 'Name': 'SalesMan', 'ReportingPerson': ['Channel Marketing', 'Channel Field Sales'], 'fillColor': '#0aa6ce' }, { 'Name': 'Adventure Work Cycle', 'ReportingPerson': ['Customer', 'SalesMan'], 'fillColor': '#f16f62' }, ]; let items: DataManager = new DataManager(data as JSON[], new Query().take(7)); let i: number = 1; diagram = new Diagram({ width: 3500, height: 3500, dataSourceSettings: { id: 'Name', parentId: 'ReportingPerson', dataSource: items }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking data source with multiple parents', (done: Function) => { let source: Node; let connector: ConnectorModel = diagram.connectors[0]; expect(diagram.nodes.length === 15 && diagram.connectors.length === 14).toBe(true); done(); }); }); describe('Data Binding', () => { let diagram: Diagram; let ele: HTMLElement; 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 data: object[] = [{ 'Name': 'Director' }, { 'Name': 'Manager', 'ReportingPerson': 'Director' }, { 'Name': 'Software Developer', 'ReportingPerson': ['Director', 'Manager'] }, ]; let items: DataManager = new DataManager(data as JSON[], new Query().take(4)); let i: number = 1; diagram = new Diagram({ width: 1000, height: 1000, dataSourceSettings: { id: 'Name', parentId: 'ReportingPerson', dataSource: items }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking cyclic data', (done: Function) => { expect(diagram.nodes.length === 3 && diagram.connectors.length === 3).toBe(true); done(); }); }); describe('Data Binding', () => { let diagram: Diagram; let ele: HTMLElement; 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 data: object[] = [ { 'Id': 'E1', 'Name': 'Maria Anders', 'Designation': 'Managing Director' }, { 'Id': 'E2', 'Name': 'Ana Trujillo', 'Designation': 'Project Manager', 'ReportingPerson': 'E1' }]; let items: DataManager = new DataManager(data as JSON[], new Query().take(2)); let i: number = 1; diagram = new Diagram({ width: 1000, height: 1000, dataSourceSettings: { id: 'Id', parentId: 'Designation', root: 'E2', dataSource: items }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking root node', (done: Function) => { expect(diagram.nodes.length === 1 && (diagram.nodes[0] as Node).inEdges.length === 0 && (diagram.nodes[0] as Node).outEdges.length === 0).toBe(true); done(); }); }); describe('Data Binding', () => { let diagram: Diagram; let ele: HTMLElement; 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 data1: object[] = [{ 'Name': 'Director' }, { 'Name': 'Manager', 'ReportingPerson': 'Director' }, { 'Name': 'TeamLead', 'ReportingPerson': 'Director' }, { 'Name': 'Software Developer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Software Developer', 'ReportingPerson': 'Manager' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'Manager' }]; let data:DataManager = new DataManager(data1 as JSON[], new Query().take(7)); let i: number = 1; diagram = new Diagram({ width: 1000, height: 1000, dataSourceSettings: { id: 'Name', dataSource: data, doBinding: (node: NodeModel, dataSource: object, diagram: Diagram) => { node.annotations = [{ content: dataSource['Name'] }]; } }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking binding without connections', (done: Function) => { expect(diagram.nodes.length == 7).toBe(true); expect((diagram.nodes[0] as NodeModel).annotations.length).toBe(1); done(); }); }); describe('Data Binding with string function', () => { let diagram: Diagram; let ele: HTMLElement; 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: 'diagramko' }); document.body.appendChild(ele); let data: object[] = [{ 'Name': 'Director' }, { 'Name': 'Manager', 'ReportingPerson': 'Director' }, { 'Name': 'TeamLead', 'ReportingPerson': 'Director' }, { 'Name': 'Software Developer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'TeamLead' }, { 'Name': 'Software Developer', 'ReportingPerson': 'Manager' }, { 'Name': 'Testing engineer', 'ReportingPerson': 'Manager' }]; let items: DataManager = new DataManager(data as JSON[]); let i: number = 1; diagram = new Diagram({ width: 1000, height: 1000, dataSourceSettings: { id: 'Name', dataSource: items, doBinding: 'doBinding' // doBinding: (node: NodeModel, dataSource: object, diagram: Diagram) => { // node.annotations = [{ content: dataSource['Name'] }]; // } }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.width = 100; obj.height = 50; obj.offsetX = i * 100; obj.offsetY = i * 100; obj.shape = { type: 'Basic', shape: 'Rectangle' } as BasicShapeModel; obj.style = { fill: 'transparent', strokeWidth: 2 }; i++; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagramko'); }); window['doBinding'] = function (node: NodeModel, dataSource: object, diagram: Diagram) { node.annotations = [{ content: dataSource['Name'] }]; } afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking binding without connections', (done: Function) => { expect(diagram.nodes.length == 7).toBe(true); expect((diagram.nodes[0] as NodeModel).annotations.length).toBe(1); 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 R from 'ramda'; import pMapSeries from 'p-map-series'; import { Scope } from '..'; import { Remotes } from '../../remotes'; import enrichContextFromGlobal from '../../hooks/utils/enrich-context-from-global'; import { BitId, BitIds } from '../../bit-id'; import VersionDependencies from '../version-dependencies'; import logger from '../../logger/logger'; import { RemoteScopeNotFound, PermissionDenied } from '../network/exceptions'; import { ComponentNotFound, DependencyNotFound } from '../exceptions'; import { Analytics } from '../../analytics/analytics'; import SourcesRepository, { ComponentDef } from '../repositories/sources'; import ComponentVersion from '../component-version'; import ComponentObjects from '../component-objects'; import GeneralError from '../../error/general-error'; import { getScopeRemotes } from '../scope-remotes'; import ConsumerComponent from '../../consumer/component'; import { splitBy } from '../../utils'; import { ModelComponent, Version } from '../models'; import ShowDoctorError from '../../error/show-doctor-error'; const removeNils = R.reject(R.isNil); export default class ScopeComponentsImporter { scope: Scope; sources: SourcesRepository; constructor(scope: Scope) { if (!scope) throw new Error('unable to instantiate ScopeComponentsImporter without Scope'); this.scope = scope; this.sources = scope.sources; } static getInstance(scope: Scope): ScopeComponentsImporter { return new ScopeComponentsImporter(scope); } /** * 1. Local objects, fetch from local. (done by this.sources.getMany method) * 2. Fetch flattened dependencies (done by toVersionDependencies method). If they're not locally, fetch from remote * and save them locally. * 3. External objects, fetch from a remote and save locally. (done by this.getExternalOnes method). */ async importMany(ids: BitIds, cache = true, persist = true): Promise<VersionDependencies[]> { logger.debugAndAddBreadCrumb('ScopeComponentsImporter', 'importMany: {ids}', { ids: ids.toString() }); const idsWithoutNils = removeNils(ids); if (R.isEmpty(idsWithoutNils)) return Promise.resolve([]); const [locals, externals] = R.partition(id => id.isLocal(this.scope.name), idsWithoutNils); const localDefs = await this.sources.getMany(locals); const versionDeps = await pMapSeries(localDefs, def => { if (!def.component) throw new ComponentNotFound(def.id.toString()); return this.componentToVersionDependencies(def.component, def.id); }); logger.debugAndAddBreadCrumb( 'ScopeComponentsImporter', 'importMany: successfully fetched local components and their dependencies. Going to fetch externals' ); const remotes = await getScopeRemotes(this.scope); const externalDeps = await this._getExternalMany(externals, remotes, cache, persist); return versionDeps.concat(externalDeps); } async importManyWithoutDependencies(ids: BitIds, cache = true): Promise<ComponentVersion[]> { if (!ids.length) return []; logger.debug(`importManyWithoutDependencies. Ids: ${ids.join(', ')}, cache: ${cache.toString()}`); Analytics.addBreadCrumb('importManyWithoutDependencies', `Ids: ${Analytics.hashData(ids)}`); const idsWithoutNils = removeNils(ids); if (R.isEmpty(idsWithoutNils)) return Promise.resolve([]); const [externals, locals] = splitBy(idsWithoutNils, id => id.isLocal(this.scope.name)); const localDefs: ComponentDef[] = await this.sources.getMany(locals); const componentVersionArr = await Promise.all( localDefs.map(def => { if (!def.component) throw new ComponentNotFound(def.id.toString()); // $FlowFixMe it must have a version // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return def.component.toComponentVersion(def.id.version); }) ); const remotes = await getScopeRemotes(this.scope); const externalDeps = await this._getExternalManyWithoutDependencies(externals, remotes, cache); return componentVersionArr.concat(externalDeps); } /** * todo: improve performance by finding all versions needed and fetching them in one request from the server * currently it goes to the server twice. First, it asks for the last version of each id, and then it goes again to * ask for the older versions. */ async importManyWithAllVersions( ids: BitIds, cache = true, allDepsVersions = false // by default, only dependencies of the latest version are imported ): Promise<VersionDependencies[]> { logger.debug(`scope.getManyWithAllVersions, Ids: ${ids.join(', ')}`); Analytics.addBreadCrumb('getManyWithAllVersions', `scope.getManyWithAllVersions, Ids: ${Analytics.hashData(ids)}`); const idsWithoutNils = removeNils(ids); if (R.isEmpty(idsWithoutNils)) return Promise.resolve([]); const versionDependenciesArr: VersionDependencies[] = await this.importMany(idsWithoutNils, cache); const allIdsWithAllVersions = new BitIds(); versionDependenciesArr.forEach(versionDependencies => { const versions = versionDependencies.component.component.listVersions(); const idsWithAllVersions = versions.map(version => { if (version === versionDependencies.component.version) return null; // imported already const versionId = versionDependencies.component.id; return versionId.changeVersion(version); }); allIdsWithAllVersions.push(...removeNils(idsWithAllVersions)); }); if (allDepsVersions) { const verDepsOfOlderVersions = await this.importMany(allIdsWithAllVersions, cache); versionDependenciesArr.push(...verDepsOfOlderVersions); const allFlattenDepsIds = versionDependenciesArr.map(v => v.allDependencies.map(d => d.id)); const dependenciesOnly = R.flatten(allFlattenDepsIds).filter((id: BitId) => !ids.hasWithoutVersion(id)); const verDepsOfAllFlattenDeps = await this.importManyWithAllVersions(BitIds.uniqFromArray(dependenciesOnly)); versionDependenciesArr.push(...verDepsOfAllFlattenDeps); } else { await this.importManyWithoutDependencies(allIdsWithAllVersions); } return versionDependenciesArr; } importDependencies(dependencies: BitIds): Promise<VersionDependencies[]> { return new Promise((resolve, reject) => { return this.importMany(dependencies) .then(resolve) .catch(e => { logger.error(`importDependencies got an error: ${JSON.stringify(e)}`); if (e instanceof RemoteScopeNotFound || e instanceof PermissionDenied) return reject(e); return reject(new DependencyNotFound(e.id)); }); }); } async componentToVersionDependencies(component: ModelComponent, id: BitId): Promise<VersionDependencies> { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const versionComp: ComponentVersion = component.toComponentVersion(id.version); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const source: string = id.scope; const version: Version = await versionComp.getVersion(this.scope.objects); if (!version) { logger.debug( `toVersionDependencies, component ${component.id().toString()}, version ${ versionComp.version } not found, going to fetch from a remote` ); if (component.scope === this.scope.name) { // it should have been fetched locally, since it wasn't found, this is an error throw new ShowDoctorError( `Version ${versionComp.version} of ${component.id().toString()} was not found in scope ${this.scope.name}` ); } return getScopeRemotes(this.scope).then(remotes => { return this._getExternal({ id, remotes, localFetch: false }); }); } logger.debug( `toVersionDependencies, component ${component.id().toString()}, version ${ versionComp.version } found, going to collect its dependencies` ); const dependencies = await this.importManyWithoutDependencies(version.flattenedDependencies); const devDependencies = await this.importManyWithoutDependencies(version.flattenedDevDependencies); const extensionsDependencies = await this.importManyWithoutDependencies(version.extensions.extensionsBitIds); return new VersionDependencies(versionComp, dependencies, devDependencies, extensionsDependencies, source); } componentsToComponentsObjects( components: Array<VersionDependencies | ComponentVersion>, clientVersion: string | null | undefined ): Promise<ComponentObjects[]> { return pMapSeries(components, component => component.toObjects(this.scope.objects, clientVersion)); } /** * get ConsumerComponent by bitId. if the component was not found locally, import it from a remote scope */ loadRemoteComponent(id: BitId): Promise<ConsumerComponent> { return this._getComponentVersion(id).then(component => { if (!component) throw new ComponentNotFound(id.toString()); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return component.toConsumer(this.scope.objects); }); } loadComponent(id: BitId, localOnly = true): Promise<ConsumerComponent> { logger.debugAndAddBreadCrumb('ScopeComponentsImporter', 'loadComponent {id}', { id: id.toString() }); if (localOnly && !id.isLocal(this.scope.name)) { throw new GeneralError('cannot load a component from remote scope, please import first'); } return this.loadRemoteComponent(id); } /** * recursive function. * if found locally, use them. Otherwise, fetch from remote and then, save into the model. */ _getExternalMany( ids: BitId[], remotes: Remotes, localFetch = true, persist = true, context: Record<string, any> = {} ): Promise<VersionDependencies[]> { if (!ids.length) return Promise.resolve([]); logger.debugAndAddBreadCrumb( 'scope.getExternalMan', `planning on fetching from ${localFetch ? 'local' : 'remote'} scope. Ids: {ids}`, { ids: ids.join(', ') } ); enrichContextFromGlobal(Object.assign(context, { requestedBitIds: ids.map(id => id.toString()) })); return this.sources.getMany(ids).then(defs => { const left = defs.filter(def => { if (!localFetch) return true; if (!def.component) return true; return false; }); if (left.length === 0) { logger.debugAndAddBreadCrumb( 'scope.getExternalMany', 'no more ids left, all found locally, exiting the method' ); return pMapSeries(defs, def => this.componentToVersionDependencies(def.component, def.id)); } logger.debugAndAddBreadCrumb('scope.getExternalMany', `${left.length} left. Fetching them from a remote`); return remotes .fetch( left.map(def => def.id), this.scope, undefined, context ) .then(componentObjects => { logger.debugAndAddBreadCrumb('scope.getExternalMany', 'writing them to the model'); return this.scope.writeManyComponentsToModel(componentObjects, persist); }) .then(() => this._getExternalMany(ids, remotes)); }); } /** * If the component is not in the local scope, fetch it from a remote and save into the local * scope. (objects directory). */ _getExternal({ id, remotes, localFetch = true, context = {} }: { id: BitId; remotes: Remotes; localFetch: boolean; context?: Record<string, any>; }): Promise<VersionDependencies> { enrichContextFromGlobal(context); return this.sources.get(id).then(component => { if (component && localFetch) { return this.componentToVersionDependencies(component, id); } return remotes .fetch([id], this.scope, undefined, context) .then(([componentObjects]) => { return this.scope.writeComponentToModel(componentObjects); }) .then(() => this._getExternal({ id, remotes, localFetch: true })); }); } _getExternalWithoutDependencies({ id, remotes, localFetch = true, context = {} }: { id: BitId; remotes: Remotes; localFetch: boolean; context?: Record<string, any>; }): Promise<ComponentVersion> { return this.sources.get(id).then(component => { if (component && localFetch) { // $FlowFixMe scope component must have a version // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return component.toComponentVersion(id.version); } return remotes .fetch([id], this.scope, true, context) .then(([componentObjects]) => this.scope.writeComponentToModel(componentObjects)) .then(() => this._getExternal({ id, remotes, localFetch: true })) .then((versionDependencies: VersionDependencies) => versionDependencies.component); }); } _getExternalManyWithoutDependencies( ids: BitId[], remotes: Remotes, localFetch = false, context: Record<string, any> = {} ): Promise<ComponentVersion[]> { if (!ids.length) return Promise.resolve([]); logger.debugAndAddBreadCrumb( 'getExternalOnes', `getExternalOnes, ids: {ids}, localFetch: ${localFetch.toString()}`, { ids: ids.join(', ') } ); enrichContextFromGlobal(Object.assign(context, { requestedBitIds: ids.map(id => id.toString()) })); return this.sources.getMany(ids).then((defs: ComponentDef[]) => { const left = defs.filter(def => { if (!localFetch) return true; if (!def.component) return true; return false; }); if (left.length === 0) { logger.debugAndAddBreadCrumb( 'scope.getExternalOnes', 'no more ids left, all found locally, exiting the method' ); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return Promise.all(defs.map(def => def.component.toComponentVersion(def.id.version))); } logger.debugAndAddBreadCrumb( 'getExternalOnes', `getExternalOnes: ${left.length} left. Fetching them from a remote` ); return remotes .fetch( left.map(def => def.id), this.scope, true, context ) .then(componentObjects => { return this.scope.writeManyComponentsToModel(componentObjects); }) .then(() => this._getExternalManyWithoutDependencies(ids, remotes, true)); }); } async _getComponentVersion(id: BitId): Promise<ComponentVersion> { if (!id.isLocal(this.scope.name)) { const remotes = await getScopeRemotes(this.scope); return this._getExternalWithoutDependencies({ id, remotes, localFetch: true }); } return this.sources.get(id).then(component => { if (!component) throw new ComponentNotFound(id.toString()); // $FlowFixMe version is set // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return component.toComponentVersion(id.version); }); } }
the_stack
* Format for an HTTP/JSON request to a grpc-gateway for a trace span exporter. */ export interface ExportTraceServiceRequest { node?: Node; /** A list of Spans that belong to the last received Node. */ spans?: Span[]; /** * The resource for the spans in this message that do not have an explicit * resource set. * If unset, the most recently set resource in the RPC stream applies. It is * valid to never be set within a stream, e.g. when no resource info is known. */ resource?: Resource; } /** * Format for an HTTP/JSON response from a grpc-gateway for trace span exporter. */ export interface ExportTraceServiceResponse {} /** Resource information. */ export interface Resource { /** Type identifier for the resource. */ type?: string; /** Set of labels that describe the resource. */ labels?: { [key: string]: string }; } /** * Identifier metadata of the Node (Application instrumented with OpenCensus) * that connects to OpenCensus Agent. * In the future we plan to extend the identifier proto definition to support * additional information (e.g cloud id, etc.) */ export interface Node { /** Identifier that uniquely identifies a process within a VM/container. */ identifier?: ProcessIdentifier; /** Information on the OpenCensus Library that initiates the stream. */ libraryInfo?: LibraryInfo; /** Additional information on service. */ serviceInfo?: ServiceInfo; /** Additional attributes. */ attributes?: { [key: string]: string }; } /** Unspecified library info language. */ export type LanguageUnspecified = 0; /** Indicates that the spans were created by OpenCensus Web. */ export type LanguageWebJs = 10; /** * OpenCensus language used to create the spans. Most of the options are * omitted since the spans produced by OpenCensus Web are always from the Web JS * library. */ export type LibraryInfoLanguage = LanguageUnspecified | LanguageWebJs; /** Information on OpenCensus library that produced the spans/metrics. */ export interface LibraryInfo { /** Language of OpenCensus Library. */ language?: LibraryInfoLanguage; /** Version of Agent exporter of Library. */ exporterVersion?: string; /** Version of OpenCensus Library. */ coreLibraryVersion?: string; } /** * Identifier that uniquely identifies a process within a VM/container. * For OpenCensus Web, this identifies the domain name of the site. */ export interface ProcessIdentifier { /** * The host name. Usually refers to the machine/container name. * For example: os.Hostname() in Go, socket.gethostname() in Python. * This will be the value of `window.location.host` for OpenCensus Web. */ hostName?: string; /** Process id. Not used in OpenCensus Web. */ pid?: number; /** Start time of this ProcessIdentifier. Represented in epoch time.. */ startTimestamp?: string; } /** Additional service information. */ export interface ServiceInfo { /** Name of the service. */ name?: string; } /** Type for the `tracestate` */ export interface TraceState { [key: string]: string; } /** Unspecified span kind. */ export type SpanKindUnspecified = 0; /** * Indicates that the span covers server-side handling of an RPC or other * remote network request. */ export type SpanKindServer = 1; /** * Indicates that the span covers the client-side wrapper around an RPC or * other remote request. */ export type SpanKindClient = 2; /** * Type of span. Can be used to specify additional relationships between spans * in addition to a parent/child relationship. */ export type SpanKind = SpanKindUnspecified | SpanKindServer | SpanKindClient; /** * A span represents a single operation within a trace. Spans can be nested to * form a trace tree. Often, a trace contains a root span that describes the * end-to-end latency, and one or more subspans for its sub-operations. A trace * can also contain multiple root spans, or none at all. Spans do not need to be * contiguous - there may be gaps or overlaps between spans in a trace. The * next id is 16. TODO(bdrutu): Add an example. */ export interface Span { /** * A unique identifier for a trace. All spans from the same trace share the * same `trace_id`. The ID is a 16-byte array. This field is required. */ traceId: string; /** * A unique identifier for a span within a trace, assigned when the span is * created. The ID is an 8-byte array. This field is required. */ spanId: string; /** * The `tracestate` field conveys information about request position in * multiple distributed tracing graphs. There can be a maximum of 32 members * in the map. The key must begin with a lowercase letter, and can only * contain lowercase letters 'a'-'z', digits '0'-'9', underscores '_', dashes * '-', asterisks '*', and forward slashes '/'. For multi-tenant vendors * scenarios '@' sign can be used to prefix vendor name. The maximum length * for the key is 256 characters. The value is opaque string up to 256 * characters printable ASCII RFC0020 characters (i.e., the range 0x20 to * 0x7E) except ',' and '='. Note that this also excludes tabs, newlines, * carriage returns, etc. See the https://github.com/w3c/distributed-tracing * for more details about this field. */ tracestate?: TraceState; /** * The `span_id` of this span's parent span. If this is a root span, then this * field must be empty. The ID is an 8-byte array. */ parentSpanId?: string; /** * A description of the span's operation. For example, the name can be a * qualified method name or a file name and a line number where the operation * is called. A best practice is to use the same display name at the same call * point in an application. This makes it easier to correlate spans in * different traces. This field is required. */ name?: TruncatableString; /** * Distinguishes between spans generated in a particular context. For example, * two spans with the same name may be distinguished using `CLIENT` and * `SERVER` to identify queueing latency associated with the span. */ kind?: SpanKind; /** * The start time of the span. On the client side, this is the time kept by * the local machine where the span execution starts. On the server side, this * is the time when the server's application handler starts running. */ startTime?: string; /** * The end time of the span. On the client side, this is the time kept by the * local machine where the span execution ends. On the server side, this is * the time when the server application handler stops running. */ endTime?: string; /** * A set of attributes on the span. */ attributes?: Attributes; /** * A stack trace captured at the start of the span. */ stackTrace?: StackTrace; /** * The included time events. */ timeEvents?: TimeEvents; /** * The inclued links. */ links?: Links; /** * An optional final status for this span. */ status?: Status; /** * A highly recommended but not required flag that identifies when a trace * crosses a process boundary. True when the parent_span belongs to the same * process as the current span. */ sameProcessAsParentSpan?: boolean; /** * An optional number of child spans that were generated while this span was * active. If set, allows an implementation to detect missing child spans. */ childSpanCount?: number; } export interface AttributeMap { [key: string]: AttributeValue; } /** * A set of attributes, each with a key and a value. */ export interface Attributes { /** * \"/instance_id\": \"my-instance\" \"/http/user_agent\": \"\" * \"/http/server_latency\": 300 \"abc.com/myattribute\": true */ attributeMap?: AttributeMap; /** * The number of attributes that were discarded. Attributes can be discarded * because their keys are too long or because there are too many attributes. * If this value is 0, then no attributes were dropped. */ droppedAttributesCount?: number; } /** * The relationship of the two spans is unknown, or known but other than * parent-child. */ export type LinkTypeUnspecified = 0; /** The linked span is a child of the current span. */ export type LinkTypeChildLinkedSpan = 1; /** The linked span is a parent of the current span. */ export type LinkTypeParentLinkedSpan = 2; /** * The relationship of the current span relative to the linked span: child, * parent, or unspecified. */ export type LinkType = | LinkTypeUnspecified | LinkTypeChildLinkedSpan | LinkTypeParentLinkedSpan; /** * A pointer from the current span to another span in the same trace or in a * different trace. For example, this can be used in batching operations, where * a single batch handler processes multiple requests from different traces or * when the handler receives a request from a different project. */ export interface Link { /** * A unique identifier for a trace. All spans from the same trace share the * same `trace_id`. The ID is a 16-byte array. */ traceId?: string; /** * A unique identifier for a span within a trace, assigned when the span is * created. The ID is an 8-byte array. */ spanId?: string; /** * The relationship of the current span relative to the linked span. */ type?: LinkType; /** * A set of attributes on the link. */ attributes?: Attributes; } /** * A collection of links, which are references from this span to a span in the * same or different trace. */ export interface Links { /** * A collection of links. */ link?: Link[]; /** * The number of dropped links after the maximum size was enforced. If this * value is 0, then no links were dropped. */ droppedLinksCount?: number; } /** * A time-stamped annotation or message event in the Span. */ export interface TimeEvent { /** * The time the event occurred. */ time?: string; /** * A text annotation with a set of attributes. */ annotation?: Annotation; /** * An event describing a message sent/received between Spans. */ messageEvent?: MessageEvent; } /** * A collection of `TimeEvent`s. A `TimeEvent` is a time-stamped annotation on * the span, consisting of either user-supplied key-value pairs, or details of a * message sent/received between Spans. */ export interface TimeEvents { /** * A collection of `TimeEvent`s. */ timeEvent?: TimeEvent[]; /** * The number of dropped annotations in all the included time events. If the * value is 0, then no annotations were dropped. */ droppedAnnotationsCount?: number; /** * The number of dropped message events in all the included time events. If * the value is 0, then no message events were dropped. */ droppedMessageEventsCount?: number; } /** * A single stack frame in a stack trace. */ export interface StackFrame { /** * The fully-qualified name that uniquely identifies the function or method * that is active in this frame. */ functionName?: TruncatableString; /** * An un-mangled function name, if `function_name` is * [mangled](http://www.avabodh.com/cxxin/namemangling.html). The name can be * fully qualified. */ originalFunctionName?: TruncatableString; /** * The name of the source file where the function call appears. */ fileName?: TruncatableString; /** * The line number in `file_name` where the function call appears. */ lineNumber?: string; /** * The column number where the function call appears, if available. This is * important in JavaScript because of its anonymous functions. */ columnNumber?: string; /** * The binary module from where the code was loaded. */ loadModule?: Module; /** * The version of the deployed source code. */ sourceVersion?: TruncatableString; } /** * A collection of stack frames, which can be truncated. */ export interface StackFrames { /** * Stack frames in this call stack. */ frame?: StackFrame[]; /** * The number of stack frames that were dropped because there were too many * stack frames. If this value is 0, then no stack frames were dropped. */ droppedFramesCount?: number; } /** * A text annotation with a set of attributes. */ export interface Annotation { /** * A user-supplied message describing the event. */ description?: TruncatableString; /** * A set of attributes on the annotation. */ attributes?: Attributes; } /** Unknown message event type. */ export type MessageEventTypeUnspecified = 0; /** Indicates a sent message. */ export type MessageEventTypeSent = 1; /** Indicates a received message. */ export type MessageEventTypeReceived = 2; /** Indicates whether the message was sent or received. */ export type MessageEventType = | MessageEventTypeUnspecified | MessageEventTypeSent | MessageEventTypeReceived; /** * An event describing a message sent/received between Spans. */ export interface MessageEvent { /** * The type of MessageEvent. Indicates whether the message was sent or * received. */ type?: MessageEventType; /** * An identifier for the MessageEvent's message that can be used to match SENT * and RECEIVED MessageEvents. For example, this field could represent a * sequence ID for a streaming RPC. It is recommended to be unique within a * Span. */ id?: string | number; /** * The number of uncompressed bytes sent or received. */ uncompressedSize?: string | number; /** * The number of compressed bytes sent or received. If zero, assumed to be the * same size as uncompressed. */ compressedSize?: string | number; } /** * The value of an Attribute. */ export interface AttributeValue { /** * A string up to 256 bytes long. */ stringValue?: TruncatableString; /** * A 64-bit signed integer. May be sent to the API as either number or string * type (string is needed to accurately express some 64-bit ints). */ intValue?: string | number; /** * A Boolean value represented by `true` or `false`. */ boolValue?: boolean; /** * A double precision floating point value. */ doubleValue?: number; } /** * A description of a binary module. */ export interface Module { /** * TODO: document the meaning of this field. For example: main binary, kernel * modules, and dynamic libraries such as libc.so, sharedlib.so. */ module?: TruncatableString; /** * A unique identifier for the module, usually a hash of its contents. */ buildId?: TruncatableString; } /** * The call stack which originated this span. */ export interface StackTrace { /** * Stack frames in this stack trace. */ stackFrames?: StackFrames; /** * The hash ID is used to conserve network bandwidth for duplicate stack * traces within a single trace. Often multiple spans will have identical * stack traces. The first occurrence of a stack trace should contain both * `stack_frames` and a value in `stack_trace_hash_id`. Subsequent spans * within the same request can refer to that stack trace by setting only * `stack_trace_hash_id`. TODO: describe how to deal with the case where * stack_trace_hash_id is zero because it was not set. */ stackTraceHashId?: string; } /** * The `Status` type defines a logical error model that is suitable for * different programming environments, including REST APIs and RPC APIs. This * proto's fields are a subset of those of * [google.rpc.Status](https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto), * which is used by [gRPC](https://github.com/grpc). */ export interface Status { /** * The status code. */ code?: number; /** * A developer-facing error message, which should be in English. */ message?: string; } /** * A string that might be shortened to a specified length. */ export interface TruncatableString { /** * The shortened string. For example, if the original string was 500 bytes * long and the limit of the string was 128 bytes, then this value contains * the first 128 bytes of the 500-byte string. Note that truncation always * happens on a character boundary, to ensure that a truncated string is still * valid UTF-8. Because it may contain multi-byte characters, the size of the * truncated string may be less than the truncation limit. */ value?: string; /** * The number of bytes removed from the original string. If this value is 0, * then the string was not shortened. */ truncatedByteCount?: number; }
the_stack
export = CesiumMeshVisualizer; export as namespace CesiumMeshVisualizer; import * as Cesium from './Cesium'; import * as geojson from './geojson'; import THREE from './THREE' /** * Make you can use three.js geometry in Cesium,and use mesh,geometry,material like three.js to manage renderable object in Cesium. */ declare namespace CesiumMeshVisualizer { /** * @returns {geojson.Feature} */ export function f():geojson.FeatureCollection<geojson.Shape> /** *定义属性,并监听属性变化事件,属性值的数据类型可以实现equals接口用于进行更进一步的比较 *@param {Object}owner *@param {String}name *@param {Any}defaultVal *@param {( changed: string, owner: object, newVal: *, oldVal: * ) => void}onChanged *@memberof Cesium */ export function defineProperty(owner: object, name: string, defaultVal: any, onChanged: ( changed: string, owner: object, newVal: any, oldVal: any ) => void): void export class GeometryUtils { /** *绕x轴旋转,修改顶点坐标 *@param {Cesium.Geometry}geometry *@param {Number}angle 弧度 */ static rotateX: (geometry: Cesium.Geometry, angle: number) => Cesium.Geometry /** *绕y轴旋转,修改顶点坐标 *@param {Cesium.Geometry}geometry *@param {Number}angle 弧度 */ static rotateY: (geometry: Cesium.Geometry, angle: number) => Cesium.Geometry /** *绕z轴旋转,修改顶点坐标 *@param {Cesium.Geometry}geometry *@param {Number}angle 弧度 */ static rotateZ: (geometry: Cesium.Geometry, angle: number) => Cesium.Geometry /** * *@param {Cesium.Geometry}geometry *@returns {Cesium.Geometry} */ static computeVertexNormals: (geometry) => Cesium.Geometry /** *合并两个或两个以上图形类型(primitiveType),属性数量、名称以及属性值的类型(GeometryAttribute的componentDatatype、componentsPerAttribute等)都一致的几何体 *@param {Array<Cesium.Geometry>}geometries *@return {Cesium.Geometry} */ static mergeGeometries: (geometries: Cesium.Geometry[]) => Cesium.Geometry /** * *@param {Cesium.Geometry}geometry *@param {Cesium.Cartesian3}offset */ static translate: (geometry: Cesium.Geometry, offset: number) => Cesium.Geometry /** * *@param {THREE.Geometry}geometry3js type:THREE.Geometry *@return {Cesium.Geometry} */ static fromGeometry3js: (geometry3js: THREE.Geometry) => Cesium.Geometry /** * *@param {Cesium.Geometry}geometry *@return {THREE.Geometry} */ static toGeometry3js: (geometry: Cesium.Geometry) => THREE.Geometry /** *@param {Cesium.Geometry|THREE.Geometry}geometry *@param {Cesium.Cartesian3}[offset] *@return {CSG} */ static toCSG: (geometry: Cesium.Geometry | THREE.Geometry, offset) => CSG /** *@param {CSG}csg_model *@param {Boolean}[toGeometry3js=false] *@return {Cesium.Geometry|THREE.Geometry} */ static fromCSG: (csg_model: CSG, toGeometry3js: boolean) => Cesium.Geometry | THREE.Geometry } /** * Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean operations like union and intersection to combine 3D solids. This library implements CSG operations on meshes elegantly and concisely using BSP trees, and is meant to serve as an easily understandable implementation of the algorithm. All edge cases involving overlapping coplanar polygons in both solids are correctly handled. Example usage: var cube = CSG.cube(); var sphere = CSG.sphere({ radius: 1.3 }); var polygons = cube.subtract(sphere).toPolygons(); ## Implementation Details All CSG operations are implemented in terms of two functions, `clipTo()` and `invert()`, which remove parts of a BSP tree inside another BSP tree and swap solid and empty space, respectively. To find the union of `a` and `b`, we want to remove everything in `a` inside `b` and everything in `b` inside `a`, then combine polygons from `a` and `b` into one solid: a.clipTo(b); b.clipTo(a); a.build(b.allPolygons()); The only tricky part is handling overlapping coplanar polygons in both trees. The code above keeps both copies, but we need to keep them in one tree and remove them in the other tree. To remove them from `b` we can clip the inverse of `b` against `a`. The code for union now looks like this: a.clipTo(b); b.clipTo(a); b.invert(); b.clipTo(a); b.invert(); a.build(b.allPolygons()); Subtraction and intersection naturally follow from set operations. If union is `A | B`, subtraction is `A - B = ~(~A | B)` and intersection is `A & B = ~(~A | ~B)` where `~` is the complement operator. ## License Copyright (c) 2011 Evan Wallace (http://madebyevan.com/), under the MIT license. # class CSG Holds a binary space partition tree representing a 3D solid. Two solids can be combined using the `union()`, `subtract()`, and `intersect()` methods. */ export class CSG { polygons: [] /** * Construct a CSG solid from a list of `CSG.Polygon` instances. */ static fromPolygons: (polygons) => CSG clone: () => CSG toPolygons: () => [] /** * Return a new CSG solid representing space in either this solid or in the * solid `csg`. Neither this solid nor the solid `csg` are modified. * * A.union(B) * * +-------+ +-------+ * | | | | * | A | | | * | +--+----+ = | +----+ * +----+--+ | +----+ | * | B | | | * | | | | * +-------+ +-------+ * */ union: (csg) => CSG /** * Return a new CSG solid representing space in this solid but not in the * solid `csg`. Neither this solid nor the solid `csg` are modified. * * A.subtract(B) * * +-------+ +-------+ * | | | | * | A | | | * | +--+----+ = | +--+ * +----+--+ | +----+ * | B | * | | * +-------+ */ subtract: (csg) => CSG /** * Return a new CSG solid representing space both this solid and in the * solid `csg`. Neither this solid nor the solid `csg` are modified. * * A.intersect(B) * * +-------+ * | | * | A | * | +--+----+ = +--+ * +----+--+ | +--+ * | B | * | | * +-------+ */ intersect: (csg) => CSG /** * Return a new CSG solid with solid and empty space switched. This solid is * not modified. */ inverse: () => CSG /** * Construct an axis-aligned solid cuboid. Optional parameters are `center` and * `radius`, which default to `[0, 0, 0]` and `[1, 1, 1]`. The radius can be * specified using a single number or a list of three numbers, one for each axis. * * Example code: * * var cube = CSG.cube({ * center: [0, 0, 0], * radius: 1 * }); */ static cube: (options) => CSG /** * Construct a solid sphere. Optional parameters are `center`, `radius`, * `slices`, and `stacks`, which default to `[0, 0, 0]`, `1`, `16`, and `8`. * The `slices` and `stacks` parameters control the tessellation along the * longitude and latitude directions. * * Example usage: * * var sphere = CSG.sphere({ * center: [0, 0, 0], * radius: 1, * slices: 16, * stacks: 8 * }); */ static sphere: (options) => CSG /** * Construct a solid cylinder. Optional parameters are `start`, `end`, * `radius`, and `slices`, which default to `[0, -1, 0]`, `[0, 1, 0]`, `1`, and * `16`. The `slices` parameter controls the tessellation. * * Example usage: * * var cylinder = CSG.cylinder({ * start: [0, -1, 0], * end: [0, 1, 0], * radius: 1, * slices: 16 * }); */ static cylinder: (options) => CSG } /** * *@param {Object}options *@param {Array<Number>|Float32Array}options.positions *@param {Array<Number>|Int32Array}options.indices *@param {Array<Number>|Float32Array}[options.normals] *@param {Array<Number>|Float32Array}[options.uvs] * *@memberof Cesium *@constructor */ export class BasicGeometry { constructor(options: { positions: number[] | Float32Array indices: number[] | Int32Array normals: number[] | Float32Array uvs: number[] | Float32Array }) positions: number[] | Float32Array indices: number[] | Int32Array normals: number[] | Float32Array uvs: number[] | Float32Array /** * *@param {Cesium.BasicGeometry}basicGeometry *@return {Cesiumm.Geometry} */ static createGeometry: (basicGeometry) => Cesium.Geometry } /** * : + —— + + | + + headLength + + | ++++headWidth++++ —— + + | + + | + + | + + length + + | + + | + + | ++++ —— width *@param {Object}[options] *@param {Number}[options.length=50000] *@param {Number}[options.width=250] *@param {Number}[options.headLength=5000] *@param {Number}[options.headWidth=1000] *@param {Boolean}[options.reverse=false] * *@property {Number}length *@property {Number}width *@property {Number}headLength *@property {Number}headWidth *@property {Boolean}reverse * *@constructor *@memberof Cesium */ export class ArrowGeometry { constructor(options: { length: number//= Cesium.defaultValue(options.length, 50000); width: number// = Cesium.defaultValue(options.width, 125); headLength: number// = Cesium.defaultValue(options.headLength, 5000); headWidth: number// = Cesium.defaultValue(options.headWidth, 1000); reverse: boolean//= Cesium.defaultValue(options.reverse, false); }) length: number//= Cesium.defaultValue(options.length, 50000); width: number// = Cesium.defaultValue(options.width, 125); headLength: number// = Cesium.defaultValue(options.headLength, 5000); headWidth: number// = Cesium.defaultValue(options.headWidth, 1000); reverse: boolean//= Cesium.defaultValue(options.reverse, false); static createGeometry: (arrowGeometry: ArrowGeometry) => Cesium.Geometry } /** * * : * * -----width----+(width/2,height/2) * | | * | (0,0) | * | + height * | | * | | * +----width----- * (-width/2,-height/2) * *@param {Number}width *@param {Number}height *@param {Number}widthSegments *@param {Number}heightSegments *@constructor *@memberof Cesium */ export class PlaneBufferGeometry { constructor(width: number, height: number, widthSegments: number, heightSegments: number) width: number height: number widthSegments: number heightSegments: number createGeometry: () => Cesium.Geometry } /** *: * * p1------------p4 * | + | * | + | * | + | * | + | * | + | * p2------------p3 * *@param {Object}options *@param {Array<Number|Cesium.Cartesian3>}options.positions [p1,p2,p3,p4]或者[p1.x,p1.y,p1.z,p2.x,...,p4.z] * *@property {Array<Number|Cesium.Cartesian3>}positions * *@constructor *@memberof Cesium */ export class PlaneGeometry { constructor(options: { positions: Array<Number | Cesium.Cartesian3> }) createGeometry: () => Cesium.Geometry } /** * *@param {Cesium.Cartesian3}axis - type:Cesium.Cartesian3 旋转轴 *@param {Number}angle 旋转角度 * *@property {Cesium.Cartesian3}axis 旋转轴 *@property {Number}angle 旋转角度 *@property {Cesium.Event}paramChanged *@constructor *@memberof Cesium */ export class Rotation { /** * *@param {Cesium.Cartesian3}axis - type:Cesium.Cartesian3 旋转轴 *@param {Number}angle 旋转角度 * *@property {Cesium.Cartesian3}axis 旋转轴 *@property {Number}angle 旋转角度 *@property {Cesium.Event}paramChanged *@constructor *@memberof Cesium */ constructor(axis: Cesium.Cartesian3, angle: number) /** * @type {Cesium.Cartesian3} */ axis: Cesium.Cartesian3 angle: number } export interface MashMaterialOptions { vertexShader: string fragmentShader: string pickColorQualifier: string uniforms: object uniformStateUsed: object translucent: boolean wireframe: boolean /** * FRONT: 3, * BACK: 1, * DOUBLE: 2 */ side: number /** * @type {Cesium.Color|string} */ defaultColor: Cesium.Color | string depthTest: boolean depthMask: boolean blending: boolean allowPick: boolean } /** * *@param {Object}options *@param {Object}[options.uniforms] *@param {Object}[options.uniformStateUsed] *@param {Boolean}[options.translucent] *@param {Boolean}[options.wireframe] *@param {Enum}[options.side=Cesium.MeshMaterial.Sides.DOUBLE] *@param {String|Cesium.Color}[options.defaultColor=Cesium.Color.WHITE] *@param {String}[options.vertexShader] *@param {String}[options.fragmentShader] *@param {string}[options.pickColorQualifier] * * *@property {Object}uniforms *@property {Object}uniformStateUsed *@property {Boolean}translucent *@property {Boolean}wireframe *@property {Enum}side *@property {String|Cesium.Color}defaultColor *@property {String}vertexShader *@property {String}fragmentShader * *@constructor *@memberof Cesium */ export class MeshMaterial { constructor(options: { vertexShader: string fragmentShader: string pickColorQualifier: string uniforms: object uniformStateUsed: object translucent: boolean wireframe: boolean /** * FRONT: 3, * BACK: 1, * DOUBLE: 2 */ side: number /** * @type {Cesium.Color|string} */ defaultColor: Cesium.Color | string depthTest: boolean depthMask: boolean blending: boolean allowPick: boolean }) uuid: string vertexShader: string fragmentShader: string pickColorQualifier: string uniforms: object uniformStateUsed: object translucent: boolean wireframe: boolean /** * FRONT: 3, * BACK: 1, * DOUBLE: 2 */ side: number /** * @type {Cesium.Color|string} */ defaultColor: Cesium.Color | string depthTest: boolean depthMask: boolean blending: boolean allowPick: boolean } /** * *@param {Object|geometry}options *@param {Cesium.Geometry|Cesium.CSG|THREE.Geometry|THREE.BufferGeometry}options.geometry *@param {Cesium.MeshMaterial}options.material *@param {Boolean}[options.show=true] *@param {Cesium.Cartesian3}[options.position] *@param {Cesium.Rotation}[options.rotation] *@param {Cesium.Cartesian3}[options.scale] *@param {{modelMatrix:Cesium.Matrix4,show:boolean}[]}[options.instances] *@param {Cesium.MeshMaterial}[material] *@param {{modelMatrix:Cesium.Matrix4,show:boolean}[]}[instances] *@param {{name:string,default:number|Cesium.Cartesian2|Cesium.Cartesian3|Cesium.Cartesian4|Cesium.Color}[]}[instancedAttributes] * *@property {Cesium.Geometry}geometry *@property {Cesium.MeshMaterial}material *@property {Boolean}show *@property {Cesium.Cartesian3}position *@property {Cesium.VolumeRendering.Rotation}rotation *@property {Cesium.Cartesian3}scale *@property {Boolean}needUpdate *@property {Cesium.Mesh|Cesium.LOD}parent *@property {{modelMatrix:Cesium.Matrix4}[]}instances * *@constructor *@memberof Cesium *@example //1. var mesh=new Mesh(geomertry,material); //2. var mesh2=new Mesh({ geomertry:geomertry2, material:material2, position:position2 }); */ export class Mesh { constructor(options: { /** * @type {Cesium.Geometry|Cesium.CSG|THREE.Geometry|THREE.BufferGeometry} */ geometry: Cesium.Geometry | CSG | THREE.Geometry | THREE.BufferGeometry material: MeshMaterial show?: boolean position?: Cesium.Cartesian3 rotation?: Rotation scale?: Cesium.Cartesian3 instances?: { modelMatrix: Cesium.Matrix4, show: boolean }[] instancedAttributes?: { name: string, default: number | Cesium.Cartesian2 | Cesium.Cartesian3 | Cesium.Cartesian4 | Cesium.Color }[] }) constructor( /** * @type {Cesium.Geometry|Cesium.CSG|THREE.Geometry|THREE.BufferGeometry} */ geometry: Cesium.Geometry | Cesium.CSG | THREE.Geometry | THREE.BufferGeometry, material: MeshMaterial, instances?: { modelMatrix: Cesium.Matrix4, show: boolean }[], instancedAttributes?: { name: string, default: number | Cesium.Cartesian2 | Cesium.Cartesian3 | Cesium.Cartesian4 | Cesium.Color }[] ) geometry: Cesium.Geometry | CSG | THREE.Geometry | THREE.BufferGeometry material: MeshMaterial show: boolean position: Cesium.Cartesian3 rotation: Rotation scale: Cesium.Cartesian3 instances: { modelMatrix: Cesium.Matrix4, show: boolean }[] instancedAttributes: { name: string, default: number | Cesium.Cartesian2 | Cesium.Cartesian3 | Cesium.Cartesian4 | Cesium.Color }[] needsUpdate: boolean modelMatrix: Cesium.Matrix4 parent: object modelMatrixNeedsUpdate: boolean /** * * @param {object}instance * @param {Cesium.Matrix4}instance.modelMatrix * @param {boolean}[instance.show=true] */ addInstance: (instance: { modelMatrix: Cesium.Matrix4, show: boolean }) => object /** * *@param {Cesium.Mesh|Cesium.LOD}node *@param {(node: Cesium.Mesh | Cesium.LOD) => void}callback */ static traverse: (node: Mesh | LOD, callback: (node: Cesium.Mesh | Cesium.LOD) => void) => void /** *@oaram {Cesium.Mesh|Cesium.LOD}child */ add: (mesh: Cesium.Mesh | Cesium.LOD) => void } /** * *@param {Object|geometry}options *@param {Boolean}[options.show=true] *@param {Cesium.Cartesian3}[options.position] *@param {Cesium.Rotation}[options.rotation] *@param {Cesium.Cartesian3}[options.scale] * *@property {Boolean}show *@property {Cesium.Cartesian3}position *@property {Cesium.Rotation}rotation *@property {Cesium.Cartesian3}scale *@property {Boolean}needUpdate * *@constructor *@memberof Cesium *@example MeshVisualizer = Cesium.MeshVisualizer; Mesh = Cesium.Mesh; MeshMaterial = Cesium.MeshMaterial; LOD = Cesium.LOD; var center = Cesium.Cartesian3.fromDegrees(homePosition[0], homePosition[1], 50000); var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center); var meshVisualizer = new MeshVisualizer({ modelMatrix: modelMatrix, up: { z: 1 } }); viewer.scene.primitives.add(meshVisualizer); var material = new MeshMaterial({ defaultColor: "rgba(200,0,0,1.0)", wireframe: true, side: MeshMaterial.Sides.FRONT }); var radius = 20000; var sphereL0 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({ radius: radius, vertexFormat: Cesium.VertexFormat.POSITION_ONLY, stackPartitions:4, slicePartitions: 4 })); var sphereL1 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({ radius: radius, vertexFormat: Cesium.VertexFormat.POSITION_ONLY, stackPartitions: 8, slicePartitions: 8 })); var sphereL2 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({ radius: radius, vertexFormat: Cesium.VertexFormat.POSITION_ONLY, stackPartitions: 16, slicePartitions: 16 })); var sphereL3 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({ radius: radius, vertexFormat: Cesium.VertexFormat.POSITION_ONLY, stackPartitions: 32, slicePartitions: 32 })); var sphereL4 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({ radius: radius, vertexFormat: Cesium.VertexFormat.POSITION_ONLY, stackPartitions: 64, slicePartitions: 64 })); var geometries = [ [sphereL4, 5], [sphereL3, 200], [sphereL2, 300], [sphereL1, 500], [sphereL0, 2000] ]; var maxAvailableDistance = 10000000; var i, j, mesh, lod; var scale = new Cesium.Cartesian3(1, 1, 1); for (j = 0; j < 1000; j++) { lod = new LOD(); for (i = 0; i < geometries.length; i++) { mesh = new Mesh(geometries[i][0], material); mesh.scale = scale; lod.addLevel(mesh, geometries[i][1] * 1000); } lod.maxAvailableDistance = maxAvailableDistance; lod.position.x = 1500000 * (0.5 - Math.random()); lod.position.y = 1750000 * (0.5 - Math.random()); lod.position.z = 130000 * (0.5 - Math.random()); meshVisualizer.add(lod); } */ class LOD { constructor(options?: { show?: boolean position?: Cesium.Cartesian3 rotation?: Cesium.Rotation scale?: Cesium.Cartesian3 }) show: boolean position: Cesium.Cartesian3 rotation: Cesium.Rotation scale: Cesium.Cartesian3 needsUpdate: boolean modelMatrix: Cesium.Matrix4 parent: Mesh | LOD | MeshVisualizer children: (Mesh | LOD) /** * *@param {Number}x *@param {Number}y *@param {Number}z */ setPosition: (x: number, y: number, z: number) => void /** * *@param {Number}x *@param {Number}y *@param {Number}z */ setScale: (x: number, y: number, z: number) => void /** *@param {Cesium.Mesh}mesh *@param {Number}distance */ addLevel: (object: Mesh | LOD, distance: number) => void update: ( /** * @type {Cesium.Matrix4} */ parentModelMatrix: Cesium.Matrix4, frameState: Cesium.FrameState) => void getObjectForDistance: (distance: number) => Mesh | LOD } /** *帧缓存纹理类,可以将一个mesh渲染到帧缓存并作为纹理提供给其他mesh。<br/> *需要配合{@link Cesium.MeshVisualizer}、{@link Cesium.Mesh}、{@link Cesium.MeshMaterial}使用。 *@param {Cesium.Mesh}mesh * *@property {Cesium.Mesh}mesh *@property {Cesium.Texture}texture *@property {Cesium.Texture}[depthTexture] * *@constructor *@memberof Cesium *@example MeshVisualizer = Cesium.MeshVisualizer; Mesh = Cesium.Mesh; MeshMaterial = Cesium.MeshMaterial; FramebufferTexture = Cesium.FramebufferTexture; Shaders = VolumeRendering.Shaders; var center2 = Cesium.Cartesian3.fromDegrees(homePosition[0]+3.5, homePosition[1] , 50000); var modelMatrix2 = Cesium.Transforms.eastNorthUpToFixedFrame(center2); var meshVisualizer = new MeshVisualizer({ modelMatrix: modelMatrix2, up: { y: 1 }, scale: new Cesium.Cartesian3(2,2,2) }); viewer.scene.primitives.add(meshVisualizer); var guiControls = new function () { this.model = 'bonsai'; this.steps = 256.0; this.alphaCorrection = 1.0; this.color1 = "#00FA58"; this.stepPos1 = 0.1; this.color2 = "#CC6600"; this.stepPos2 = 0.7; this.color3 = "#F2F200"; this.stepPos3 = 1.0; }; function updateTransferFunction() { var canvas = document.createElement('canvas'); canvas.height = 20; canvas.width = 256; var ctx = canvas.getContext('2d'); var grd = ctx.createLinearGradient(0, 0, canvas.width - 1, canvas.height - 1); grd.addColorStop(guiControls.stepPos1, guiControls.color1); grd.addColorStop(guiControls.stepPos2, guiControls.color2); grd.addColorStop(guiControls.stepPos3, guiControls.color3); ctx.fillStyle = grd; ctx.fillRect(0, 0, canvas.width - 1, canvas.height - 1); return canvas; } var dimensions = new Cesium.Cartesian3(50000, 50000, 50000); var boxGeometry = Cesium.BoxGeometry.createGeometry(Cesium.BoxGeometry.fromDimensions({ dimensions: dimensions, vertexFormat: Cesium.VertexFormat.POSITION_ONLY })); var materialFirstPass = new MeshMaterial({ vertexShader: Shaders.vertexShaderFirstPass, fragmentShader: Shaders.fragmentShaderFirstPass, side: MeshMaterial.Sides.BACK, uniforms: { dimensions: dimensions } }); var meshFirstPass = new Mesh(boxGeometry, materialFirstPass); var rtTexture = new FramebufferTexture(meshFirstPass);//这里使用FramebufferTexture var transferTexture = updateTransferFunction(); var materialSecondPass = new MeshMaterial({ vertexShader: Shaders.vertexShaderSecondPass, fragmentShader: Shaders.fragmentShaderSecondPass, side: MeshMaterial.Sides.FRONT, uniforms: { alpha: 1, dimensions: dimensions, tex: rtTexture, cubeTex: "./teapot.raw.png", transferTex: transferTexture, steps: guiControls.steps, alphaCorrection: guiControls.alphaCorrection } }); var meshSecondPass = new Mesh(boxGeometry, materialSecondPass); meshVisualizer.add(meshSecondPass); */ export class FramebufferTexture { /** * * @param mesh * @param renderTarget - Cesium.Texture */ constructor(mesh: Mesh, renderTarget: Cesium.Texture, depthTexture: Cesium.Texture) mesh: Mesh /** * @type {Cesium.Texture} */ texture: Cesium.Texture depthTexture: Cesium.Texture framebuffer: Cesium.Framebuffer ready: boolean readyPromise: Promise<FramebufferTexture> destroy: () => void } export class RendererUtils { /** *使用帧缓冲技术,执行渲染命令,渲染到纹理 *@param {Cesium.DrawCommand|Array<Cesium.DrawCommand>}drawCommand - type:Cesium.DrawCommand|Array<Cesium.DrawCommand> 渲染命令(集合) *@param {Cesium.FrameState}frameState - type:Cesium.FrameState 帧状态对象,可以从Cesium.Scene中获取 *@param {Cesium.Texture|Cesium.Framebuffer}outpuTexture - type:Cesium.Texture 将渲染到的目标纹理对象 *@param {Cesium.Texture}[outputDepthTexture] - type:Cesium.Texture 可选,输出的深度纹理 */ static renderToTexture: ( drawCommand: Cesium.DrawCommand | Cesium.DrawCommand[], frameState: Cesium.FrameState, outputTexture: Cesium.Texture | Cesium.Framebuffer, outputDepthTexture?: Cesium.Texture ) => void /** *使用帧缓冲技术,执行渲染命令,渲染到纹理并读取像素值,可以用于实现并行计算 *@param {Cesium.DrawCommand|Array<Cesium.DrawCommand>}drawCommand 渲染命令(集合) *@param {Cesium.FrameState}frameState 帧状态对象,可以从Cesium.Scene中获取 *@param {Cesium.Texture}outpuTexture 将渲染到的目标纹理对象 *@param {Object}[options] *@param {Array.<Number>}outputPixels *@return {Array.<Number>}outputPixels 输出的像素 */ static renderToPixels: ( drawCommand: Cesium.DrawCommand | Array<Cesium.DrawCommand>, frameState: Cesium.FrameState, outputTexture: Cesium.Texture, options: { x: number y: number width: number height: number /** * @type {Cesium.PixelDatatype} */ pixelDatatype: Cesium.PixelDatatype /** * @type {Cesium.PixelFormat} */ pixelFormat: Cesium.PixelFormat /** * @type {Cesium.Framebuffer} */ framebuffer?: Cesium.Framebuffer }, pixels: Array<Number> | TypedArray) => void /** * @param {Cesium.FrameState}frameState * @param {Object}[readState] * @param {number}readState.x * @param {number}readState.y * @param {number}readState.width * @param {number}readState.height * @param {Cesium.PixelDatatype}readState.pixelDatatype * @param {Cesium.PixelFormat}readState.pixelFormat * @param {ArrayBufferView}pixels * @return {ArrayBufferView} */ static readPixels: ( /** * @type {Cesium.FrameState} */ frameState: Cesium.FrameState, readState: { x: number y: number width: number height: number /** * @type {Cesium.PixelDatatype} */ pixelDatatype: Cesium.PixelDatatype /** * @type {Cesium.PixelFormat} */ pixelFormat: Cesium.PixelFormat /** * @type {Cesium.Framebuffer} */ framebuffer?: Cesium.Framebuffer }, pixels: number[] | ArrayBufferView) => void /** * *@param {Cesium.Matrix4}srcMatrix *@param {Cesium.Matrix4}dstMatrix *@return {Cesium.Matrix4} */ static yUp2Zup: (srcMatrix: Cesium.Matrix4, dstMatrix: Cesium.Matrix4) => Cesium.Matrix4 /** *平移、旋转或缩放,返回计算之后的模型转换矩阵 *@param {Cesium.Cartesian3}[translation=undefined] *@param {Object}[rotation=undefined] 旋转参数 *@param {Cesium.Cartesian3}[rotation.axis] 旋转轴 *@param {Number}[rotation.angle] 旋转角度 *@param {Cesium.Cartesian3}[rotation.scale] 缩放 *@param {Cesium.Matrix4}[outModelMatrix] 计算结果矩阵,和返回值一样,但是传递此参数时则返回值不是新创建的Cesium.Matrix4实例 *@return {Cesium.Matrix4} */ static computeModelMatrix: (srcModelMatrix: Cesium.Matrix4, translation: Cesium.Cartesian3, rotation: { axis: Cesium.Cartesian3, angle: number }, scale: Cesium.Cartesian3, outModelMatrix: Cesium.Matrix4) => Cesium.Matrix4 } /** * * *@param {Object}options *@param {Cesium.Matrix4}[options.modelMatrix=Cesium.Matrix4.IDENTITY] *@param {Cesium.Cartesian3}[options.up=Cesium.Cartesian3.UNIT_Z] *@param {Cesium.Cartesian3}[options.position=Cesium.Cartesian3.ZERO] *@param {Cesium.Cartesian3}[options.scale=new Cartesian3(1, 1, 1)] *@param {Cesium.Rotation}[options.rotation] *@param {Boolean}[options.show=true] *@param {Boolean}[options.showReference=true] *@param {Cesium.ArrowGeometry}[options.referenceAxisParameter] * *@property {Cesium.Matrix4}modelMatrix *@property {Cesium.Cartesian3}up *@property {Cesium.Cartesian3}position *@property {Cesium.Cartesian3}scale *@property {Cesium.Rotation}rotation *@property {Boolean}show *@property {Boolean}showReference *@property {Boolean}modelMatrixNeedsUpdate *@property {Cesium.Event}beforeUpdate * *@constructor *@memberof Cesium *@extends Cesium.Primitive * *@example MeshVisualizer = Cesium.MeshVisualizer; Mesh = Cesium.Mesh; MeshMaterial = Cesium.MeshMaterial; FramebufferTexture = Cesium.FramebufferTexture; var center = Cesium.Cartesian3.fromDegrees(homePosition[0], homePosition[1], 50000); var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center); var meshVisualizer = new MeshVisualizer({ modelMatrix: modelMatrix, }); viewer.scene.primitives.add(meshVisualizer); //示例1:Cesium.Geometry+Cesium.MeshMaterial组合 var box = Cesium.BoxGeometry.createGeometry(Cesium.BoxGeometry.fromDimensions({ dimensions: new Cesium.Cartesian3(100000, 50000, 50000), vertexFormat: Cesium.VertexFormat.POSITION_ONLY })); var material = new MeshMaterial({ defaultColor: "rgba(255,0,0,1.0)", wireframe: false, side: MeshMaterial.Sides.DOUBLE }); var boxMesh = new Mesh(box, material); meshVisualizer.add(boxMesh); //示例2:Cesium.CSG+Cesium.MeshMaterial组合,可以用Cesium.CSG做布尔运算并渲染运算结果 //首先使用Cesium创建球体 var sphere = new Cesium.SphereGeometry({ radius: 50000.0, vertexFormat: Cesium.VertexFormat.POSITION_ONLY }); sphere = Cesium.SphereGeometry.createGeometry(sphere); var sphereMesh = new Mesh(sphere, material); sphereMesh.position = new Cesium.Cartesian3(100000, 0, 0) meshVisualizer.add(sphereMesh); //将球体对象Cesium.SphereGeometry转成Cesium.CSG实例 sphere = CSG.toCSG(sphere); //将盒子对象转成Cesium.CSG实例 box = CSG.toCSG(box); //做布尔运算 var subResult = sphere.subtract(box); //渲染运算结果 var subResultMesh = new Mesh(subResult, material); subResultMesh.position = new Cesium.Cartesian3(700000, 0, 0) meshVisualizer.add(subResultMesh); //示例3:使用帧缓存作纹理,实际应用中如体绘制,风场流场绘制等等都可以运用此技术 function createGeometry() { var p1 = new Cesium.Cartesian3(-50000, 50000, 100); var p2 = new Cesium.Cartesian3(-50000, -50000, 100); var p3 = new Cesium.Cartesian3(50000, -50000, 100); var p4 = new Cesium.Cartesian3(50000, 50000, 100); var positions = new Float64Array([ p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, p3.x, p3.y, p3.z, p4.x, p4.y, p4.z ]); var indices = new Uint16Array([ 0, 1, 3, 1, 2, 3, ]); var sts = new Float32Array([ 1, 1, 1, 0, 0, 0, 0, 1 ]); var geometry = new Cesium.Geometry({ attributes: { position: new Cesium.GeometryAttribute({ componentDatatype: Cesium.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: positions }), st: new Cesium.GeometryAttribute({ componentDatatype: Cesium.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: sts }) }, indices: indices, primitiveType: Cesium.PrimitiveType.TRIANGLES, boundingSphere: Cesium.BoundingSphere.fromVertices(positions) }); return geometry; } //将上文中的盒子渲染到缓存,作为纹理参与createGeometry()方法创建的几何体渲染过程 var framebufferTex = new FramebufferTexture(boxMesh); var geometry = createGeometry(); var customMesh = new Mesh(geometry, new MeshMaterial({ uniforms: { u_textureMap: framebufferTex//Cesium.buildModuleUrl('Widgets/Images/TerrainProviders/STK.png') }, side: MeshMaterial.Sides.DOUBLE, vertexShader : "\n\ \n\ varying vec3 v_position;\n\ varying vec2 v_st;\n\ \n\ void main(void) \n\ {\n\ vec4 pos = u_modelViewMatrix * vec4(position,1.0);\n\ v_position = pos.xyz;\n\ v_st=st;\n\ gl_Position = u_projectionMatrix * pos;\n\ }", fragmentShader : "varying vec2 v_st;\ uniform sampler2D u_textureMap;\ void main()\ {\ gl_FragColor = texture2D(u_textureMap,v_st);\n\ \ }\ " })); customMesh.position = new Cesium.Cartesian3(100000, 0, 0); meshVisualizer.add(customMesh); */ export class MeshVisualizer { constructor(options: { modelMatrix?: Cesium.Matrix4 up?: Cesium.Cartesian3 position?: Cesium.Cartesian3 scale?: Cesium.Cartesian3 rotation?: Rotation show?: boolean showReference?: boolean referenceAxisParameter?: ArrowGeometry }) /** * @type {Cesium.Event} */ beforeUpdate: Cesium.Event children: (Mesh | LOD)[] /** * *@param {Cesium.Mesh}mesh */ add: (mesh: Mesh) => void /** *@param {Cesium.Mesh}mesh */ remove: (mesh: Mesh) => void /** * *拾取点,用局部坐标系表达。内部使用Cesium.Scene.pickPosition和MeshVisualizer.worldCoordinatesToLocal实现。 *@param {Cesium.Cartesian2}windowPosition *@param {Cesium.Cartesian3}[result] *@return {Cesium.Cartesian3} */ pickPosition: (windowPosition: Cesium.Cartesian2, result?: Cesium.Cartesian3) => Cesium.Cartesian3 /** * *创建一条射线,用局部坐标系表达 *@param {Cesium.Cartesian2}windowPosition *@param {Cesium.Ray}[result] *@return {Cesium.Ray} */ getPickRay: (windowPosition: Cesium.Cartesian2, result?: Cesium.Ray) => Cesium.Ray /** *世界坐标到局部坐标 *@param {Cesium.Cartesian3}worldCoordinates *@param {Cesium.Cartesian3}[result] *@return {Cesium.Cartesian3} */ worldCoordinatesToLocal: (worldCoordinates: Cesium.Cartesian3, result?: Cesium.Cartesian3) => Cesium.Cartesian3 /** *局部坐标到世界坐标 *@param {Cesium.Cartesian3}localCoordinates *@param {Cesium.Cartesian3}[result] *@return {Cesium.Cartesian3} */ localToWorldCoordinates: (localCoordinates: Cesium.Cartesian3, result?: Cesium.Cartesian3) => Cesium.Cartesian3 /** * *@param {Number}x *@param {Number}y *@param {Number}z */ setPosition: (x: number, y: number, z: number) => void /** * *@param {Number}x *@param {Number}y *@param {Number}z */ setScale: (x: number, y: number, z: number) => void createBoundingSphere: (mesh: Mesh) => void /** * *@param {Cesium.Mesh} mesh *@param {Cesium.FrameState} frameState *@return {Cesium.DrawCommand} *@private */ createDrawCommand: (mesh: Mesh, frameState: Cesium.FrameState) => Cesium.DrawCommand /** * * *@param {THREE.Material}material *@return {Cesium.RenderState}frameState *@private */ getRenderState: (material: MeshMaterial) => object /** * * *@param {THREE.Material}material *@param {Cesium.FrameState}frameState *@private */ getUniformMap: (material: MeshMaterial, frameState: Cesium.FrameState) => object /** * *@param {Cesium.Geometry} geometry *@param {Cesium.Material} material *@return {String} *@private */ getVertexShaderSource: (mesh: Mesh, material: MeshMaterial) => string /** * *@param {Cesium.Material} material *@return {String} *@private */ getFragmentShaderSource: (material: MeshMaterial) => string /** * *@param {Cesium.FrameState}frameState */ update: (frameState: Cesium.FrameState) => void /** *单独渲染frameBufferTexture中的mesh,最终更新frameBufferTexture中的texture *@param {Cesium.FrameState}frameState *@param {Cesium.FramebufferTexture}frameBufferTexture */ updateFrameBufferTexture: (frameState: Cesium.FrameState, frameBufferTexture: FramebufferTexture, viewport: { x: number, y: number, width: number, height: number }) => void /** *单独渲染frameBufferTexture中的mesh,最终更新frameBufferTexture中的texture,并读取缓冲区的像素,可以用于实现并行计算(参看MeshVisualizer.prototype.compute) *@param {Cesium.FrameState}frameState *@param {Cesium.FramebufferTexture}frameBufferTexture *@param {Object}[viewport] 可选,视口设置 *@param {Number}viewport.x 视口位置x坐标(屏幕坐标系,左上角为原点) *@param {Number}viewport.y 视口位置y坐标(屏幕坐标系,左上角为原点) *@param {Number}viewport.width 视口宽度 *@param {Number}viewport.height 视口高度 *@param {Cesium.PixelDatatype}[viewport.pixelDatatype=Cesium.PixelDatatype.UNSIGNED_BYTE] 输出数据中像素值的rgba各项的数据类型,注意:有的移动设备不支持浮点型 *@param {Object}[readState] 可选,读取设置 *@param {Number}readState.x 读取区域位置x坐标(屏幕坐标系,左上角为原点) *@param {Number}readState.y 读取区域位置y坐标(屏幕坐标系,左上角为原点) *@param {Number}readState.width 读取区域宽度 *@param {Number}readState.height 读取区域高度 *@param {Cesium.PixelDatatype}[readState.pixelDatatype=Cesium.PixelDatatype.UNSIGNED_BYTE] 输出数据中像素值的rgba各项的数据类型,注意:有的移动设备不支持浮点型 *@param {Array.<Number>}outputPixels *@return {Array.<Number>}outputPixels 输出的像素 */ getPixels: (frameState: Cesium.FrameState, frameBufferTexture: FramebufferTexture, viewport: { x: number y: number width: number height: number pixelDatatype: Cesium.PixelDatatype }, readState: { x: number y: number width: number height: number pixelDatatype: Cesium.PixelDatatype }, outputPixels: number[] | ArrayBufferView) => number[] | ArrayBufferView /** * */ destroy: () => void /** * *遍历节点 *@param {Cesium.MeshVisualizer|Cesium.Mesh}root *@param {Cesium.MeshVisualizer~TraverseCallback}traverseFunc 访问每个节点时回调该函数,进行相关操作。回调函数包含一个参数,traverseArgs,其中封装了一个属性cancelCurrent,可以通过改变此属性达到终止遍历当前节点的子节点 *@param {Boolean}visibleOnly visibleOnly为true时仅遍历可见的节点,如果父级节点不可见则不再访问其子节点 */ static traverse: (node: MeshVisualizer | Mesh | LOD, traverseFunc: ( node: Mesh | LOD | MeshVisualizer, traverseArgs: { /** * 为true时终止遍历当前节点的子节点 */ cancelCurrent: boolean /** * 为true时终止遍历,退出遍历循环 */ cancelAll: boolean }) => void, visibleOnly: boolean) => void } }
the_stack
import { TypeAssertion, TypeAssertionMap, TypeAssertionSetValue, ObjectAssertion, AssertionSymlink, SymbolResolverOperators, ResolveSymbolOptions, SymbolResolverContext } from '../types'; import * as operators from '../operators'; import { NumberPattern } from '../lib/util'; function mergeTypeAndSymlink(ty: TypeAssertion, link: AssertionSymlink): TypeAssertion { const link2 = {...link}; delete (link2 as any).kind; // NOTE: (TS>=4.0) TS2790: The operand of a 'delete' operator must be optional. delete (link2 as any).symlinkTargetName; // NOTE: (TS>=4.0) TS2790: The operand of a 'delete' operator must be optional. delete (link2 as any).memberTree; // NOTE: (TS>=4.0) TS2790: The operand of a 'delete' operator must be optional. return ({...ty, ...link2} as any as TypeAssertion); } function updateSchema(original: TypeAssertion, schema: TypeAssertionMap, ty: TypeAssertion, typeName: string | undefined) { if (typeName && schema.has(typeName)) { const z: TypeAssertionSetValue = schema.get(typeName) as TypeAssertionSetValue; if (z.ty === original) { schema.set(typeName, {...z, ty, resolved: true}); } } return ty; } export function resolveMemberNames( ty: TypeAssertion, rootSym: string, memberTreeSymbols: string[], memberPos: number): TypeAssertion { const addTypeName = (mt: TypeAssertion, typeName: string | undefined, memberSym: string) => { if (typeName) { return ({ ...mt, typeName: memberPos === 0 ? `${rootSym}.${memberTreeSymbols.join('.')}` : `${typeName}.${memberSym}`, }); } else { return mt; } }; for (let i = memberPos; i < memberTreeSymbols.length; i++) { const memberSym = memberTreeSymbols[i]; switch (ty.kind) { case 'optional': return resolveMemberNames(ty.optional, rootSym, memberTreeSymbols, i + 1); case 'object': for (const m of ty.members) { if (memberSym === m[0]) { return addTypeName( resolveMemberNames(m[1], rootSym, memberTreeSymbols, i + 1), ty.typeName, memberSym, ); } } if (ty.additionalProps) { for (const m of ty.additionalProps) { for (const k of m[0]) { switch (k) { case 'number': if (NumberPattern.test(memberSym)) { return resolveMemberNames(m[1], rootSym, memberTreeSymbols, i + 1); } break; case 'string': return resolveMemberNames(m[1], rootSym, memberTreeSymbols, i + 1); default: if (k.test(memberSym)) { return resolveMemberNames(m[1], rootSym, memberTreeSymbols, i + 1); } break; } } } } throw new Error(`Undefined member name is appeared: ${memberSym}`); case 'symlink': if (! ty.typeName) { throw new Error(`Reference of anonymous type is appeared: ${memberSym}`); } return ({ ...{ kind: 'symlink', symlinkTargetName: rootSym, name: memberSym, typeName: rootSym, }, ...(0 < memberTreeSymbols.length ? { memberTree: memberTreeSymbols, } : {}), }); default: // TODO: kind === 'operator' throw new Error(`Unsupported type kind is appeared: (kind:${ty.kind}).${memberSym}`); } } return ty; } export function resolveSymbols(schema: TypeAssertionMap, ty: TypeAssertion, ctx: SymbolResolverContext): TypeAssertion { const ctx2 = {...ctx, nestLevel: ctx.nestLevel + 1}; switch (ty.kind) { case 'symlink': { const x = schema.get(ty.symlinkTargetName); if (! x) { throw new Error(`Undefined symbol '${ty.symlinkTargetName}' is referred.`); } if (0 <= ctx.symlinkStack.findIndex(s => s === ty.symlinkTargetName)) { return ty; } const ty2 = {...ty}; let xTy = x.ty; if (ty.memberTree && 0 < ty.memberTree.length) { xTy = { ...resolveMemberNames(xTy, ty.symlinkTargetName, ty.memberTree, 0), }; ty2.typeName = xTy.typeName; } return ( resolveSymbols( schema, mergeTypeAndSymlink(xTy, ty2), {...ctx2, symlinkStack: [...ctx2.symlinkStack, ty2.symlinkTargetName]}, ) ); } case 'repeated': return updateSchema(ty, schema, { ...ty, repeated: resolveSymbols(schema, ty.repeated, ctx2), }, ty.typeName); case 'spread': return updateSchema(ty, schema, { ...ty, spread: resolveSymbols(schema, ty.spread, ctx2), }, ty.typeName); case 'sequence': return updateSchema(ty, schema, { ...ty, sequence: ty.sequence.map(x => resolveSymbols(schema, x, ctx2)), }, ty.typeName); case 'one-of': return updateSchema(ty, schema, { ...ty, oneOf: ty.oneOf.map(x => resolveSymbols(schema, x, ctx2)), }, ty.typeName); case 'optional': return updateSchema(ty, schema, { ...ty, optional: resolveSymbols(schema, ty.optional, ctx2), }, ty.typeName); case 'object': { if (0 < ctx.nestLevel && ty.typeName && 0 <= ctx.symlinkStack.findIndex(s => s === ty.typeName)) { if (schema.has(ty.typeName)) { const z = schema.get(ty.typeName) as TypeAssertionSetValue; if (z.resolved) { return z.ty; } } } const baseSymlinks = ty.baseTypes?.filter(x => x.kind === 'symlink') as AssertionSymlink[]; if (baseSymlinks && baseSymlinks.length > 0 && !ctx.isDeserialization) { const exts = baseSymlinks .map(x => resolveSymbols(schema, x, ctx2)) .filter(x => x.kind === 'object'); // TODO: if x.kind !== 'object' items exist -> error? const d2 = resolveSymbols( schema, operators.derived({ ...ty, ...(ty.baseTypes ? { baseTypes: ty.baseTypes.filter(x => x.kind !== 'symlink'), } : {}), }, ...exts), ty.typeName ? {...ctx2, symlinkStack: [...ctx2.symlinkStack, ty.typeName]} : ctx2, ); return updateSchema(ty, schema, { ...ty, ...d2, }, ty.typeName); } else { return updateSchema(ty, schema, { ...{ ...ty, members: ty.members .map(x => [ x[0], resolveSymbols(schema, x[1], ty.typeName ? {...ctx2, symlinkStack: [...ctx2.symlinkStack, ty.typeName]} : ctx2), ...x.slice(2), ] as any), }, ...(ty.additionalProps && 0 < ty.additionalProps.length ? { additionalProps: ty.additionalProps .map(x => [ x[0], resolveSymbols(schema, x[1], ty.typeName ? {...ctx2, symlinkStack: [...ctx2.symlinkStack, ty.typeName]} : ctx2), ...x.slice(2), ] as any), } : {}), ...(ty.baseTypes && 0 < ty.baseTypes.length ? { baseTypes: ctx.isDeserialization ? ty.baseTypes .map(x => x.kind === 'symlink' ? resolveSymbols(schema, x, ctx2) : x) .filter(x => x.kind === 'object') as ObjectAssertion[] : ty.baseTypes, } : {}), }, ty.typeName); } } case 'operator': if (ctx2.operators) { const ctx3 = ty.typeName ? {...ctx2, symlinkStack: [...ctx2.symlinkStack, ty.typeName]} : ctx2; const operands = ty.operands.map(x => { if (typeof x === 'object' && x.kind) { return resolveSymbols(schema, x, ctx3); } return x; }); if (0 < operands.filter(x => x && typeof x === 'object' && (x.kind === 'symlink' || x.kind === 'operator')).length) { throw new Error(`Unresolved type operator is found: ${ty.operator}`); } if (! ctx2.operators[ty.operator]) { throw new Error(`Undefined type operator is found: ${ty.operator}`); } const ty2 = {...ty}; delete (ty2 as any).operator; // NOTE: (TS>=4.0) TS2790: The operand of a 'delete' operator must be optional. delete (ty2 as any).operands; // NOTE: (TS>=4.0) TS2790: The operand of a 'delete' operator must be optional. return updateSchema( ty, schema, { ...ty2, ...resolveSymbols(schema, ctx2.operators[ty.operator](...operands), ctx3), }, ty.typeName, ); } else { return ty; } default: return ty; } } const resolverOps: SymbolResolverOperators = { picked: operators.picked, omit: operators.omit, partial: operators.partial, intersect: operators.intersect, subtract: operators.subtract, }; export function resolveSchema(schema: TypeAssertionMap, opts?: ResolveSymbolOptions): TypeAssertionMap { for (const ent of schema.entries()) { const ty = resolveSymbols(schema, ent[1].ty, {...opts, nestLevel: 0, symlinkStack: [ent[0]], operators: resolverOps}); ent[1].ty = ty; } return schema; }
the_stack
import * as validator from 'validator'; import { Meta } from '../base'; import { CustomValidation, StandardValidation } from '../context-items'; import { ContextBuilder } from '../context-builder'; import { body } from '../middlewares/validation-chain-builders'; import { validationResult } from '../validation-result'; import { Validators } from './validators'; import { ValidatorsImpl } from './validators-impl'; let chain: any; let builder: ContextBuilder; let validators: Validators<any>; beforeEach(() => { chain = {}; builder = new ContextBuilder(); jest.spyOn(builder, 'addItem'); validators = new ValidatorsImpl(builder, chain); }); it('has methods for all standard validators', () => { // Cast is here to workaround the lack of index signature const validatorModule = validator as any; Object.keys(validator) .filter((key): key is keyof Validators<any> => { return key.startsWith('is') && typeof validatorModule[key] === 'function'; }) .forEach(key => { expect(validators).toHaveProperty(key); const ret = validators[key].call(validators); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validatorModule[key], false, expect.any(Array)), ); }); validators.contains('foo'); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.contains, false, ['foo', undefined]), ); validators.equals('bar'); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.equals, false, ['bar']), ); validators.matches('baz'); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.matches, false, ['baz', undefined]), ); }); describe('#custom()', () => { it('adds custom validator to the context', () => { const validator = jest.fn(); const ret = validators.custom(validator); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith(new CustomValidation(validator, false)); }); }); describe('#exists()', () => { it('adds custom validator to the context', () => { const ret = validators.exists(); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith(new CustomValidation(expect.any(Function), false)); }); it('checks if context is not undefined by default', async () => { validators.exists(); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const exists = context.stack[0]; await exists.run(context, undefined, meta); await exists.run(context, null, meta); await exists.run(context, 0, meta); await exists.run(context, '', meta); await exists.run(context, false, meta); expect(context.errors).toHaveLength(1); }); it('checks if context is not falsy when checkFalsy is true', async () => { validators.exists({ checkFalsy: true }); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const exists = context.stack[0]; await exists.run(context, undefined, meta); await exists.run(context, null, meta); await exists.run(context, 0, meta); await exists.run(context, '', meta); await exists.run(context, false, meta); await exists.run(context, true, meta); expect(context.errors).toHaveLength(5); }); it('checks if context is not null when checkNull is true', async () => { validators.exists({ checkNull: true }); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const exists = context.stack[0]; await exists.run(context, undefined, meta); await exists.run(context, null, meta); expect(context.errors).toHaveLength(2); await exists.run(context, 0, meta); await exists.run(context, '', meta); await exists.run(context, false, meta); await exists.run(context, true, meta); expect(context.errors).toHaveLength(2); }); }); describe('#isAlpha()', () => { it('checks options.ignore transformation from string[] to string', () => { const ret = validators.isAlpha('it-IT', { ignore: ['b', 'a', 'r'] }); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.isAlpha, false, ['it-IT', { ignore: 'bar' }]), ); }); }); describe('default #isBoolean()', () => { it('adds validator to the context', () => { const ret = validators.isBoolean(); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.isBoolean, false, expect.any(Array)), ); }); it('checks if context is strict boolean', async () => { validators.isBoolean(); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isBoolean = context.stack[0]; await isBoolean.run(context, true, meta); await isBoolean.run(context, false, meta); await isBoolean.run(context, 'true', meta); await isBoolean.run(context, 'false', meta); await isBoolean.run(context, 1, meta); await isBoolean.run(context, 0, meta); // The two below are passing because we are using a StandardValidator which passes the value to `toString` await isBoolean.run(context, [false], meta); await isBoolean.run(context, ['true'], meta); expect(context.errors).toHaveLength(0); await isBoolean.run(context, 'no', meta); await isBoolean.run(context, 'True', meta); await isBoolean.run(context, 'False', meta); await isBoolean.run(context, 'yes', meta); expect(context.errors).toHaveLength(4); }); }); describe('strict #isBoolean()', () => { it('adds validator to the context', () => { const ret = validators.isBoolean({ strict: true }); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith(new CustomValidation(expect.any(Function), false)); }); it('checks if context is strict boolean', async () => { validators.isBoolean({ strict: true }); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isBoolean = context.stack[0]; await isBoolean.run(context, true, meta); await isBoolean.run(context, false, meta); expect(context.errors).toHaveLength(0); await isBoolean.run(context, 0, meta); await isBoolean.run(context, 'true', meta); await isBoolean.run(context, 'false', meta); // The two below are not passing because we are using a custom validator which takes the raw value and does not pass it through `toString` await isBoolean.run(context, [false], meta); await isBoolean.run(context, ['true'], meta); expect(context.errors).toHaveLength(5); }); }); describe('loose #isBoolean()', () => { it('adds validator to the context', () => { const ret = validators.isBoolean({ loose: true }); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.isBoolean, false, [{ loose: true }]), ); }); it('checks if context is strict boolean', async () => { validators.isBoolean({ loose: true }); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isBoolean = context.stack[0]; await isBoolean.run(context, true, meta); await isBoolean.run(context, false, meta); await isBoolean.run(context, 'true', meta); await isBoolean.run(context, 'false', meta); await isBoolean.run(context, 'no', meta); await isBoolean.run(context, 'True', meta); await isBoolean.run(context, 'False', meta); await isBoolean.run(context, 'FalSE', meta); await isBoolean.run(context, 'yes', meta); await isBoolean.run(context, 1, meta); await isBoolean.run(context, 0, meta); await isBoolean.run(context, [false], meta); await isBoolean.run(context, ['true'], meta); expect(context.errors).toHaveLength(0); }); }); describe('#isString()', () => { it('adds custom validator to the context', () => { const ret = validators.isString(); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith(new CustomValidation(expect.any(Function), false)); }); it('checks if context is string', async () => { validators.isString(); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isString = context.stack[0]; await isString.run(context, 'foo', meta); expect(context.errors).toHaveLength(0); await isString.run(context, 1, meta); await isString.run(context, true, meta); await isString.run(context, null, meta); await isString.run(context, undefined, meta); await isString.run(context, [], meta); expect(context.errors).toHaveLength(5); }); }); describe('#isObject()', () => { it('adds custom validator to the context', () => { const ret = validators.isObject(); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith(new CustomValidation(expect.any(Function), false)); }); it('checks if context is object', async () => { validators.isObject(); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isObject = context.stack[0]; await isObject.run(context, {}, meta); await isObject.run(context, { foo: 'foo' }, meta); expect(context.errors).toHaveLength(0); await isObject.run(context, 'foo', meta); await isObject.run(context, 5, meta); await isObject.run(context, true, meta); await isObject.run(context, null, meta); await isObject.run(context, undefined, meta); await isObject.run(context, ['foo'], meta); expect(context.errors).toHaveLength(6); }); it('checks if context is object with strict = false', async () => { validators.isObject({ strict: false }); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isObject = context.stack[0]; await isObject.run(context, {}, meta); await isObject.run(context, { foo: 'foo' }, meta); await isObject.run(context, ['foo'], meta); await isObject.run(context, null, meta); expect(context.errors).toHaveLength(0); await isObject.run(context, 'foo', meta); await isObject.run(context, 5, meta); await isObject.run(context, true, meta); await isObject.run(context, undefined, meta); expect(context.errors).toHaveLength(4); }); }); describe('#isArray()', () => { it('adds custom validator to the context', () => { const ret = validators.isArray(); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith(new CustomValidation(expect.any(Function), false)); }); it('checks if context is array', async () => { validators.isArray(); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isArray = context.stack[0]; await isArray.run(context, [], meta); expect(context.errors).toHaveLength(0); await isArray.run(context, 1, meta); await isArray.run(context, true, meta); await isArray.run(context, null, meta); await isArray.run(context, undefined, meta); await isArray.run(context, 'foo', meta); expect(context.errors).toHaveLength(5); }); it('checks if context is array of right length', async () => { validators.isArray({ min: 2, max: 5 }); const context = builder.build(); const meta: Meta = { req: {}, location: 'body', path: 'foo' }; const isArray = context.stack[0]; await isArray.run(context, [1, '2'], meta); await isArray.run(context, ['1', undefined, '3'], meta); await isArray.run(context, ['1', null, '3', '4', '5'], meta); expect(context.errors).toHaveLength(0); await isArray.run(context, [], meta); await isArray.run(context, ['1'], meta); await isArray.run(context, ['1', '2', '3', '4', '5', '6'], meta); expect(context.errors).toHaveLength(3); }); }); describe('#notEmpty()', () => { it('adds negated isEmpty() validator to the context', () => { const ret = validators.notEmpty(); expect(ret).toBe(chain); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.isEmpty, true, expect.any(Array)), ); }); }); describe('correctly merges validator.matches flags', () => { it('correctly uses modifiers and string', () => { validators.matches('baz', 'gi'); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.matches, false, ['baz', 'gi']), ); }); it('correctly uses modifiers and regex flags', () => { validators.matches(/baz/gi, 'm'); expect(builder.addItem).toHaveBeenCalledWith( new StandardValidation(validator.matches, false, ['baz', 'mgi']), ); }); }); describe('always correctly validates with validator.matches using the g flag', () => { const expectedErr = { value: 'fo157115', msg: 'INVALID USER FORMAT', param: 'user', location: 'body', }; [ { name: 'with valid value', user: 'it157115', expected: [] }, { name: 'with invalid value', user: 'fo157115', expected: [expectedErr, expectedErr, expectedErr], }, ].forEach(config => { it(config.name, async () => { const req = { body: { user: config.user } }; const validator = body('user') .toLowerCase() .matches(/^(it)(\d{6})$/g) .withMessage('INVALID USER FORMAT'); // try three times because per #1127 validation failed one other time let i = 0; const results = []; while (++i < 3) { await validator.run(req); results.push(...validationResult(req).array()); } expect(results).toEqual(config.expected); }); }); });
the_stack
import { assert } from "chai"; import * as path from "path"; import * as fs from "fs-extra"; import * as os from "os"; import * as dotnetUtils from "../utils/dotnet"; import { isLinux, isWindows } from "../../../../src/common/deps-checker/util/system"; import { DotnetChecker, DotnetVersion, } from "../../../../src/common/deps-checker/internal/dotnetChecker"; import { DepsChecker, DepsInfo, DepsType } from "../../../../src/common/deps-checker/depsChecker"; import { CheckerFactory } from "../../../../src/common/deps-checker/checkerFactory"; import { logger } from "../adapters/testLogger"; import { TestTelemetry } from "../adapters/testTelemetry"; import { assertPathEqual, commandExistsInPath, getExecutionPolicyForCurrentUser, setExecutionPolicyForCurrentUser, } from "../utils/common"; import * as sinon from "sinon"; import * as process from "process"; import "mocha"; describe("DotnetChecker E2E Test - first run", async () => { beforeEach(async function () { await dotnetUtils.cleanup(); // cleanup to make sure the environment is clean before test }); afterEach(async function (t) { // cleanup to make sure the environment is clean await dotnetUtils.cleanup(); }); it(".NET SDK is not installed, whether globally or in home dir", async function () { if (await commandExistsInPath(dotnetUtils.dotnetCommand)) { this.skip(); } const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ); const isInstalled = await dotnetChecker.isInstalled(); assert.isFalse(isInstalled, ".NET is not installed, but isInstalled() return true"); const depsInfo: DepsInfo = await dotnetChecker.getDepsInfo(); assert.isNotNull(depsInfo); assert.isFalse(depsInfo.isLinuxSupported, "Linux should not support .NET"); const res = await dotnetChecker.resolve(); assert.isTrue(res.isOk() && res.value); await verifyPrivateInstallation(dotnetChecker); }); it(".NET SDK is not installed and the user homedir contains special characters", async function () { if (isLinux() || (await commandExistsInPath(dotnetUtils.dotnetCommand))) { this.skip(); } // test for space and non-ASCII characters const specialUserName = "Aarón García"; const [resourceDir, cleanupCallback] = await dotnetUtils.createMockResourceDir(specialUserName); try { const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ) as DotnetChecker; sinon.stub(dotnetChecker, "getResourceDir").returns(resourceDir); const res = await dotnetChecker.resolve(); assert.isTrue(res.isOk() && res.value); await verifyPrivateInstallation(dotnetChecker); } finally { cleanupCallback(); } }); it(".NET SDK supported version is installed globally", async function () { if ( !(await dotnetUtils.hasAnyDotnetVersions( dotnetUtils.dotnetCommand, dotnetUtils.dotnetSupportedVersions )) ) { this.skip(); } const dotnetFullPath = await commandExistsInPath(dotnetUtils.dotnetCommand); assert.isNotNull(dotnetFullPath); const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ); assert.isTrue(await dotnetChecker.isInstalled()); const dotnetExecPathFromConfig = await dotnetUtils.getDotnetExecPathFromConfig( dotnetUtils.dotnetConfigPath ); assert.isNotNull(dotnetExecPathFromConfig); assert.isTrue( await dotnetUtils.hasAnyDotnetVersions( dotnetExecPathFromConfig!, dotnetUtils.dotnetSupportedVersions ) ); // test dotnet executable is from config file. assertPathEqual(dotnetExecPathFromConfig!, await dotnetChecker.command()); }); it(".NET SDK is too old", async function () { const has21 = await dotnetUtils.hasDotnetVersion( dotnetUtils.dotnetCommand, dotnetUtils.dotnetOldVersion ); const hasSupported = await dotnetUtils.hasAnyDotnetVersions( dotnetUtils.dotnetCommand, dotnetUtils.dotnetSupportedVersions ); if (!(has21 && !hasSupported)) { this.skip(); } if (isLinux()) { this.skip(); } assert.isTrue(await commandExistsInPath(dotnetUtils.dotnetCommand)); const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ); const res = await dotnetChecker.resolve(); assert.isTrue(res.isOk() && res.value); await verifyPrivateInstallation(dotnetChecker); }); it(".NET SDK installation failure and manually install", async function () { if (isLinux() || (await commandExistsInPath(dotnetUtils.dotnetCommand))) { this.skip(); } // DotnetChecker with mock dotnet-install script const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ) as DotnetChecker; const correctResourceDir = dotnetChecker.getResourceDir(); sinon.stub(dotnetChecker, "getResourceDir").returns(getErrorResourceDir()); const res = await dotnetChecker.resolve(); assert.isFalse(res.isOk() && res.value); await verifyInstallationFailed(dotnetChecker); // DotnetChecker with correct dotnet-install script sinon.stub(dotnetChecker, "getResourceDir").returns(correctResourceDir); // user manually install await dotnetUtils.withDotnet( dotnetChecker, DotnetVersion.v31, true, async (installedDotnetExecPath: string) => { // pre-check installed dotnet works assert.isTrue( await dotnetUtils.hasDotnetVersion( installedDotnetExecPath, dotnetUtils.dotnetInstallVersion ) ); await dotnetChecker.resolve(); assert.isTrue(await dotnetChecker.isInstalled()); const dotnetExecPath = await dotnetChecker.command(); assertPathEqual(dotnetExecPath, installedDotnetExecPath); assert.isTrue( await dotnetUtils.hasDotnetVersion(dotnetExecPath, dotnetUtils.dotnetInstallVersion) ); } ); }); describe("PowerShell ExecutionPolicy is default on Windows", async () => { if (!isWindows()) { return; } let originalExecutionPolicy = "Unrestricted"; beforeEach(async function () { originalExecutionPolicy = await getExecutionPolicyForCurrentUser(); await setExecutionPolicyForCurrentUser("Restricted"); }); afterEach(async function () { await setExecutionPolicyForCurrentUser(originalExecutionPolicy); }); it(".NET SDK not installed and PowerShell ExecutionPolicy is default (Restricted) on Windows", async function () { if (await commandExistsInPath(dotnetUtils.dotnetCommand)) { this.skip(); } const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ); const res = await dotnetChecker.resolve(); assert.isTrue(res.isOk() && res.value); await verifyPrivateInstallation(dotnetChecker); }); }); }); describe("DotnetChecker E2E Test - second run", () => { beforeEach(async function () { await dotnetUtils.cleanup(); // cleanup to make sure the environment is clean before test }); beforeEach(async function () { // cleanup to make sure the environment is clean await dotnetUtils.cleanup(); }); it("Valid dotnet.json file", async function () { if (await commandExistsInPath(dotnetUtils.dotnetCommand)) { this.skip(); } const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ) as DotnetChecker; await dotnetUtils.withDotnet( dotnetChecker, DotnetVersion.v31, false, async (installedDotnetExecPath: string) => { // pre-check installed dotnet works assert.isTrue( await dotnetUtils.hasDotnetVersion( installedDotnetExecPath, dotnetUtils.dotnetInstallVersion ) ); // setup config file await fs.mkdirp(path.resolve(dotnetUtils.dotnetConfigPath, "..")); await fs.writeJson( dotnetUtils.dotnetConfigPath, { dotnetExecutablePath: installedDotnetExecPath }, { encoding: "utf-8", spaces: 4, EOL: os.EOL, } ); const res = await dotnetChecker.resolve(); const dotnetExecPath = await dotnetChecker.command(); assert.isTrue(res.isOk() && res.value); assertPathEqual(dotnetExecPath, installedDotnetExecPath); assert.isTrue( await dotnetUtils.hasDotnetVersion(dotnetExecPath, dotnetUtils.dotnetInstallVersion) ); } ); }); it("Invalid dotnet.json file and .NET SDK not installed", async function () { if (await commandExistsInPath(dotnetUtils.dotnetCommand)) { this.skip(); } // setup config file const invalidPath = "/this/path/does/not/exist"; await fs.mkdirp(path.resolve(dotnetUtils.dotnetConfigPath, "..")); await fs.writeJson( dotnetUtils.dotnetConfigPath, { dotnetExecutablePath: invalidPath }, { encoding: "utf-8", spaces: 4, EOL: os.EOL, } ); const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ); const res = await dotnetChecker.resolve(); assert.isTrue(res.isOk() && res.value); await verifyPrivateInstallation(dotnetChecker); }); it("Invalid dotnet.json file and .NET SDK installed", async function () { if (await commandExistsInPath(dotnetUtils.dotnetCommand)) { this.skip(); } const dotnetChecker = CheckerFactory.createChecker( DepsType.Dotnet, logger, new TestTelemetry() ) as DotnetChecker; await dotnetUtils.withDotnet( dotnetChecker, DotnetVersion.v31, true, async (installedDotnetExecPath: string) => { const invalidPath = "/this/path/does/not/exist"; // setup config file await fs.mkdirp(path.resolve(dotnetUtils.dotnetConfigPath, "..")); await fs.writeJson( dotnetUtils.dotnetConfigPath, { dotnetExecutablePath: invalidPath }, { encoding: "utf-8", spaces: 4, EOL: os.EOL, } ); const res = await dotnetChecker.resolve(); const dotnetExecPath = await dotnetChecker.command(); const dotnetExecPathFromConfig = await dotnetUtils.getDotnetExecPathFromConfig( dotnetUtils.dotnetConfigPath ); assert.isTrue(res.isOk() && res.value); assertPathEqual(dotnetExecPath, installedDotnetExecPath); assert.isNotNull(dotnetExecPathFromConfig); assertPathEqual(dotnetExecPath, dotnetExecPathFromConfig!); assert.isTrue( await dotnetUtils.hasDotnetVersion(dotnetExecPath, dotnetUtils.dotnetInstallVersion) ); } ); }); }); async function verifyPrivateInstallation(dotnetChecker: DepsChecker) { assert.isTrue(await dotnetChecker.isInstalled(), ".NET installation failed"); assert.isTrue( await dotnetUtils.hasDotnetVersion( await dotnetChecker.command(), dotnetUtils.dotnetInstallVersion ) ); // validate dotnet config file const dotnetExecPath = await dotnetUtils.getDotnetExecPathFromConfig( dotnetUtils.dotnetConfigPath ); assert.isNotNull(dotnetExecPath); assert.isTrue( await dotnetUtils.hasDotnetVersion(dotnetExecPath!, dotnetUtils.dotnetInstallVersion) ); } async function verifyInstallationFailed(dotnetChecker: DepsChecker) { assert.isFalse(await dotnetChecker.isInstalled()); assert.isNull(await dotnetUtils.getDotnetExecPathFromConfig(dotnetUtils.dotnetConfigPath)); assert.equal(await dotnetChecker.command(), dotnetUtils.dotnetCommand); } function getErrorResourceDir(): string { process.env["ENV_CHECKER_CUSTOM_SCRIPT_STDOUT"] = "mock dotnet installing"; process.env["ENV_CHECKER_CUSTOM_SCRIPT_STDERR"] = "mock dotnet install failure"; process.env["ENV_CHECKER_CUSTOM_SCRIPT_EXITCODE"] = "1"; return path.resolve(__dirname, "../resource"); }
the_stack
import { DrawCommands } from './Graphics'; import { TweenProps, KeyframeData, TweenData, TweenablePropNames } from './Tween'; import { MovieClip } from './MovieClip'; import { DisplayObject } from '@pixi/display'; import { Renderer } from '@pixi/core'; import { Prepare } from '@pixi/prepare'; // If the movieclip plugin is installed let _prepare: Prepare = null; /* eslint-disable @typescript-eslint/no-namespace, no-inner-declarations */ // awkwardly named instead of the final export of 'utils' to avoid problems in .d.ts build tools. export namespace utils { /** * Convert the Hexidecimal string (e.g., "#fff") to uint */ export function hexToUint(hex: string): number { // Remove the hash hex = hex.substr(1); // Convert shortcolors fc9 to ffcc99 if (hex.length === 3) { hex = hex.replace(/([a-f0-9])/g, '$1$1'); } return parseInt(hex, 16); } /** * Fill frames with booleans of true (showing) and false (hidden). * @param timeline * @param startFrame The start frame when the timeline shows up * @param duration The length of showing */ export function fillFrames(timeline: boolean[], startFrame: number, duration: number): void { // ensure that the timeline is long enough const oldLength = timeline.length; if (oldLength < startFrame + duration) { timeline.length = startFrame + duration; // fill any gaps with false to denote that the child should be removed for a bit if (oldLength < startFrame) { // if the browser has implemented the ES6 fill() function, use that if (timeline.fill) { timeline.fill(false, oldLength, startFrame); } else { // if we can't use fill, then do a for loop to fill it for (let i = oldLength; i < startFrame; ++i) { timeline[i] = false; } } } } // if the browser has implemented the ES6 fill() function, use that if (timeline.fill) { timeline.fill(true, startFrame, startFrame + duration); } else { const length = timeline.length; // if we can't use fill, then do a for loop to fill it for (let i = startFrame; i < length; ++i) { timeline[i] = true; } } } const keysMap: {[s: string]: keyof TweenProps} = { X: 'x', // x position Y: 'y', // y position A: 'sx', // scale x B: 'sy', // scale y C: 'kx', // skew x D: 'ky', // skew y R: 'r', // rotation L: 'a', // alpha T: 't', // tint F: 'c', // colorTransform V: 'v', // visibility }; /** * Parse the value of the compressed keyframe. * @param prop The property key * @param buffer The contents * @return The parsed value */ function parseValue(prop: string, buffer: string): string|number|boolean|(string|number)[] { switch (prop) { // Color transforms are parsed as an array case 'c': { const buff: (string|number)[] = buffer.split(','); buff.forEach((val, i, buffer) => { buffer[i] = parseFloat(val as string); }); return buff; } // Tint value should not be converted // can be color uint or string case 't': { return buffer; } // The visiblity parse as boolean case 'v': { return !!parseInt(buffer, 10); } // Everything else parse a floats default: { return parseFloat(buffer); } } } const tweenKeysMap: { [s: string]: keyof TweenData } = { D: 'd', // duration // E: 'e', // easing - disabled for manual handling P: 'p', // props }; /** * Regex to test for a basic ease desccriptor */ const basicEase = /(\-?\d*\.?\d*)([a-zA-Z]+)/; /** * Convert serialized tween from a serialized keyframe into TweenData * `"D20E25EaseIn;PX3Y5A1.2"` to: `{ d: 20, e: { s: 25, n: "EaseIn" }, p: { x:3, y: 5, sx: 1.2 } }` * @param tweenBuffer * @return Resulting TweenData */ function parseTween(tweenBuffer: string): TweenData { const result: TweenData = { d: 0, p: {} }; let i = 0; let buffer = ''; let handlingProps = false; let prop: keyof TweenProps|keyof TweenData; // tween format: // D20E25EaseIn;PX3Y5A1.2 while (i <= tweenBuffer.length) { const c = tweenBuffer[i]; if (!handlingProps && (tweenKeysMap[prop] || tweenKeysMap[c])) { // handle potential active duration property, which is the only normal one if (prop === 'd') { (result.d as any) = parseValue(prop, buffer); prop = null; } // seeing the p property kicks us immediately into props mode if (c === 'P') { handlingProps = true; ++i; } else { // only handles D, really prop = tweenKeysMap[c]; ++i; } buffer = ''; } // seeing easing means we need to read ahead to the end of the easing section else if (c === 'E') { // search for the next space or end of the string to see where the tween ends let index = tweenBuffer.indexOf(';', i); // should never end early, but just in case we are somehow tweening 0 properties if (index < 0) { index = tweenBuffer.length; } const easeBuffer = tweenBuffer.substring(i + 1, index); if (basicEase.test(easeBuffer)) { const [, strength, name] = basicEase.exec(easeBuffer); // if not yet handling props, apply ease to whole tween if (!handlingProps) { result.e = { s: parseFloat(strength), n: name, }; } // apply ease to last property read else if (prop) { (result.p[prop as TweenablePropNames] as any) = parseValue(prop, buffer); if (!result.p.e) { result.p.e = {}; } result.p.e[prop as TweenablePropNames] = { s: parseFloat(strength), n: name, }; prop = null; buffer = ''; } } else { // TODO: encode some sort of function for a custom ease } i = index + 1; } // normal prop/buffer handling, like in the main deserializeKeyframes function else if (keysMap[c]) { if (prop) { (result.p[prop as keyof TweenProps] as any) = parseValue(prop, buffer); } prop = keysMap[c]; buffer = ''; i++; } else if (!c) { if (prop) { (result.p[prop as keyof TweenProps] as any) = parseValue(prop, buffer); } buffer = ''; prop = null; i++; } else { buffer += c; i++; } } return result; } /** * Convert serialized array into keyframes * `"0x100y100 1x150"` to: `{ "0": {"x":100, "y": 100}, "1": {"x": 150} }` * @param keyframes * @return Resulting keyframes */ export function deserializeKeyframes(keyframes: string): {[s: number]: KeyframeData} { const result: {[s: number]: KeyframeData} = {}; let i = 0; let buffer = ''; let isFrameStarted = false; let prop: keyof TweenProps; let frame: KeyframeData = {}; while (i <= keyframes.length) { const c = keyframes[i]; // if we found the name of a property if (keysMap[c]) { // start a new frame if we need to if (!isFrameStarted) { isFrameStarted = true; result[buffer as any] = frame; } // finish a previous prop if one is running if (prop) { (frame[prop] as any) = parseValue(prop, buffer); } // save the new prop that we are now handling prop = keysMap[c]; // reset buffer (because we did the previous prop if we had to) buffer = ''; i++; } // contains a tween else if (c === 'W') { // start a new frame if we need to if (!isFrameStarted) { isFrameStarted = true; result[buffer as any] = frame; } // finish previous prop if (prop) { (frame[prop] as any) = parseValue(prop, buffer); buffer = ''; prop = null; } // search for the next space or end of the string to see where the tween ends let index = keyframes.indexOf(' ', i); if (index < 0) { index = keyframes.length; } // parse the tween section frame.tw = parseTween(keyframes.substring(i + 1, index)); // skip past the tween section i = index; } // finish existing prop & frame on end of string or space else if (!c || c === ' ') { i++; if (prop) { (frame[prop] as any) = parseValue(prop, buffer); } buffer = ''; prop = null; frame = {}; isFrameStarted = false; } // add to the buffer for the next parse else { buffer += c; i++; } } return result; } /** * Convert serialized shapes into draw commands for PIXI.Graphics. * @param str * @param Resulting shapes map */ export function deserializeShapes(str: string): DrawCommands[] { const result = []; // each shape is a new line const shapes = str.split('\n'); const isCommand = /^[a-z]{1,2}$/; for (let i = 0; i < shapes.length; i++) { const shape: DrawCommands = shapes[i].split(' '); // arguments are space separated for (let j = 0; j < shape.length; j++) { // Convert all numbers to floats, ignore colors const arg = shape[j] as string; if (arg[0] !== '#' && !isCommand.test(arg)) { shape[j] = parseFloat(arg); } } result.push(shape); } return result; } /** * Add movie clips to the upload prepare. * @param {*} item To add to the queue */ export function addMovieClips(item: any): boolean { if (item instanceof MovieClip) { item._timedChildTimelines.forEach((timeline) => { const index = item.children.indexOf(timeline.target); if (index === -1) { // eslint-disable-next-line no-unused-expressions _prepare?.add(timeline.target); } }); return true; } return false; } /** * Upload all the textures and graphics to the GPU. * @param renderer Render to upload to * @param clip MovieClip to upload * @param done When complete */ export function upload(renderer: Renderer, displayObject: DisplayObject, done: () => void): void { if (!_prepare) { _prepare = renderer.plugins.prepare; _prepare.registerFindHook(addMovieClips); } // eslint-disable-next-line no-unused-expressions _prepare?.upload(displayObject, done); } }
the_stack
import { Arbitrary } from '../../../../src/check/arbitrary/definition/Arbitrary'; import { Shrinkable } from '../../../../src/check/arbitrary/definition/Shrinkable'; import { asyncProperty } from '../../../../src/check/property/AsyncProperty'; import { pre } from '../../../../src/check/precondition/Pre'; import { PreconditionFailure } from '../../../../src/check/precondition/PreconditionFailure'; import { configureGlobal, resetConfigureGlobal } from '../../../../src/check/runner/configuration/GlobalParameters'; import * as stubArb from '../../stubs/arbitraries'; import * as stubRng from '../../stubs/generators'; import { NextValue } from '../../../../src/check/arbitrary/definition/NextValue'; import { fakeNextArbitrary } from '../../arbitrary/__test-helpers__/NextArbitraryHelpers'; import { convertToNextProperty } from '../../../../src/check/property/ConvertersProperty'; import { convertFromNext } from '../../../../src/check/arbitrary/definition/Converters'; import { Stream } from '../../../../src/stream/Stream'; describe('AsyncProperty', () => { afterEach(() => resetConfigureGlobal()); it('Should fail if predicate fails', async () => { const p = asyncProperty(stubArb.single(8), async (_arg: number) => { return false; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); // property fails }); it('Should fail if predicate throws', async () => { const p = asyncProperty(stubArb.single(8), async (_arg: number) => { throw 'predicate throws'; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toEqual('predicate throws'); }); it('Should fail if predicate throws an Error', async () => { const p = asyncProperty(stubArb.single(8), async (_arg: number) => { throw new Error('predicate throws'); }); const out = await p.run(p.generate(stubRng.mutable.nocall()).value); expect(out).toContain('predicate throws'); expect(out).toContain('\n\nStack trace:'); }); it('Should forward failure of runs with failing precondition', async () => { let doNotResetThisValue = false; const p = asyncProperty(stubArb.single(8), async (_arg: number) => { pre(false); doNotResetThisValue = true; return false; }); const out = await p.run(p.generate(stubRng.mutable.nocall()).value); expect(PreconditionFailure.isFailure(out)).toBe(true); expect(doNotResetThisValue).toBe(false); // does not run code after the failing precondition }); it('Should succeed if predicate is true', async () => { const p = asyncProperty(stubArb.single(8), async (_arg: number) => { return true; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should succeed if predicate does not return anything', async () => { const p = asyncProperty(stubArb.single(8), async (_arg: number) => {}); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should wait until completion of the check to follow', async () => { const delay = () => new Promise((resolve) => setTimeout(resolve, 0)); let runnerHasCompleted = false; let resolvePromise: (t: boolean) => void = null as any as (t: boolean) => void; const p = asyncProperty(stubArb.single(8), async (_arg: number) => { return await new Promise<boolean>(function (resolve) { resolvePromise = resolve; }); }); const runner = p.run(p.generate(stubRng.mutable.nocall()).value); runner.then(() => (runnerHasCompleted = true)); await delay(); // give back the control for other threads expect(runnerHasCompleted).toBe(false); resolvePromise(true); await delay(); // give back the control for other threads expect(runnerHasCompleted).toBe(true); expect(await runner).toBe(null); // property success }); it('Should throw on invalid arbitrary', () => expect(() => asyncProperty(stubArb.single(8), stubArb.single(8), {} as Arbitrary<any>, async () => {}) ).toThrowError()); it('Should use the unbiased arbitrary by default', () => { const p = asyncProperty( new (class extends Arbitrary<number> { generate(): Shrinkable<number> { return new Shrinkable(69); } withBias(): Arbitrary<number> { throw 'Should not call withBias if not forced to'; } })(), async () => {} ); expect(p.generate(stubRng.mutable.nocall()).value).toEqual([69]); }); it('Should use the biased arbitrary when asked to', () => { const p = asyncProperty( new (class extends Arbitrary<number> { generate(): Shrinkable<number> { return new Shrinkable(69); } withBias(freq: number): Arbitrary<number> { if (typeof freq !== 'number' || freq < 2) { throw new Error(`freq atribute must always be superior or equal to 2, got: ${freq}`); } return new (class extends Arbitrary<number> { generate(): Shrinkable<number> { return new Shrinkable(42); } })(); } })(), async () => {} ); expect(p.generate(stubRng.mutable.nocall(), 0).value).toEqual([42]); expect(p.generate(stubRng.mutable.nocall(), 2).value).toEqual([42]); }); it('Should always execute beforeEach before the test', async () => { const prob = { beforeEachCalled: false }; const p = asyncProperty(stubArb.single(8), async (_arg: number) => { const beforeEachCalled = prob.beforeEachCalled; prob.beforeEachCalled = false; return beforeEachCalled; }).beforeEach(async (globalBeforeEach) => { prob.beforeEachCalled = true; await globalBeforeEach(); }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should execute both global and local beforeEach hooks before the test', async () => { const globalAsyncBeforeEach = jest.fn(); const prob = { beforeEachCalled: false }; configureGlobal({ asyncBeforeEach: globalAsyncBeforeEach, }); const p = asyncProperty(stubArb.single(8), async (_arg: number) => { const beforeEachCalled = prob.beforeEachCalled; prob.beforeEachCalled = false; return beforeEachCalled; }) .beforeEach(async (globalBeforeEach) => { prob.beforeEachCalled = false; await globalBeforeEach(); }) .beforeEach(async (previousBeforeEach) => { await previousBeforeEach(); prob.beforeEachCalled = true; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); expect(globalAsyncBeforeEach).toBeCalledTimes(1); }); it('Should use global asyncBeforeEach as default if specified', async () => { const prob = { beforeEachCalled: false }; configureGlobal({ asyncBeforeEach: () => (prob.beforeEachCalled = true), }); const p = asyncProperty(stubArb.single(8), async (_arg: number) => { const beforeEachCalled = prob.beforeEachCalled; prob.beforeEachCalled = false; return beforeEachCalled; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should use global beforeEach as default if specified', async () => { const prob = { beforeEachCalled: false }; configureGlobal({ beforeEach: () => (prob.beforeEachCalled = true), }); const p = asyncProperty(stubArb.single(8), async (_arg: number) => { const beforeEachCalled = prob.beforeEachCalled; prob.beforeEachCalled = false; return beforeEachCalled; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should fail if both global asyncBeforeEach and beforeEach are specified', () => { configureGlobal({ asyncBeforeEach: () => {}, beforeEach: () => {}, }); expect(() => asyncProperty(stubArb.single(8), async () => {})).toThrowError( 'Global "asyncBeforeEach" and "beforeEach" parameters can\'t be set at the same time when running async properties' ); }); it('Should execute afterEach after the test on success', async () => { const callOrder: string[] = []; const p = asyncProperty(stubArb.single(8), async (_arg: number) => { callOrder.push('test'); return true; }).afterEach(async () => { callOrder.push('afterEach'); }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); expect(callOrder).toEqual(['test', 'afterEach']); }); it('Should execute afterEach after the test on failure', async () => { const callOrder: string[] = []; const p = asyncProperty(stubArb.single(8), async (_arg: number) => { callOrder.push('test'); return false; }).afterEach(async () => { callOrder.push('afterEach'); }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); expect(callOrder).toEqual(['test', 'afterEach']); }); it('Should execute afterEach after the test on uncaught exception', async () => { const callOrder: string[] = []; const p = asyncProperty(stubArb.single(8), async (_arg: number) => { callOrder.push('test'); throw new Error('uncaught'); }).afterEach(async () => { callOrder.push('afterEach'); }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); expect(callOrder).toEqual(['test', 'afterEach']); }); it('Should use global asyncAfterEach as default if specified', async () => { const callOrder: string[] = []; configureGlobal({ asyncAfterEach: async () => callOrder.push('globalAsyncAfterEach'), }); const p = asyncProperty(stubArb.single(8), async (_arg: number) => { callOrder.push('test'); return false; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); expect(callOrder).toEqual(['test', 'globalAsyncAfterEach']); }); it('Should use global afterEach as default if specified', async () => { const callOrder: string[] = []; configureGlobal({ afterEach: async () => callOrder.push('globalAfterEach'), }); const p = asyncProperty(stubArb.single(8), async (_arg: number) => { callOrder.push('test'); return false; }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); expect(callOrder).toEqual(['test', 'globalAfterEach']); }); it('Should execute both global and local afterEach hooks', async () => { const callOrder: string[] = []; configureGlobal({ asyncAfterEach: async () => callOrder.push('globalAsyncAfterEach'), }); const p = asyncProperty(stubArb.single(8), async (_arg: number) => { callOrder.push('test'); return true; }) .afterEach(async (globalAfterEach) => { callOrder.push('afterEach'); await globalAfterEach(); }) .afterEach(async (previousAfterEach) => { await previousAfterEach(); callOrder.push('after afterEach'); }); expect(await p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); expect(callOrder).toEqual(['test', 'afterEach', 'globalAsyncAfterEach', 'after afterEach']); }); it('Should fail if both global asyncAfterEach and afterEach are specified', () => { configureGlobal({ asyncAfterEach: () => {}, afterEach: () => {}, }); expect(() => asyncProperty(stubArb.single(8), async () => {})).toThrowError( 'Global "asyncAfterEach" and "afterEach" parameters can\'t be set at the same time when running async properties' ); }); it('should not call shrink on the arbitrary if no context and not unhandled value', () => { // Arrange const { instance: arb, shrink, canShrinkWithoutContext } = fakeNextArbitrary(); canShrinkWithoutContext.mockReturnValue(false); const value = Symbol(); // Act const p = convertToNextProperty(asyncProperty(convertFromNext(arb), jest.fn())); const shrinks = p.shrink(new NextValue([value], undefined)); // context=undefined in the case of user defined values // Assert expect(canShrinkWithoutContext).toHaveBeenCalledWith(value); expect(canShrinkWithoutContext).toHaveBeenCalledTimes(1); expect(shrink).not.toHaveBeenCalled(); expect([...shrinks]).toEqual([]); }); it('should call shrink on the arbitrary if no context but properly handled value', () => { // Arrange const { instance: arb, shrink, canShrinkWithoutContext } = fakeNextArbitrary(); canShrinkWithoutContext.mockReturnValue(true); const s1 = Symbol(); const s2 = Symbol(); shrink.mockReturnValue(Stream.of(new NextValue<symbol>(s1, undefined), new NextValue(s2, undefined))); const value = Symbol(); // Act const p = convertToNextProperty(asyncProperty(convertFromNext(arb), jest.fn())); const shrinks = p.shrink(new NextValue([value], undefined)); // context=undefined in the case of user defined values // Assert expect(canShrinkWithoutContext).toHaveBeenCalledWith(value); expect(canShrinkWithoutContext).toHaveBeenCalledTimes(1); expect(shrink).toHaveBeenCalledWith(value, undefined); expect(shrink).toHaveBeenCalledTimes(1); expect([...shrinks].map((s) => s.value_)).toEqual([[s1], [s2]]); }); });
the_stack
import React from 'react'; import { mount, shallow } from 'enzyme'; import assert from 'assert'; import sinon from 'sinon'; import _ from 'lodash'; import { common } from '../../util/generic-tests'; import { DropMenuDumb as DropMenu } from './DropMenu'; import ContextMenu from '../ContextMenu/ContextMenu'; import * as KEYCODE from '../../constants/key-code'; const { Control, Header, Option, OptionGroup, NullOption } = DropMenu as any; describe('DropMenu', () => { common(DropMenu); describe('render', () => { it('should render a ContextMenu', () => { const wrapper = shallow( <DropMenu isExpanded> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); assert.equal(wrapper.find('ContextMenu').length, 1); }); }); describe('props', () => { describe('children', () => { it('should not render any direct child elements which are not DropMenu-specific', () => { const wrapper = shallow( <DropMenu className='MyDropMenu'> <button>button</button> <Control> control <i>italic</i> </Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> <h1>header</h1> </DropMenu> ); assert.equal(wrapper.find('button').length, 0); assert.equal(wrapper.find('h1').length, 0); assert.equal(wrapper.find('i').length, 1); }); }); describe('className', () => { it('should pass the className prop thru to the root element', () => { const wrapper = shallow( <DropMenu className='MyDropMenu'> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const dropMenuClassName = wrapper.first().prop('className'); assert(_.includes(dropMenuClassName, 'MyDropMenu')); }); describe('FlyOut', () => { let wrapper: any; afterEach(() => { if (wrapper) { wrapper.unmount(); } }); it('should pass the className prop thru to the FlyOut (portal) element', () => { wrapper = mount( <DropMenu isExpanded className='MyDropMenu'> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const flyOutClassName = (document as any).querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut' ).className; assert(_.includes(flyOutClassName, 'MyDropMenu')); }); }); }); describe('style', () => { it('should pass the style prop thru to the root element', () => { const wrapper = shallow( <DropMenu style={{ flex: 2 }}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const dropMenuStyle = wrapper.first().prop('style'); assert( _.isEqual(dropMenuStyle, { flex: 2, }) ); }); }); describe('isDisabled', () => { it('should make the control handle `onClick`, `onKeyDown`, and have a `tabIndex` when `false`', () => { const wrapper = shallow( <DropMenu isDisabled={false}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const controlElement = wrapper.find('.lucid-DropMenu-Control'); assert(!_.isNil(controlElement.prop('tabIndex'))); assert(!_.isNil(controlElement.prop('onClick'))); assert(!_.isNil(controlElement.prop('onKeyDown'))); }); it('should make the control not handle `onClick`, `onKeydown`, or have a `tabIndex` when `true`', () => { const wrapper = shallow( <DropMenu isDisabled={true}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const controlElement = wrapper.find('.lucid-DropMenu-Control'); assert(_.isNil(controlElement.prop('tabIndex'))); assert(_.isNil(controlElement.prop('onClick'))); assert(_.isNil(controlElement.prop('onKeyDown'))); }); }); describe('isExpanded', () => { it('should pass isExpanded to the underlying ContextMenu component thru props', () => { const wrapper = shallow( <DropMenu isExpanded> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const contextMenuIsExpanded = wrapper .find('ContextMenu') .prop('isExpanded'); assert.equal(contextMenuIsExpanded, true); }); }); describe('direction', () => { it('should pass the direction to the underlying ContextMenu component thru props', () => { const wrapper = shallow( <DropMenu direction='up'> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const contextMenuDirection = wrapper .find('ContextMenu') .prop('direction'); assert.equal(contextMenuDirection, 'up'); }); }); describe('selectedIndices', () => { let wrapper: any; afterEach(() => { wrapper.unmount(); }); it('should render the selected options with appropriate className', () => { wrapper = mount( <DropMenu isExpanded={true} selectedIndices={[0, 2]}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const optionDOMNodes = document.querySelectorAll( '.lucid-ContextMenu-FlyOut .lucid-DropMenu-Option' ); assert( _.includes( optionDOMNodes[0].className, 'lucid-DropMenu-Option-is-selected' ) ); assert( !_.includes( optionDOMNodes[1].className, 'lucid-DropMenu-Option-is-selected' ) ); assert( _.includes( optionDOMNodes[2].className, 'lucid-DropMenu-Option-is-selected' ) ); }); }); describe('focusedIndex', () => { let wrapper: any; afterEach(() => { wrapper.unmount(); }); it('should render the focused option with appropriate className', () => { wrapper = mount( <DropMenu isExpanded={true} focusedIndex={2}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const optionDOMNodes = document.querySelectorAll( '.lucid-ContextMenu-FlyOut .lucid-DropMenu-Option' ); assert( !_.includes( optionDOMNodes[0].className, 'lucid-DropMenu-Option-is-focused' ) ); assert( !_.includes( optionDOMNodes[1].className, 'lucid-DropMenu-Option-is-focused' ) ); assert( _.includes( optionDOMNodes[2].className, 'lucid-DropMenu-Option-is-focused' ) ); }); }); describe('portalId', () => { let wrapper: any; afterEach(() => { if (wrapper) { wrapper.unmount(); } }); it('should render an element under document.body with the same id', () => { wrapper = mount( <DropMenu portalId='test-dropmenu-portal' isExpanded={true}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const portalDOMNode: any = document.getElementById( 'test-dropmenu-portal' ); assert(_.isElement(portalDOMNode)); assert.equal(document.body, portalDOMNode.parentNode); }); }); describe('flyOutStyle', () => { it('should pass flyOutStyle style object to the ContextMenu.FlyOut', () => { const styleObj = { width: 123, height: 321, backgroundColor: 'tan', }; const wrapper = shallow( <DropMenu flyOutStyle={styleObj}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); assert.deepEqual( styleObj, wrapper.find(ContextMenu.FlyOut).prop('style'), 'style object must be passed through to ContextMenu.FlyOut' ); }); }); describe('onExpand', () => { describe('mouse', () => { it('should be called when DropMenu [not expanded, clicked]', () => { const onExpand = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={false} onExpand={onExpand}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('click'); assert(onExpand.called); }); it('should not be called when DropMenu [expanded, clicked]', () => { const onExpand = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} onExpand={onExpand}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('click'); assert(onExpand.notCalled); }); }); describe('keyboard', () => { it('should be called when DropMenu [not expanded, has focus, Down Arrow key pressed]', () => { const onExpand = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={false} onExpand={onExpand}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.ArrowDown, preventDefault: _.noop, }); assert(onExpand.called); }); }); }); describe('onCollapse', () => { describe('mouse', () => { it('should be called when DropMenu [expanded, control clicked]', () => { const onCollapse = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} onCollapse={onCollapse}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('click'); assert(onCollapse.called); }); it('should not be called when DropMenu [not expanded, control clicked]', () => { const onCollapse = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={false} onCollapse={onCollapse}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('click'); assert(onCollapse.notCalled); }); it('should be called when DropMenu [expanded, ContextMenu onClickOut called]', () => { const onCollapse = sinon.spy(); const wrapper: any = shallow( <DropMenu isExpanded={true} onCollapse={onCollapse}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('ContextMenu').prop('onClickOut')(); assert(onCollapse.called); }); }); describe('keyboard', () => { it('should be called when DropMenu [expanded, Escape key pressed]', () => { const onCollapse = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} onCollapse={onCollapse}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.Escape, preventDefault: _.noop, }); assert(onCollapse.called); }); }); }); describe('onSelect', () => { describe('mouse', () => { let onSelect: any; let wrapper: any; beforeEach(() => { onSelect = sinon.spy(); wrapper = mount( <DropMenu isExpanded={true} onSelect={onSelect}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); }); afterEach(() => { wrapper.unmount(); onSelect.reset(); }); it('should be called when DropMenu [expanded, option clicked]', () => { const optionDOMNodes: any = document.querySelectorAll( '.lucid-ContextMenu-FlyOut .lucid-DropMenu-Option' ); optionDOMNodes[2].click(); assert(onSelect.called); assert(onSelect.calledWith(2)); }); }); describe('keyboard', () => { it('should be called when DropMenu [expanded, option focused, Enter key pressed]', () => { const onSelect: any = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} focusedIndex={2} onSelect={onSelect}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.Enter, preventDefault: _.noop, }); assert(onSelect.called); assert(onSelect.calledWith(2)); }); }); }); describe('onFocusOption', () => { describe('keyboard', () => { it('should be called when DropMenu [expanded, focusedIndex=null, Down Arrow key pressed]', () => { const onFocusOption = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} focusedIndex={null} onFocusOption={onFocusOption} > <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.ArrowDown, preventDefault: _.noop, }); assert(onFocusOption.called); }); it('should be called when DropMenu [expanded, focusedIndex={not last option}, Down Arrow key pressed]', () => { const onFocusOption = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} focusedIndex={1} onFocusOption={onFocusOption} > <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.ArrowDown, preventDefault: _.noop, }); assert(onFocusOption.called); }); it('should not be called when DropMenu [expanded, focusedIndex={last option}, Down Arrow key pressed]', () => { const onFocusOption = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} focusedIndex={2} onFocusOption={onFocusOption} > <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.ArrowDown, preventDefault: _.noop, }); assert(onFocusOption.notCalled); }); it('should be called when DropMenu [expanded, focusedIndex={not first option}, Up Arrow key pressed]', () => { const onFocusOption = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} focusedIndex={2} onFocusOption={onFocusOption} > <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.ArrowUp, preventDefault: _.noop, }); assert(onFocusOption.called); }); it('should not be called when DropMenu [expanded, focusedIndex={first option}, Up Arrow key pressed]', () => { const onFocusOption = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} focusedIndex={0} onFocusOption={onFocusOption} > <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.ArrowUp, preventDefault: _.noop, }); assert(onFocusOption.notCalled); }); it('should not be called when DropMenu [expanded, focusedIndex={null}, Up Arrow key pressed]', () => { const onFocusOption = sinon.spy(); const wrapper = shallow( <DropMenu isExpanded={true} focusedIndex={null} onFocusOption={onFocusOption} > <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); wrapper.find('.lucid-DropMenu-Control').simulate('keydown', { keyCode: KEYCODE.ArrowUp, preventDefault: _.noop, }); assert(onFocusOption.notCalled); }); }); describe('mouse', () => { let onFocusOption: any; let wrapper: any; beforeEach(() => { onFocusOption = sinon.spy(); wrapper = mount( <DropMenu isExpanded={true} onFocusOption={onFocusOption}> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); }); afterEach(() => { wrapper.unmount(); onFocusOption.reset(); }); it('should be called when user moves mouse over option', () => { const optionDOMNodes = document.querySelectorAll( '.lucid-ContextMenu-FlyOut .lucid-DropMenu-Option' ); const mouseMoveEvent = document.createEvent('MouseEvents'); mouseMoveEvent.initMouseEvent( 'mousemove', //event type : click, mousedown, mouseup, mouseover, mousemove, mouseout. true, //canBubble false, //cancelable window, //event's AbstractView : should be window 1, // detail : Event's mouse click count 50, // screenX 50, // screenY 50, // clientX 50, // clientY false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 0, // button : 0 = click, 1 = middle button, 2 = right button null // relatedTarget : Only used with some event types (e.g. mouseover and mouseout). In other cases, pass null. ); optionDOMNodes[2].dispatchEvent(mouseMoveEvent); assert(onFocusOption.called); assert(onFocusOption.calledWith(2)); assert(true); }); }); }); }); describe('child elements', () => { describe('Control', () => { it('should render the children of Control to the control container', () => { const wrapper = shallow( <DropMenu> <Control>control</Control> </DropMenu> ); assert.equal('control', wrapper.find('.lucid-DropMenu-Control').text()); }); }); describe('Option', () => { let wrapper: any; afterEach(() => { if (wrapper) { wrapper.unmount(); } }); it('should render the children of each Option in option nodes of the flyout menu', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut' ); const optionDOMNodes = flyOutDOMNode.querySelectorAll( '.lucid-DropMenu-Option' ); assert.equal(optionDOMNodes.length, 3); assert.equal(optionDOMNodes[0].innerHTML, 'option a'); assert.equal(optionDOMNodes[1].innerHTML, 'option b'); assert.equal(optionDOMNodes[2].innerHTML, 'option c'); }); it('should not render children with `isHidden`', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <Option isHidden>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut' ); const optionDOMNodes = flyOutDOMNode.querySelectorAll( '.lucid-DropMenu-Option' ); assert.equal(optionDOMNodes.length, 2); assert.equal(optionDOMNodes[0].innerHTML, 'option b'); assert.equal(optionDOMNodes[1].innerHTML, 'option c'); }); it('should render children options with `Selection` properties without generating React warnings', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <Option Selection={{ kind: 'warning' }}>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut' ); const optionDOMNodes = flyOutDOMNode.querySelectorAll( '.lucid-DropMenu-Option' ); assert.equal(optionDOMNodes.length, 3); assert.equal(optionDOMNodes[0].innerHTML, 'option a'); assert.equal(optionDOMNodes[1].innerHTML, 'option b'); assert.equal(optionDOMNodes[2].innerHTML, 'option c'); }); }); describe('OptionGroup', () => { let wrapper: any; afterEach(() => { if (wrapper) { wrapper.unmount(); } }); it('should render the Options in each OptionGroup separated by dividers', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <OptionGroup> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </OptionGroup> <OptionGroup> <Option>option p</Option> <Option>option q</Option> </OptionGroup> <OptionGroup> <Option>option x</Option> <Option>option y</Option> <Option>option z</Option> </OptionGroup> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); assert.equal(flyOutDOMNode.children.length, 10); assert.equal(flyOutDOMNode.children[0].innerHTML, 'option a'); assert.equal(flyOutDOMNode.children[1].innerHTML, 'option b'); assert.equal(flyOutDOMNode.children[2].innerHTML, 'option c'); assert.equal( flyOutDOMNode.children[3].className, 'lucid-DropMenu-OptionGroup-divider' ); assert.equal(flyOutDOMNode.children[4].innerHTML, 'option p'); assert.equal(flyOutDOMNode.children[5].innerHTML, 'option q'); assert.equal( flyOutDOMNode.children[6].className, 'lucid-DropMenu-OptionGroup-divider' ); assert.equal(flyOutDOMNode.children[7].innerHTML, 'option x'); assert.equal(flyOutDOMNode.children[8].innerHTML, 'option y'); assert.equal(flyOutDOMNode.children[9].innerHTML, 'option z'); assert( _.includes( flyOutDOMNode.children[0].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[1].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[2].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[4].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[5].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[7].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[8].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[9].className, 'lucid-DropMenu-Option-is-grouped' ) ); }); it('should render the ungrouped and grouped Options separated by dividers', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <OptionGroup> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </OptionGroup> <Option>option x</Option> <Option>option y</Option> <Option>option z</Option> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); assert.equal(flyOutDOMNode.children.length, 7); assert.equal(flyOutDOMNode.children[0].innerHTML, 'option a'); assert.equal(flyOutDOMNode.children[1].innerHTML, 'option b'); assert.equal(flyOutDOMNode.children[2].innerHTML, 'option c'); assert.equal( flyOutDOMNode.children[3].className, 'lucid-DropMenu-OptionGroup-divider' ); assert.equal(flyOutDOMNode.children[4].innerHTML, 'option x'); assert.equal(flyOutDOMNode.children[5].innerHTML, 'option y'); assert.equal(flyOutDOMNode.children[6].innerHTML, 'option z'); assert( _.includes( flyOutDOMNode.children[0].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[1].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( _.includes( flyOutDOMNode.children[2].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( !_.includes( flyOutDOMNode.children[4].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( !_.includes( flyOutDOMNode.children[5].className, 'lucid-DropMenu-Option-is-grouped' ) ); assert( !_.includes( flyOutDOMNode.children[6].className, 'lucid-DropMenu-Option-is-grouped' ) ); }); it('should render non-Option children of OptionGroups as group labels', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <OptionGroup> Preferred <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </OptionGroup> <OptionGroup> Available <Option>option x</Option> <Option>option y</Option> <Option>option z</Option> </OptionGroup> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); assert.equal(flyOutDOMNode.children.length, 9); assert.equal(flyOutDOMNode.children[0].textContent, 'Preferred'); assert.equal(flyOutDOMNode.children[1].innerHTML, 'option a'); assert.equal(flyOutDOMNode.children[2].innerHTML, 'option b'); assert.equal(flyOutDOMNode.children[3].innerHTML, 'option c'); assert.equal( flyOutDOMNode.children[4].className, 'lucid-DropMenu-OptionGroup-divider' ); assert.equal(flyOutDOMNode.children[5].textContent, 'Available'); assert.equal(flyOutDOMNode.children[6].innerHTML, 'option x'); assert.equal(flyOutDOMNode.children[7].innerHTML, 'option y'); assert.equal(flyOutDOMNode.children[8].innerHTML, 'option z'); assert( _.includes( flyOutDOMNode.children[0].className, 'lucid-DropMenu-label' ) ); assert( _.includes( flyOutDOMNode.children[5].className, 'lucid-DropMenu-label' ) ); }); it('should not render OptionGroups with `isHidden`', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <OptionGroup isHidden> Preferred <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </OptionGroup> <OptionGroup> Available <Option>option x</Option> <Option>option y</Option> <Option>option z</Option> </OptionGroup> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); assert.equal(flyOutDOMNode.children.length, 4); assert.equal(flyOutDOMNode.children[0].textContent, 'Available'); assert.equal(flyOutDOMNode.children[1].innerHTML, 'option x'); assert.equal(flyOutDOMNode.children[2].innerHTML, 'option y'); assert.equal(flyOutDOMNode.children[3].innerHTML, 'option z'); assert( _.includes( flyOutDOMNode.children[0].className, 'lucid-DropMenu-label' ) ); }); }); describe('NullOption', () => { let wrapper: any; afterEach(() => { if (wrapper) { wrapper.unmount(); } }); it('should render NullOption first with a divider immediately following', () => { wrapper = mount( <DropMenu isExpanded> <Control>control</Control> <NullOption>unselect</NullOption> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut .lucid-DropMenu-option-container' ); assert.equal(flyOutDOMNode.children.length, 5); assert.equal(flyOutDOMNode.children[0].innerHTML, 'unselect'); assert.equal( flyOutDOMNode.children[1].className, 'lucid-DropMenu-OptionGroup-divider' ); assert.equal(flyOutDOMNode.children[2].innerHTML, 'option a'); assert.equal(flyOutDOMNode.children[3].innerHTML, 'option b'); assert.equal(flyOutDOMNode.children[4].innerHTML, 'option c'); assert( _.includes( flyOutDOMNode.children[0].className, 'lucid-DropMenu-Option' ) ); assert( _.includes( flyOutDOMNode.children[0].className, 'lucid-DropMenu-Option-is-null' ) ); assert( _.includes( flyOutDOMNode.children[2].className, 'lucid-DropMenu-Option' ) ); assert( _.includes( flyOutDOMNode.children[3].className, 'lucid-DropMenu-Option' ) ); assert( _.includes( flyOutDOMNode.children[4].className, 'lucid-DropMenu-Option' ) ); }); }); describe('Header', () => { let wrapper: any; afterEach(() => { if (wrapper) { wrapper.unmount(); } }); it('should render Header first if it is provided, followed by the option-container', () => { wrapper = mount( <DropMenu isExpanded> <Header>HeyDer</Header> <Control>control</Control> <NullOption>unselect</NullOption> <Option>option a</Option> <Option>option b</Option> <Option>option c</Option> </DropMenu> ); const flyOutDOMNode: any = document.querySelector( '.lucid-DropMenu.lucid-ContextMenu-FlyOut' ); assert.equal(flyOutDOMNode.children.length, 2); assert.equal(flyOutDOMNode.children[0].innerHTML, 'HeyDer'); assert.equal( flyOutDOMNode.children[1].className, 'lucid-DropMenu-option-container' ); }); }); }); });
the_stack
import {Direction, Directionality} from '@angular/cdk/bidi'; import {END, HOME, LEFT_ARROW, RIGHT_ARROW, SPACE, TAB} from '@angular/cdk/keycodes'; import { dispatchFakeEvent, dispatchKeyboardEvent, MockNgZone, patchElementFocus, } from '../../cdk/testing/private'; import { Component, DebugElement, NgZone, QueryList, Type, ViewChild, ViewChildren, EventEmitter, } from '@angular/core'; import {ComponentFixture, fakeAsync, flush, TestBed, tick} from '@angular/core/testing'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {By} from '@angular/platform-browser'; import {MatChipListbox, MatChipOption, MatChipsModule} from './index'; describe('MDC-based MatChipListbox', () => { let fixture: ComponentFixture<any>; let chipListboxDebugElement: DebugElement; let chipListboxNativeElement: HTMLElement; let chipListboxInstance: MatChipListbox; let testComponent: StandardChipListbox; let chips: QueryList<MatChipOption>; let zone: MockNgZone; let directionality: {value: Direction; change: EventEmitter<Direction>}; let primaryActions: NodeListOf<HTMLElement>; describe('StandardChipList', () => { describe('basic behaviors', () => { beforeEach(() => { createComponent(StandardChipListbox); }); it('should add the `mat-mdc-chip-set` class', () => { expect(chipListboxNativeElement.classList).toContain('mat-mdc-chip-set'); }); it('should not have the aria-selected attribute when it is not selectable', fakeAsync(() => { testComponent.selectable = false; fixture.detectChanges(); tick(); const chipsValid = chips .toArray() .every( chip => !chip.selectable && !chip._elementRef.nativeElement.hasAttribute('aria-selected'), ); expect(chipsValid).toBe(true); })); it('should toggle the chips disabled state based on whether it is disabled', () => { expect(chips.toArray().every(chip => chip.disabled)).toBe(false); chipListboxInstance.disabled = true; fixture.detectChanges(); expect(chips.toArray().every(chip => chip.disabled)).toBe(true); chipListboxInstance.disabled = false; fixture.detectChanges(); expect(chips.toArray().every(chip => chip.disabled)).toBe(false); }); it('should disable a chip that is added after the listbox became disabled', fakeAsync(() => { expect(chips.toArray().every(chip => chip.disabled)).toBe(false); chipListboxInstance.disabled = true; fixture.detectChanges(); expect(chips.toArray().every(chip => chip.disabled)).toBe(true); fixture.componentInstance.chips.push(5, 6); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(chips.toArray().every(chip => chip.disabled)).toBe(true); })); it('should not set a role on the grid when the list is empty', () => { testComponent.chips = []; fixture.detectChanges(); expect(chipListboxNativeElement.hasAttribute('role')).toBe(false); }); it('should be able to set a custom role', () => { testComponent.role = 'grid'; fixture.detectChanges(); expect(chipListboxNativeElement.getAttribute('role')).toBe('grid'); }); it('should not set aria-required when it does not have a role', () => { testComponent.chips = []; fixture.detectChanges(); expect(chipListboxNativeElement.hasAttribute('role')).toBe(false); expect(chipListboxNativeElement.hasAttribute('aria-required')).toBe(false); }); }); describe('with selected chips', () => { beforeEach(() => { fixture = createComponent(SelectedChipListbox); }); it('should not override chips selected', () => { const instanceChips = fixture.componentInstance.chips.toArray(); expect(instanceChips[0].selected) .withContext('Expected first option to be selected.') .toBe(true); expect(instanceChips[1].selected) .withContext('Expected second option to be not selected.') .toBe(false); expect(instanceChips[2].selected) .withContext('Expected third option to be selected.') .toBe(true); }); it('should have role listbox', () => { expect(chipListboxNativeElement.getAttribute('role')).toBe('listbox'); }); it('should not have role when empty', () => { fixture.componentInstance.foods = []; fixture.detectChanges(); expect(chipListboxNativeElement.getAttribute('role')) .withContext('Expect no role attribute') .toBeNull(); }); }); describe('focus behaviors', () => { beforeEach(() => { createComponent(StandardChipListbox); }); it('should focus the first chip on focus', () => { chipListboxInstance.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(primaryActions[0]); }); it('should focus the primary action when calling the `focus` method', () => { chips.last.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(primaryActions[primaryActions.length - 1]); }); it('should not be able to become focused when disabled', () => { expect(chipListboxInstance.focused) .withContext('Expected listbox to not be focused.') .toBe(false); chipListboxInstance.disabled = true; fixture.detectChanges(); chipListboxInstance.focus(); fixture.detectChanges(); expect(chipListboxInstance.focused) .withContext('Expected listbox to continue not to be focused') .toBe(false); }); it('should remove the tabindex from the listbox if it is disabled', () => { expect(chipListboxNativeElement.getAttribute('tabindex')).toBe('0'); chipListboxInstance.disabled = true; fixture.detectChanges(); expect(chipListboxNativeElement.getAttribute('tabindex')).toBe('-1'); }); describe('on chip destroy', () => { it('should focus the next item', () => { const midItem = chips.get(2)!; // Focus the middle item patchElementFocus(midItem.primaryAction!._elementRef.nativeElement); midItem.focus(); // Destroy the middle item testComponent.chips.splice(2, 1); fixture.detectChanges(); // It focuses the 4th item expect(document.activeElement).toBe(primaryActions[3]); }); it('should focus the previous item', () => { // Focus the last item patchElementFocus(chips.last.primaryAction!._elementRef.nativeElement); chips.last.focus(); // Destroy the last item testComponent.chips.pop(); fixture.detectChanges(); // It focuses the next-to-last item expect(document.activeElement).toBe(primaryActions[primaryActions.length - 2]); }); it('should not focus if chip listbox is not focused', fakeAsync(() => { const midItem = chips.get(2)!; // Focus and blur the middle item midItem.focus(); (document.activeElement as HTMLElement).blur(); tick(); zone.simulateZoneExit(); // Destroy the middle item testComponent.chips.splice(2, 1); fixture.detectChanges(); tick(); // Should not have focus expect(chipListboxNativeElement.contains(document.activeElement)).toBe(false); })); it('should focus the listbox if the last focused item is removed', fakeAsync(() => { testComponent.chips = [0]; fixture.detectChanges(); spyOn(chipListboxInstance, 'focus'); patchElementFocus(chips.last.primaryAction!._elementRef.nativeElement); chips.last.focus(); testComponent.chips.pop(); fixture.detectChanges(); expect(chipListboxInstance.focus).toHaveBeenCalled(); })); }); }); describe('keyboard behavior', () => { describe('LTR (default)', () => { beforeEach(() => { createComponent(StandardChipListbox); }); it('should focus previous item when press LEFT ARROW', () => { const lastIndex = primaryActions.length - 1; // Focus the last item in the array chips.last.focus(); expect(document.activeElement).toBe(primaryActions[lastIndex]); // Press the LEFT arrow dispatchKeyboardEvent(primaryActions[lastIndex], 'keydown', LEFT_ARROW); fixture.detectChanges(); // It focuses the next-to-last item expect(document.activeElement).toBe(primaryActions[lastIndex - 1]); }); it('should focus next item when press RIGHT ARROW', () => { // Focus the last item in the array chips.first.focus(); expect(document.activeElement).toBe(primaryActions[0]); // Press the RIGHT arrow dispatchKeyboardEvent(primaryActions[0], 'keydown', RIGHT_ARROW); fixture.detectChanges(); // It focuses the next-to-last item expect(document.activeElement).toBe(primaryActions[1]); }); it('should not handle arrow key events from non-chip elements', () => { const previousActiveElement = document.activeElement; dispatchKeyboardEvent(chipListboxNativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); expect(document.activeElement) .withContext('Expected focused item not to have changed.') .toBe(previousActiveElement); }); it('should focus the first item when pressing HOME', () => { const lastAction = primaryActions[primaryActions.length - 1]; chips.last.focus(); expect(document.activeElement).toBe(lastAction); const event = dispatchKeyboardEvent(lastAction, 'keydown', HOME); fixture.detectChanges(); expect(document.activeElement).toBe(primaryActions[0]); expect(event.defaultPrevented).toBe(true); }); it('should focus the last item when pressing END', () => { chips.first.focus(); expect(document.activeElement).toBe(primaryActions[0]); const event = dispatchKeyboardEvent(primaryActions[0], 'keydown', END); fixture.detectChanges(); expect(document.activeElement).toBe(primaryActions[primaryActions.length - 1]); expect(event.defaultPrevented).toBe(true); }); }); describe('RTL', () => { beforeEach(() => { createComponent(StandardChipListbox, 'rtl'); }); it('should focus previous item when press RIGHT ARROW', () => { const lastIndex = primaryActions.length - 1; // Focus the last item in the array chips.last.focus(); expect(document.activeElement).toBe(primaryActions[lastIndex]); // Press the RIGHT arrow dispatchKeyboardEvent(primaryActions[lastIndex], 'keydown', RIGHT_ARROW); fixture.detectChanges(); // It focuses the next-to-last item expect(document.activeElement).toBe(primaryActions[lastIndex - 1]); }); it('should focus next item when press LEFT ARROW', () => { // Focus the last item in the array chips.first.focus(); expect(document.activeElement).toBe(primaryActions[0]); // Press the LEFT arrow dispatchKeyboardEvent(primaryActions[0], 'keydown', LEFT_ARROW); fixture.detectChanges(); // It focuses the next-to-last item expect(document.activeElement).toBe(primaryActions[1]); }); it('should allow focus to escape when tabbing away', fakeAsync(() => { dispatchKeyboardEvent(chipListboxNativeElement, 'keydown', TAB); expect(chipListboxInstance.tabIndex) .withContext('Expected tabIndex to be set to -1 temporarily.') .toBe(-1); flush(); expect(chipListboxInstance.tabIndex) .withContext('Expected tabIndex to be reset back to 0') .toBe(0); })); it('should use user defined tabIndex', fakeAsync(() => { chipListboxInstance.tabIndex = 4; fixture.detectChanges(); expect(chipListboxInstance.tabIndex) .withContext('Expected tabIndex to be set to user defined value 4.') .toBe(4); dispatchKeyboardEvent(chipListboxNativeElement, 'keydown', TAB); expect(chipListboxInstance.tabIndex) .withContext('Expected tabIndex to be set to -1 temporarily.') .toBe(-1); flush(); expect(chipListboxInstance.tabIndex) .withContext('Expected tabIndex to be reset back to 4') .toBe(4); })); }); it('should account for the direction changing', () => { createComponent(StandardChipListbox); chips.first.focus(); expect(document.activeElement).toBe(primaryActions[0]); dispatchKeyboardEvent(primaryActions[0], 'keydown', RIGHT_ARROW); fixture.detectChanges(); expect(document.activeElement).toBe(primaryActions[1]); directionality.value = 'rtl'; directionality.change.next('rtl'); fixture.detectChanges(); dispatchKeyboardEvent(primaryActions[1], 'keydown', RIGHT_ARROW); fixture.detectChanges(); expect(document.activeElement).toBe(primaryActions[0]); }); }); describe('selection logic', () => { beforeEach(() => { fixture = createComponent(BasicChipListbox); }); it('should remove selection if chip has been removed', fakeAsync(() => { const instanceChips = fixture.componentInstance.chips; const chipListbox = fixture.componentInstance.chipListbox; dispatchKeyboardEvent(primaryActions[0], 'keydown', SPACE); fixture.detectChanges(); expect(instanceChips.first.selected) .withContext('Expected first option to be selected.') .toBe(true); expect(chipListbox.selected) .withContext('Expected first option to be selected.') .toBe(chips.first); fixture.componentInstance.foods = []; fixture.detectChanges(); tick(); expect(chipListbox.selected) .withContext('Expected selection to be removed when option no longer exists.') .toBe(undefined); })); it('should select an option that was added after initialization', () => { fixture.componentInstance.foods.push({viewValue: 'Potatoes', value: 'potatoes-8'}); fixture.detectChanges(); primaryActions = chipListboxNativeElement.querySelectorAll<HTMLElement>( '.mdc-evolution-chip__action--primary', ); dispatchKeyboardEvent(primaryActions[8], 'keydown', SPACE); fixture.detectChanges(); expect(fixture.componentInstance.chipListbox.value) .withContext('Expect value contain the value of the last option') .toContain('potatoes-8'); expect(fixture.componentInstance.chips.last.selected) .withContext('Expect last option selected') .toBeTruthy(); }); it('should not select disabled chips', () => { const array = chips.toArray(); dispatchKeyboardEvent(primaryActions[2], 'keydown', SPACE); fixture.detectChanges(); expect(fixture.componentInstance.chipListbox.value) .withContext('Expect value to be undefined') .toBeUndefined(); expect(array[2].selected).withContext('Expect disabled chip not selected').toBeFalsy(); expect(fixture.componentInstance.chipListbox.selected) .withContext('Expect no selected chips') .toBeUndefined(); }); }); describe('chip list with chip input', () => { describe('single selection', () => { beforeEach(() => { fixture = createComponent(BasicChipListbox); }); it('should take an initial view value with reactive forms', fakeAsync(() => { fixture.componentInstance.control = new FormControl('pizza-1'); fixture.detectChanges(); tick(); const array = chips.toArray(); expect(array[1].selected).withContext('Expect pizza-1 chip to be selected').toBeTruthy(); dispatchKeyboardEvent(primaryActions[1], 'keydown', SPACE); fixture.detectChanges(); flush(); expect(array[1].selected) .withContext('Expect chip to be not selected after toggle selected') .toBeFalsy(); })); it('should set the view value from the form', () => { const chipListbox = fixture.componentInstance.chipListbox; const array = chips.toArray(); expect(chipListbox.value) .withContext('Expect chip listbox to have no initial value') .toBeFalsy(); fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); expect(array[1].selected).withContext('Expect chip to be selected').toBeTruthy(); }); it('should update the form value when the view changes', fakeAsync(() => { expect(fixture.componentInstance.control.value) .withContext(`Expected the control's value to be empty initially.`) .toEqual(null); dispatchKeyboardEvent(primaryActions[0], 'keydown', SPACE); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.value) .withContext(`Expected control's value to be set to the new option.`) .toEqual('steak-0'); })); it('should clear the selection when a nonexistent option value is selected', () => { const array = chips.toArray(); fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); expect(array[1].selected) .withContext(`Expected chip with the value to be selected.`) .toBeTruthy(); fixture.componentInstance.control.setValue('gibberish'); fixture.detectChanges(); expect(array[1].selected) .withContext(`Expected chip with the old value not to be selected.`) .toBeFalsy(); }); it('should clear the selection when the control is reset', () => { const array = chips.toArray(); fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); fixture.componentInstance.control.reset(); fixture.detectChanges(); expect(array[1].selected) .withContext(`Expected chip with the old value not to be selected.`) .toBeFalsy(); }); it('should set the control to touched when the chip listbox is touched', fakeAsync(() => { expect(fixture.componentInstance.control.touched) .withContext('Expected the control to start off as untouched.') .toBe(false); const nativeChipListbox = fixture.debugElement.query( By.css('mat-chip-listbox'), )!.nativeElement; dispatchFakeEvent(nativeChipListbox, 'blur'); tick(); expect(fixture.componentInstance.control.touched) .withContext('Expected the control to be touched.') .toBe(true); })); it('should not set touched when a disabled chip listbox is touched', fakeAsync(() => { expect(fixture.componentInstance.control.touched) .withContext('Expected the control to start off as untouched.') .toBe(false); fixture.componentInstance.control.disable(); const nativeChipListbox = fixture.debugElement.query( By.css('mat-chip-listbox'), )!.nativeElement; dispatchFakeEvent(nativeChipListbox, 'blur'); tick(); expect(fixture.componentInstance.control.touched) .withContext('Expected the control to stay untouched.') .toBe(false); })); it("should set the control to dirty when the chip listbox's value changes in the DOM", () => { expect(fixture.componentInstance.control.dirty) .withContext(`Expected control to start out pristine.`) .toEqual(false); dispatchKeyboardEvent(primaryActions[1], 'keydown', SPACE); fixture.detectChanges(); expect(fixture.componentInstance.control.dirty) .withContext(`Expected control to be dirty after value was changed by user.`) .toEqual(true); }); it('should not set the control to dirty when the value changes programmatically', () => { expect(fixture.componentInstance.control.dirty) .withContext(`Expected control to start out pristine.`) .toEqual(false); fixture.componentInstance.control.setValue('pizza-1'); expect(fixture.componentInstance.control.dirty) .withContext(`Expected control to stay pristine after programmatic change.`) .toEqual(false); }); it('should be able to programmatically select a falsy option', () => { fixture.destroy(); TestBed.resetTestingModule(); const falsyFixture = createComponent(FalsyValueChipListbox); falsyFixture.componentInstance.control.setValue([0]); falsyFixture.detectChanges(); falsyFixture.detectChanges(); expect(falsyFixture.componentInstance.chips.first.selected) .withContext('Expected first option to be selected') .toBe(true); }); it('should not focus the active chip when the value is set programmatically', () => { const chipArray = fixture.componentInstance.chips.toArray(); spyOn(chipArray[4], 'focus').and.callThrough(); fixture.componentInstance.control.setValue('chips-4'); fixture.detectChanges(); expect(chipArray[4].focus).not.toHaveBeenCalled(); }); }); describe('multiple selection', () => { beforeEach(() => { fixture = createComponent(MultiSelectionChipListbox); chips = fixture.componentInstance.chips; }); it('should take an initial view value with reactive forms', () => { fixture.componentInstance.control = new FormControl(['pizza-1']); fixture.detectChanges(); const array = chips.toArray(); expect(array[1].selected).withContext('Expect pizza-1 chip to be selected').toBeTruthy(); dispatchKeyboardEvent(primaryActions[1], 'keydown', SPACE); fixture.detectChanges(); expect(array[1].selected) .withContext('Expect chip to be not selected after toggle selected') .toBeFalsy(); }); it('should set the view value from the form', () => { const chipListbox = fixture.componentInstance.chipListbox; const array = chips.toArray(); expect(chipListbox.value) .withContext('Expect chip listbox to have no initial value') .toBeFalsy(); fixture.componentInstance.control.setValue(['pizza-1']); fixture.detectChanges(); expect(array[1].selected).withContext('Expect chip to be selected').toBeTruthy(); }); it('should update the form value when the view changes', () => { expect(fixture.componentInstance.control.value) .withContext(`Expected the control's value to be empty initially.`) .toEqual(null); dispatchKeyboardEvent(primaryActions[0], 'keydown', SPACE); fixture.detectChanges(); expect(fixture.componentInstance.control.value) .withContext(`Expected control's value to be set to the new option.`) .toEqual(['steak-0']); }); it('should clear the selection when a nonexistent option value is selected', () => { const array = chips.toArray(); fixture.componentInstance.control.setValue(['pizza-1']); fixture.detectChanges(); expect(array[1].selected) .withContext(`Expected chip with the value to be selected.`) .toBeTruthy(); fixture.componentInstance.control.setValue(['gibberish']); fixture.detectChanges(); expect(array[1].selected) .withContext(`Expected chip with the old value not to be selected.`) .toBeFalsy(); }); it('should clear the selection when the control is reset', () => { const array = chips.toArray(); fixture.componentInstance.control.setValue(['pizza-1']); fixture.detectChanges(); fixture.componentInstance.control.reset(); fixture.detectChanges(); expect(array[1].selected) .withContext(`Expected chip with the old value not to be selected.`) .toBeFalsy(); }); }); }); }); function createComponent<T>( component: Type<T>, direction: Direction = 'ltr', ): ComponentFixture<T> { directionality = { value: direction, change: new EventEmitter(), }; TestBed.configureTestingModule({ imports: [FormsModule, ReactiveFormsModule, MatChipsModule], declarations: [component], providers: [ {provide: NgZone, useFactory: () => (zone = new MockNgZone())}, {provide: Directionality, useValue: directionality}, ], }).compileComponents(); fixture = TestBed.createComponent<T>(component); fixture.detectChanges(); chipListboxDebugElement = fixture.debugElement.query(By.directive(MatChipListbox))!; chipListboxNativeElement = chipListboxDebugElement.nativeElement; chipListboxInstance = chipListboxDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; chips = chipListboxInstance._chips; primaryActions = chipListboxNativeElement.querySelectorAll<HTMLElement>( '.mdc-evolution-chip__action--primary', ); return fixture; } }); @Component({ template: ` <mat-chip-listbox [tabIndex]="tabIndex" [selectable]="selectable" [role]="role"> <mat-chip-option *ngFor="let i of chips" (select)="chipSelect(i)" (deselect)="chipDeselect(i)"> {{name}} {{i + 1}} </mat-chip-option> </mat-chip-listbox>`, }) class StandardChipListbox { name: string = 'Test'; selectable: boolean = true; chipSelect: (index?: number) => void = () => {}; chipDeselect: (index?: number) => void = () => {}; tabIndex: number = 0; chips = [0, 1, 2, 3, 4]; role: string | null = null; } @Component({ template: ` <mat-chip-listbox [formControl]="control" [required]="isRequired" [tabIndex]="tabIndexOverride" [selectable]="selectable"> <mat-chip-option *ngFor="let food of foods" [value]="food.value" [disabled]="food.disabled"> {{ food.viewValue }} </mat-chip-option> </mat-chip-listbox> `, }) class BasicChipListbox { foods: any[] = [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos', disabled: true}, {value: 'sandwich-3', viewValue: 'Sandwich'}, {value: 'chips-4', viewValue: 'Chips'}, {value: 'eggs-5', viewValue: 'Eggs'}, {value: 'pasta-6', viewValue: 'Pasta'}, {value: 'sushi-7', viewValue: 'Sushi'}, ]; control = new FormControl<string | null>(null); isRequired: boolean; tabIndexOverride: number; selectable: boolean; @ViewChild(MatChipListbox) chipListbox: MatChipListbox; @ViewChildren(MatChipOption) chips: QueryList<MatChipOption>; } @Component({ template: ` <mat-chip-listbox [multiple]="true" [formControl]="control" [required]="isRequired" [tabIndex]="tabIndexOverride" [selectable]="selectable"> <mat-chip-option *ngFor="let food of foods" [value]="food.value" [disabled]="food.disabled"> {{ food.viewValue }} </mat-chip-option> </mat-chip-listbox> `, }) class MultiSelectionChipListbox { foods: any[] = [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos', disabled: true}, {value: 'sandwich-3', viewValue: 'Sandwich'}, {value: 'chips-4', viewValue: 'Chips'}, {value: 'eggs-5', viewValue: 'Eggs'}, {value: 'pasta-6', viewValue: 'Pasta'}, {value: 'sushi-7', viewValue: 'Sushi'}, ]; control = new FormControl<string | null>(null); isRequired: boolean; tabIndexOverride: number; selectable: boolean; @ViewChild(MatChipListbox) chipListbox: MatChipListbox; @ViewChildren(MatChipOption) chips: QueryList<MatChipOption>; } @Component({ template: ` <mat-chip-listbox [formControl]="control"> <mat-chip-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mat-chip-option> </mat-chip-listbox> `, }) class FalsyValueChipListbox { foods: any[] = [ {value: 0, viewValue: 'Steak'}, {value: 1, viewValue: 'Pizza'}, ]; control = new FormControl([] as number[]); @ViewChildren(MatChipOption) chips: QueryList<MatChipOption>; } @Component({ template: ` <mat-chip-listbox> <mat-chip-option *ngFor="let food of foods" [value]="food.value" [selected]="food.selected"> {{ food.viewValue }} </mat-chip-option> </mat-chip-listbox> `, }) class SelectedChipListbox { foods: any[] = [ {value: 0, viewValue: 'Steak', selected: true}, {value: 1, viewValue: 'Pizza', selected: false}, {value: 2, viewValue: 'Pasta', selected: true}, ]; @ViewChildren(MatChipOption) chips: QueryList<MatChipOption>; }
the_stack
import { __ } from '@/components/_utils/_all'; /*-- Apply Third-party animation plugins --*/ import TweenMax from '@/components/_plugins/_lib-gsap'; declare global { interface Window { dragEvents?: any[any]; intervalEvents?: any[any]; } } interface hybridSliderAnimeConfig { /** Transition speed. This setting sets how long the transition animation lasts. Amount of time measured in milliseconds. */ speed?: number | undefined; /** The direction of the component animation, the value can be `vertical` and `horizontal` */ dir?: string; /** Setup a hybridSliderAnime for the slider to animate automatically. */ auto?: string | boolean | undefined; /** Autoplay interval. */ timing?: number | undefined; /** Gives the slider a seamless infinite loop. */ loop?: boolean | undefined; /** Navigation ID for paging control of each slide. */ paginationID?: string | undefined; /** Previous/Next arrow navigation ID. */ arrowsID?: string | boolean | undefined; /** Allow drag and drop on the slider (touch devices will always work). */ draggable?: boolean | undefined; /** Drag & Drop Change icon/cursor while dragging. */ draggableCursor?: string | boolean | undefined; } export function hybridSliderAnime( curElement: any, config: hybridSliderAnimeConfig ) { if ( typeof curElement === typeof undefined ) return; // Set a default configuration config = __.setDefaultOptions({ "speed" : 250, "dir" : "horizontal", "auto" : false, "timing" : 10000, "loop" : false, "paginationID" : ".poemkit-hybridslider__pagination", "arrowsID" : ".poemkit-hybridslider__arrows", "draggable" : false, "draggableCursor" : "move" }, config); // let dataSpeed = config.speed, dataDir = config.dir, dataAuto = config.auto, dataTiming = config.timing, dataLoop = config.loop, dataControlsPagination = config.paginationID, dataControlsArrows = config.arrowsID, dataDraggable = config.draggable, dataDraggableCursor = config.draggableCursor, dataNext = `${dataControlsArrows} .poemkit-hybrid-content-slider__controls--next`, dataPrev = `${dataControlsArrows} .poemkit-hybrid-content-slider__controls--prev`; // const $sliderWrapper = curElement; //Used to delete the global listening event when the component is about to be unmounted window.dragEvents = []; window.intervalEvents = []; let $itemsOuter = $sliderWrapper.find( '.poemkit-hybrid-content-slider__items' ), $items = $sliderWrapper.find( '.poemkit-hybrid-content-slider__items .poemkit-hybrid-content-slider__item' ), itemsTotal = $items.len(), amountVisible = 1; //Autoplay times let playTimes; //A function called "timer" once every second (like a digital watch). $sliderWrapper.get(0).animatedSlides; //Store the latest position (X,Y) in a temporary variable let tempItemsPos = []; //each item width and height let eachItemNewWidth, eachItemNewHeight = []; //total height of items let totalItemsHeight = 0; // Returns the value of a number rounded to the nearest integer. const midIndex = 0; //Images loaded //------------------------------------- const sources = []; //Push all images from page const imgs = $sliderWrapper.get(0).getElementsByTagName('img'); for (let i = 0; i < imgs.length; i++) { sources.push({"url": imgs[i].src, "type": 'img'} as never); } loadTextures(sources).then( function() { sliderInit(); }); /* * Initialize sliderAnime * * @return {Void} */ function sliderInit() { // Get the width and height of each item $items.each(function (this: any, index: number) { const _height = __( this ).height(); eachItemNewHeight.push( _height as never ); __( this ).attr('data-height', _height); __( this ).attr('data-index', index); }); //Returns the total height of items for (let i = 0; i < eachItemNewHeight.length; i++ ) { totalItemsHeight += eachItemNewHeight[i]; if ( (i+1) == (itemsTotal - amountVisible) ) break; } //Set target index of the slider buttons setButtonTargetIndex( __( dataNext ), __( dataPrev ), 'init', null ); //set actived item & initialize the height of container setContainerSize( 0 ); $items.addClass( 'js-is-ready' ); // Activate the current item from carouse setItemState( 0 ); //Slider Initialize //------------------------------------------ const eachItemOldWidth = $itemsOuter.width()/amountVisible; eachItemNewWidth = ( $sliderWrapper.width() / amountVisible ); if ( dataDir === 'horizontal' ) { $itemsOuter.css( 'width', itemsTotal * eachItemOldWidth ); } // Re-order all items sliderReOrder(); //default button status __( dataPrev ).addClass( 'is-disabled' ).data( 'disabled', 1 ); // Re-order all items //------------------------------------------ function sliderReOrder() { //Initialize the width and height of each item if ( dataDir === 'horizontal' ) { const boxWidth = eachItemNewWidth; TweenMax.set($items.get(-1), { width: boxWidth, height: function(i, target) { return eachItemNewHeight[i]; }, x: function(i, target) { return i * boxWidth; } }); } else { TweenMax.set($items.get(-1), { height: function(i, target) { return eachItemNewHeight[i]; }, y: function(i, target) { let yIncrement = 0; for (let k = 0; k < eachItemNewHeight.length; k++ ) { const tempY = ( typeof eachItemNewHeight[k-1] === typeof undefined ) ? 0 : eachItemNewHeight[k-1]; yIncrement += tempY; if ( k == i ) break; } return yIncrement; } }); } } //Next/Prev buttons //------------------------------------- const _prev = __( dataPrev ), _next = __( dataNext ); __( dataControlsArrows ).find( 'a' ).removeClass( 'is-disabled' ); if ( !dataLoop ) { _prev.addClass( 'is-disabled' ); } _prev.off( 'click' ).on( 'click', function( this: any, e: any ) { e.preventDefault(); btnPrevMove(); }); _next.off( 'click' ).on( 'click', function( this: any, e: any ) { e.preventDefault(); btnNextMove(); }); // (right/down) function btnPrevMove() { //Prevent buttons' events from firing multiple times if ( _prev.attr( 'aria-disabled' ) == 'true' ) return false; _prev.attr( 'aria-disabled', 'true' ); setTimeout( function() { _prev.attr( 'aria-disabled', 'false' ); }, dataSpeed ); // if ( _prev.hasClass( 'is-disabled' ) ) return false; // movePositionWithButton( false, _prev, 'prev' ); //Pause the auto play event clearInterval( $sliderWrapper.get(0).animatedSlides ); } // (left/up) function btnNextMove() { //Prevent buttons' events from firing multiple times if ( _next.attr( 'aria-disabled' ) == 'true' ) return false; _next.attr( 'aria-disabled', 'true' ); setTimeout( function() { _next.attr( 'aria-disabled', 'false' ); }, dataSpeed ); // if ( _next.hasClass( 'is-disabled' ) ) return false; // movePositionWithButton( false, _next, 'next' ); //Pause the auto play event clearInterval( $sliderWrapper.get(0).animatedSlides ); } // Pagination //------------------------------------------ let _dot = ''; _dot += '<ul>'; for ( let i = 0; i < itemsTotal; i++ ) { _dot += '<li><a data-index="'+i+'" href="#"></a></li>'; } _dot += '</ul>'; if ( __( dataControlsPagination ).html() == '' ) __( dataControlsPagination ).html( _dot ); // Activate the currently selected Pagination setPaginationState( 0 ); __( dataControlsPagination ).find( 'li a' ).off( 'click' ).on( 'click', function( this: any, e: any ) { e.preventDefault(); //Prevent buttons' events from firing multiple times const $btn = __( this ); if ( $btn.attr( 'aria-disabled' ) == 'true' ) return false; __( dataControlsPagination ).find( 'li a' ).attr( 'aria-disabled', 'true' ); setTimeout( function() { __( dataControlsPagination ).find( 'li a' ).attr( 'aria-disabled', 'false' ); }, dataSpeed ); if ( !$btn.parent().hasClass( 'is-active' ) ) { movePositionWithButton( true, $btn, 'next' ); //Pause the auto play event clearInterval( $sliderWrapper.get(0).animatedSlides ); } }); //Drag and Drop //------------------------------------- let firstItemOffset; let maxMoveOffset; // need to initialize a value let targetIndex = 0; let dragDirChanged = false; let currentIsFirstOrLast = false; let dragDirection = ''; let elAnim = true; //Temporarily store arrays as strings //!!!important /////////////////////////////////////// //!!! Prevent dragging events from nesting multiple //!!! times to reduce subscripts. //!!!important /////////////////////////////////////// const allHeightStr = eachItemNewHeight.toString(); // const $dragTrigger = $sliderWrapper.find( '.poemkit-hybrid-content-slider__items' ); let mouseX, mouseY; //Avoid images causing mouseup to fail $dragTrigger.find( 'img' ).css({ 'pointer-events': 'none', 'user-select': 'none' }); //Make the cursor a move icon when a user hovers over an item if ( dataDraggable && dataDraggableCursor != '' && dataDraggableCursor != false ) $dragTrigger.css( 'cursor', dataDraggableCursor ); //draggable for touch devices if ( __.isTouchCapable() ) dataDraggable = true; if ( dataDraggable ) { $dragTrigger.get(0).removeEventListener( 'mousedown', dragStart ); document.removeEventListener( 'mouseup', dragEnd ); $dragTrigger.get(0).removeEventListener( 'touchstart', dragStart ); document.removeEventListener( 'touchend', dragEnd ); // $dragTrigger.get(0).addEventListener( 'mousedown', dragStart ); $dragTrigger.get(0).addEventListener( 'touchstart', dragStart ); //block the vertical scrolling on a touch-device while on the element $sliderWrapper.css('touch-action', 'pan-x'); } function dragStart(e) { //Do not use "e.preventDefault()" to avoid prevention page scroll on drag in IOS and Android const touches = e.touches; if ( touches && touches.length ) { mouseX = touches[0].clientX; mouseY = touches[0].clientY; } else { mouseX = e.clientX; mouseY = e.clientY; } //drag direction dragDirection = ''; //current item index dragDirChanged = false; targetIndex = __( e.target ).data( 'index' ); if ( targetIndex === null ) targetIndex = __( e.target ).closest( '.poemkit-hybrid-content-slider__item' ).data( 'index' ); if ( targetIndex === null ) targetIndex = __( e.target ).find( '.poemkit-hybrid-content-slider__item' ).data( 'index' ); //determine whether it is the first or the last currentIsFirstOrLast = false; firstItemOffset = ( dataDir === 'horizontal' ) ? $itemsOuter.find( '[data-index="0"]' ).get(0)._gsTransform.x : $itemsOuter.find( '[data-index="0"]' ).get(0)._gsTransform.y; maxMoveOffset = ( dataDir === 'horizontal' ) ? -eachItemNewWidth*(itemsTotal-amountVisible) : -totalItemsHeight; // document.addEventListener('mouseup', dragEnd); document.addEventListener('mousemove', dragProcess); document.addEventListener('touchend', dragEnd); document.addEventListener('touchmove', dragProcess); window.dragEvents.push(dragEnd, dragProcess); } function dragProcess(e) { const touches = e.touches; let offsetX, offsetY; if ( touches && touches.length ) { offsetX = mouseX - touches[0].clientX, offsetY = mouseY - touches[0].clientY; } else { offsetX = mouseX - e.clientX, offsetY = mouseY - e.clientY; } //drag direction if ( dataDir === 'horizontal' ) { if ( offsetX > 0) dragDirection = 'left'; if ( offsetX < 0) dragDirection = 'right'; } else { if ( offsetY > 0) dragDirection = 'up'; if ( offsetY < 0) dragDirection = 'down'; } if ( dragDirection == 'right' || dragDirection == 'down' ) { if ( !dragDirChanged ) { //current item index targetIndex = targetIndex; //first item if ( firstItemOffset >= 0 ) currentIsFirstOrLast = true; // dragDirChanged = true; } } if ( dragDirection == 'left' || dragDirection == 'up' ) { if ( !dragDirChanged ) { //current item index targetIndex = targetIndex + 1; //last item if ( firstItemOffset <= maxMoveOffset ) currentIsFirstOrLast = true; // dragDirChanged = true; } } //console.log( 'dragDirection: ', dragDirection, 'targetIndex: ', targetIndex, 'currentIsFirstOrLast: ', currentIsFirstOrLast, 'offsetX: ', offsetX , 'offsetY: ', offsetY ); //Rebound effect of drag offset // //!important -> Please do not use multiple case conditions, //otherwise it may cause vertical data problems if ( dataDir === 'horizontal' ) { switch ( dragDirection ) { case 'left': if ( offsetX < eachItemNewWidth/4 && offsetX > 0 ) { elAnim = false; const simulationButtonNext = __( dataNext ); itemUpdates( $sliderWrapper, simulationButtonNext, -offsetX, 0.1, true, targetIndex, allHeightStr ); } else { elAnim = ( currentIsFirstOrLast ) ? false : true; } break; case 'right': if ( offsetX > -eachItemNewWidth/4 && offsetX < 0 ) { elAnim = false; const simulationButtonPrev = __( dataPrev ); itemUpdates( $sliderWrapper, simulationButtonPrev, -offsetX, 0.1, true, targetIndex, allHeightStr ); } else { elAnim = ( currentIsFirstOrLast ) ? false : true; } break; } } else { const draggingItemHeight = ( typeof allHeightStr.split( ',' )[targetIndex-1] === typeof undefined ) ? allHeightStr.split( ',' )[targetIndex] : allHeightStr.split( ',' )[targetIndex-1]; switch ( dragDirection ) { case 'up': if ( offsetY < parseFloat(draggingItemHeight)/4 && offsetY > 0 ) { elAnim = false; const simulationButtonNext = __( dataNext ); itemUpdates( $sliderWrapper, simulationButtonNext, -offsetY, 0.1, true, targetIndex, allHeightStr ); } else { elAnim = ( currentIsFirstOrLast ) ? false : true; } break; case 'down': if ( offsetY > -parseFloat(draggingItemHeight)/4 && offsetY < 0 ) { elAnim = false; const simulationButtonPrev = __( dataPrev ); itemUpdates( $sliderWrapper, simulationButtonPrev, -offsetY, 0.1, true, targetIndex, allHeightStr ); } else { elAnim = ( currentIsFirstOrLast ) ? false : true; } break; } } } function dragEnd(e) { document.removeEventListener( 'mousemove', dragProcess); document.removeEventListener( 'touchmove', dragProcess); if ( elAnim ) { //!important -> Please do not use multiple case conditions, //otherwise it may cause vertical data problems if ( dataDir === 'horizontal' ) { switch ( dragDirection ) { case 'left': btnNextMove(); break; case 'right': btnPrevMove(); break; } } else { switch ( dragDirection ) { case 'up': btnNextMove(); break; case 'down': btnPrevMove(); break; } } } else { //Rebound effect of drag offset itemUpdates( $sliderWrapper, false, tempItemsPos, null, false, targetIndex, allHeightStr); //Pause the auto play event clearInterval( $sliderWrapper.get(0).animatedSlides ); } //restore drag status dragDirChanged = false; } } //Autoplay Slider //------------------------------------- if (dataAuto && !isNaN(dataTiming as number) && isFinite(dataTiming as number)) { sliderAutoPlay( playTimes, dataTiming, dataLoop ); const autoplayEnter = function() { clearInterval( $sliderWrapper.get(0).animatedSlides ); }; const autoplayLeave = function() { sliderAutoPlay( playTimes, dataTiming, dataLoop ); }; // Do not use the `off()` method, otherwise it will cause the second mouseenter to be invalid $sliderWrapper.on( 'mouseenter', autoplayEnter ); $sliderWrapper.on( 'mouseleave', autoplayLeave ); // To determine if it is a touch screen. if ( __.isTouchCapable() ) { $sliderWrapper.on( 'pointerenter', autoplayEnter ); $sliderWrapper.on( 'pointerleave', autoplayLeave ); } } /* * Trigger slider autoplay * * @param {Function} playTimes - Number of times. * @param {Number} timing - Autoplay interval. * @param {Boolean} loop - Gives the slider a seamless infinite loop. * @return {Void} */ function sliderAutoPlay( playTimes, timing, loop ) { $sliderWrapper.get(0).animatedSlides = setInterval( function() { const autoMove = function( indexGo ) { // Retrieve the position (X,Y) of an element const moveX = eachItemNewWidth * indexGo; let moveYIncrement = 0; for (let k = 0; k < eachItemNewHeight.length; k++ ) { const tempY = ( typeof eachItemNewHeight[k-1] === typeof undefined ) ? 0 : eachItemNewHeight[k-1]; moveYIncrement += tempY; if ( k == indexGo ) break; } const moveY = moveYIncrement; // const delta = ( dataDir === 'horizontal' ) ? -moveX : -moveY; // itemUpdates( $sliderWrapper, 'auto', delta, null, false, indexGo, eachItemNewHeight ); }; playTimes = parseFloat( $items.filter( '.is-active' ).index() ); playTimes++; if ( !loop ) { if ( playTimes < itemsTotal && playTimes >= 0 ) { autoMove( playTimes ); } } else { if ( playTimes == itemsTotal ) playTimes = 0; if ( playTimes < 0 ) playTimes = itemsTotal-1; autoMove( playTimes ); } }, timing ); window.intervalEvents.push($sliderWrapper.get(0).animatedSlides); } /* * Transition Between Items * * @param {Element} wrapper - Wrapper of slider. * @param {?Element|String|Boolean} curBtn - The button that currently triggers the move. * @param {Number|Array} delta - The value returned will need to be adjusted according to the offset rate. * @param {?Number} speed - Sliding speed. Please set to 0 when rebounding. * @param {Boolean} dragging - Determine if the object is being dragged. * @param {!Number} indexGo - The target item index. * @param {String|Array} itemsHeight - Return all items height (the string type is used when a drag event is triggered). * @return {Void} */ function itemUpdates( wrapper, curBtn, delta, speed, dragging, indexGo, itemsHeight ) { if ( speed == null ) speed = (dataSpeed as number)/1000; let $curWrapper = wrapper.children( '.poemkit-hybrid-content-slider__items' ), //Default: $itemsOuter $curItems = $curWrapper.find( '.poemkit-hybrid-content-slider__item' ); //Default: $items //Get height constant let itemsHeightArr; if ( Array.isArray( itemsHeight ) ) { itemsHeightArr = [].slice.call(itemsHeight); } else { itemsHeightArr = itemsHeight.split( ',' ); } //Check next or previous event let btnType = 'init'; if ( curBtn !== false && curBtn !== 'auto' ) { if ( curBtn.attr( 'class' ) !== null ) { btnType = ( curBtn.attr( 'class' ).indexOf( '--next' ) >=0 ) ? 'next' : 'prev'; } else { btnType = 'next'; } } //Check next or previous event ( Autoplay ) if ( curBtn === 'auto' ) btnType = 'next'; //Clone the first element to the last position if ( dataDir === 'horizontal' ) { const boxWidth = eachItemNewWidth; TweenMax.to( $curItems.get(-1), speed, { x: function(i, target) { let xIncrement = 0; for (let k = 0; k < itemsTotal; k++ ) { const tempX = ( k == 0 ) ? 0 : boxWidth; xIncrement += tempX; if ( k == i ) break; } if ( Array.isArray( delta ) ) { //Rebound effect of drag offset return ( delta.length == 0 ) ? xIncrement : delta[i]; } else { if ( !dragging ) { //console.log( 'btnType: ' + btnType + ' indexGo: ' + indexGo ); let curWidthIncrement = 0; for (let m= 0; m < itemsTotal; m++ ) { const tempW = ( m == 0 ) ? 0 : boxWidth; curWidthIncrement += tempW; if ( m == ( btnType == 'next' ? indexGo : indexGo-1 ) ) break; } return xIncrement + -curWidthIncrement; } else { //console.log( 'dragging...' ); const x = Math.round(target._gsTransform.x / boxWidth ) * boxWidth; return x + delta; } } }, onComplete : function() { if ( !dragging && !Array.isArray( delta ) ) { //Get index of current element let currentIndex = 0; //The state of the control button setButtonState( Math.round( $curItems.first().get(0)._gsTransform.x ), Math.round( ($curItems.len() - amountVisible) * boxWidth ) ); //Initialize the height of container currentIndex = Math.round( $curItems.first().get(0)._gsTransform.x/boxWidth ); setContainerSize( currentIndex ); //Set target index of the slider buttons setButtonTargetIndex( __( dataNext ), __( dataPrev ), btnType, ( btnType == 'next' ? Math.abs( currentIndex ) : Math.abs( currentIndex ) + 1 ) ); // Activate the currently selected Pagination setPaginationState( Math.abs( currentIndex ) ); // Activate the current item from carouse setItemState( Math.abs( currentIndex ) ); //Store the latest position (X,Y) in a temporary variable tempItemsPos = createStoreLatestPosition(); } } }); } else { TweenMax.to( $curItems.get(-1), speed, { y: function(i, target) { let yIncrement = 0; for (let k = 0; k < itemsHeightArr.length; k++ ) { const tempY = ( typeof itemsHeightArr[k-1] === typeof undefined ) ? 0 : itemsHeightArr[k-1]; yIncrement += tempY; if ( k == i ) break; } if ( Array.isArray( delta ) ) { //Rebound effect of drag offset return ( delta.length == 0 ) ? yIncrement : delta[i]; } else { if ( !dragging ) { //console.log( 'btnType: ' + btnType + ' indexGo: ' + indexGo ); let curHeightIncrement = 0; for (let m = 0; m < itemsHeightArr.length; m++ ) { const tempH = ( typeof itemsHeightArr[m-1] === typeof undefined ) ? 0 : itemsHeightArr[m-1]; curHeightIncrement += tempH; if ( m == ( btnType == 'next' ? indexGo : indexGo-1 ) ) break; } return yIncrement + -curHeightIncrement; } else { //console.log( 'dragging...' ); const draggingItemHeight = ( typeof itemsHeightArr[indexGo-1] === typeof undefined ) ? itemsHeightArr[indexGo] : itemsHeightArr[indexGo-1]; const y = Math.round(target._gsTransform.y / draggingItemHeight ) * draggingItemHeight; return y + delta; } } }, onComplete : function() { if ( !dragging && !Array.isArray( delta ) ) { //The state of the control button setButtonState( $curItems.first().get(0)._gsTransform.y, totalItemsHeight ); //Set target index of the slider buttons setButtonTargetIndex( __( dataNext ), __( dataPrev ), btnType, indexGo ); //set actived item & initialize the height of container setContainerSize( ( btnType == 'next' ? indexGo : indexGo-1 ) ); // Activate the currently selected Pagination setPaginationState( ( btnType == 'next' ? indexGo : indexGo-1 ) ); // Activate the current item from carouse setItemState( ( btnType == 'next' ? indexGo : indexGo-1 ) ); //Store the latest position (X,Y) in a temporary variable tempItemsPos = createStoreLatestPosition(); } } }); } } /* * Use the button to trigger the transition between the two sliders * * @param {Boolean} paginationEnabled - Determine whether it is triggered by pagination * @param {Element} $btn - The button that currently triggers the move. * @param {String} type - Move next or previous. * @return {Void} */ function movePositionWithButton( paginationEnabled, $btn, type ) { //Protection button is not triggered multiple times. const btnDisabled = $btn.data( 'disabled' ); //Get target index let tIndex = $btn.data( 'index' ); // Retrieve the position (X,Y) of an element let moveX = eachItemNewWidth, moveY = ( typeof eachItemNewHeight[tIndex-1] === typeof undefined ) ? 0 : eachItemNewHeight[tIndex-1]; if ( paginationEnabled ) { //-- moveX = eachItemNewWidth * tIndex; //-- let moveYIncrement = 0; for (let k = 0; k < eachItemNewHeight.length; k++ ) { const tempY = ( typeof eachItemNewHeight[k-1] === typeof undefined ) ? 0 : eachItemNewHeight[k-1]; moveYIncrement += tempY; if ( k == tIndex ) break; } moveY = moveYIncrement; } // let delta; if ( type == 'next' ) { delta = ( dataDir === 'horizontal' ) ? -moveX : -moveY; } else { delta = ( dataDir === 'horizontal' ) ? moveX : moveY; } if ( btnDisabled === null ) { itemUpdates( $sliderWrapper, $btn, delta, null, false, tIndex, eachItemNewHeight ); } } /* * Activate the currently selected Pagination * * @param {Number} index - Get index of current element. * @return {Void} */ function setPaginationState( index ) { __( dataControlsPagination ).find( 'li' ).removeClass( 'is-active' ); __( dataControlsPagination ).find( 'li a[data-index="'+index+'"]' ).parent().addClass( 'is-active' ); } /* * Activate the current item from carouse * * @param {Number} index - Get index of current element. * @return {Void} */ function setItemState( index ) { $items.removeClass( 'is-active' ); $items.eq( index ).addClass( 'is-active' ); } /* * Store the latest position (X,Y) in a temporary variable * * @return {Array} - Return to a new position. */ function createStoreLatestPosition() { const pos = []; // Retrieve the temporary variable of each item. $items.each(function (this: any, index: number) { let _v: number; if ( dataDir === 'horizontal' ) { _v = __( this ).get(0)._gsTransform.x; } else { _v = __( this ).get(0)._gsTransform.y; } pos.push( _v as never ); }); return pos; } /* * Initialize the height of container * * @param {Number} index - Get index of current element. * @return {Void} */ function setContainerSize( index ) { const _h = eachItemNewHeight[Math.abs( index )]; if ( typeof _h !== typeof undefined ) { TweenMax.to( $itemsOuter.get(-1), 0.2, { height: eachItemNewHeight[Math.abs( index )] } ); } } /* * Set target index of the slider buttons * * @param {Element} nextBtn - The next move button. * @param {Element} prevBtn - The previous move button. * @param {String} type - The type of button is triggered. Values: next, prev, init * @param {?Number} indexGo - The target item index. * @return {Void} */ function setButtonTargetIndex( nextBtn, prevBtn, type, indexGo ) { switch ( type ) { case 'init': nextBtn.data('index', 1); prevBtn.data('index', 0); break; case 'next': let nextBtnOldTargetIndex1 = nextBtn.data( 'index' ); let prevBtnOldTargetIndex1 = prevBtn.data( 'index' ); if ( indexGo != null ) { nextBtnOldTargetIndex1 = indexGo; prevBtnOldTargetIndex1 = indexGo-1; } nextBtn.data('index', nextBtnOldTargetIndex1+1); prevBtn.data('index', prevBtnOldTargetIndex1+1); break; case 'prev': let nextBtnOldTargetIndex2 = nextBtn.data( 'index' ) - 1; let prevBtnOldTargetIndex2 = prevBtn.data( 'index' ) - 1; if ( indexGo != null ) { nextBtnOldTargetIndex2 = indexGo; prevBtnOldTargetIndex2 = indexGo-1; } nextBtn.data('index', nextBtnOldTargetIndex2); prevBtn.data('index', prevBtnOldTargetIndex2); break; } } /* * The state of the control button * * @param {Number} firstOffset - Get the computed Translate X or Y values of a given first DOM element. * @param {Number} lastOffset - Get the computed Translate X or Y values of a given last DOM element. * @return {Void} */ function setButtonState( firstOffset, lastOffset ) { if ( Math.abs( firstOffset ) == lastOffset ) { __( dataNext ).addClass( 'is-disabled' ).data( 'disabled', 1 ); __( dataPrev ).removeClass( 'is-disabled' ).removeData( 'disabled' ); } else if ( Math.round( firstOffset ) == 0 ) { __( dataNext ).removeClass( 'is-disabled' ).removeData( 'disabled' ); __( dataPrev ).addClass( 'is-disabled' ).data( 'disabled', 1 ); } else { __( dataNext ).removeClass( 'is-disabled' ).removeData( 'disabled' ); __( dataPrev ).removeClass( 'is-disabled' ).removeData( 'disabled' ); } } /* * Load Textures * * @param {Array} arr - All images and videos from array. * Such as: `[{"url":"1.jpg","type":"img"},{"url":"1.mp4","type":"video"}]` * @param {?Function} perLoadedCallback - Callback function after per item is completed * @return {Promise} */ function loadTextures(arr, perLoadedCallback?) { let promises = []; if (typeof(perLoadedCallback) === 'undefined') perLoadedCallback = function (url) { console.log(url) }; for (let i = 0; i < arr.length; i++) { if (arr[i].type == 'img') { /////////// // IMAGE // /////////// const _promise = new Promise(function (resolve: any, reject?: any) { const img = document.createElement('img'); img.crossOrigin = "anonymous"; img.src = arr[i].url; img.onload = function (this: any, e: any) { // compatible with safari and firefox const _path = typeof e.path === typeof undefined ? e.target.currentSrc : e.path[0].currentSrc; // send back result return resolve({ height: this.height, width: this.width, source: _path }); }; }) as never; promises.push(_promise); } else { /////////// // VIDEO // /////////// const _promise = new Promise(function (resolve: any, reject?: any) { const video = document.createElement('video'); video.addEventListener("loadedmetadata", function (this: any, e: any) { // retrieve dimensions let height = this.videoHeight; let width = this.videoWidth; // compatible with safari and firefox const _path = typeof e.path === typeof undefined ? e.target.currentSrc : e.path[0].currentSrc; // send back result return resolve({ height: height, width: width, source: _path }); }, false); // start download meta-datas video.src = arr[i].url; }) as never; promises.push(_promise); } } return Promise.all(promises); } } export default hybridSliderAnime;
the_stack
type Direction = "up" | "down" | "left" | "right"; /** * Maintains tiling context and performs various tiling actions. */ class TilingEngine { public layouts: LayoutStore; public windows: WindowStore; constructor() { this.layouts = new LayoutStore(); this.windows = new WindowStore(); } /** * Adjust layout based on the change in size of a tile. * * This operation is completely layout-dependent, and no general implementation is * provided. * * Used when tile is resized using mouse. */ public adjustLayout(basis: Window) { const srf = basis.surface; const layout = this.layouts.getCurrentLayout(srf); if (layout.adjust) { const area = srf.workingArea.gap(CONFIG.screenGapLeft, CONFIG.screenGapRight, CONFIG.screenGapTop, CONFIG.screenGapBottom); const tiles = this.windows.getVisibleTiles(srf); layout.adjust(area, tiles, basis, basis.geometryDelta); } } /** * Resize the current floating window. * * @param window a floating window */ public resizeFloat(window: Window, dir: "east" | "west" | "south" | "north", step: -1 | 1) { const srf = window.surface; // TODO: configurable step size? const hStepSize = srf.workingArea.width * 0.05; const vStepSize = srf.workingArea.height * 0.05; let hStep, vStep; switch (dir) { case "east" : hStep = step, vStep = 0; break; case "west" : hStep = -step, vStep = 0; break; case "south": hStep = 0, vStep = step; break; case "north": hStep = 0, vStep = -step; break; } const geometry = window.actualGeometry; const width = geometry.width + hStepSize * hStep; const height = geometry.height + vStepSize * vStep; window.forceSetGeometry(new Rect(geometry.x, geometry.y, width, height)); } /** * Resize the current tile by adjusting the layout. * * Used by grow/shrink shortcuts. */ public resizeTile(basis: Window, dir: "east" | "west" | "south" | "north", step: -1 | 1) { const srf = basis.surface; if (dir === "east") { const maxX = basis.geometry.maxX; const easternNeighbor = this.windows.getVisibleTiles(srf) .filter((tile) => tile.geometry.x >= maxX); if (easternNeighbor.length === 0) { dir = "west"; step *= -1; } } else if (dir === "south") { const maxY = basis.geometry.maxY; const southernNeighbor = this.windows.getVisibleTiles(srf) .filter((tile) => tile.geometry.y >= maxY); if (southernNeighbor.length === 0) { dir = "north"; step *= -1; } } // TODO: configurable step size? const hStepSize = srf.workingArea.width * 0.03; const vStepSize = srf.workingArea.height * 0.03; let delta: RectDelta; switch (dir) { case "east" : delta = new RectDelta(hStepSize * step, 0, 0, 0); break; case "west" : delta = new RectDelta(0, hStepSize * step, 0, 0); break; case "south": delta = new RectDelta(0, 0, vStepSize * step, 0); break; case "north": /* passthru */ default : delta = new RectDelta(0, 0, 0, vStepSize * step); break; } const layout = this.layouts.getCurrentLayout(srf); if (layout.adjust) { const area = srf.workingArea.gap(CONFIG.screenGapLeft, CONFIG.screenGapRight, CONFIG.screenGapTop, CONFIG.screenGapBottom); layout.adjust(area, this.windows.getVisibleTileables(srf), basis, delta); } } /** * Resize the given window, by moving border inward or outward. * * The actual behavior depends on the state of the given window. * * @param dir which border * @param step which direction. 1 means outward, -1 means inward. */ public resizeWindow(window: Window, dir: "east" | "west" | "south" | "north", step: -1 | 1) { const state = window.state; if (Window.isFloatingState(state)) this.resizeFloat(window, dir, step); else if (Window.isTiledState(state)) this.resizeTile(window, dir, step); } /** * Arrange tiles on all screens. */ public arrange(ctx: IDriverContext) { debug(() => "arrange"); ctx.screens.forEach((srf: ISurface) => { this.arrangeScreen(ctx, srf); }); } /** * Arrange tiles on a screen. */ public arrangeScreen(ctx: IDriverContext, srf: ISurface) { const layout = this.layouts.getCurrentLayout(srf); const workingArea = srf.workingArea; let tilingArea: Rect; if (CONFIG.monocleMaximize && layout instanceof MonocleLayout) tilingArea = workingArea; else tilingArea = workingArea.gap(CONFIG.screenGapLeft, CONFIG.screenGapRight, CONFIG.screenGapTop, CONFIG.screenGapBottom); const visibles = this.windows.getVisibleWindows(srf); debugObj(() => ["arrangeScreen", { layout, srf, visibles: visibles.length, }]); visibles.forEach((window) => { if (window.state === WindowState.Undecided) window.state = (window.shouldFloat) ? WindowState.Floating : WindowState.Tiled; }); const tileables = this.windows.getVisibleTileables(srf); if (CONFIG.maximizeSoleTile && tileables.length === 1) { tileables[0].state = WindowState.Maximized; tileables[0].geometry = workingArea; } else if (tileables.length > 0) layout.apply(new EngineContext(ctx, this), tileables, tilingArea); if (CONFIG.limitTileWidthRatio > 0 && !(layout instanceof MonocleLayout)) { const maxWidth = Math.floor(workingArea.height * CONFIG.limitTileWidthRatio); tileables.filter((tile) => tile.tiled && tile.geometry.width > maxWidth) .forEach((tile) => { const g = tile.geometry; tile.geometry = new Rect( g.x + Math.floor((g.width - maxWidth) / 2), g.y, maxWidth, g.height, ); }); } visibles.forEach((window) => window.commit()); debugObj(() => ["arrangeScreen/finished", { srf }]); } /** * Re-apply window geometry, computed by layout algorithm. * * Sometimes applications move or resize windows without user intervention, * which is straigh against the purpose of tiling WM. This operation * move/resize such windows back to where/how they should be. */ public enforceSize(ctx: IDriverContext, window: Window) { if (window.tiled && !window.actualGeometry.equals(window.geometry)) ctx.setTimeout(() => { if (window.tiled) window.commit(); }, 10); } /** * Register the given window to WM. */ public manage(window: Window) { if (!window.shouldIgnore) { /* engine#arrange will update the state when required. */ window.state = WindowState.Undecided; if (CONFIG.newWindowAsMaster) this.windows.unshift(window); else this.windows.push(window); } } /** * Unregister the given window from WM. */ public unmanage(window: Window) { this.windows.remove(window); } /** * Focus the next or previous window. */ public focusOrder(ctx: IDriverContext, step: -1 | 1) { const window = ctx.currentWindow; /* if no current window, select the first tile. */ if (window === null) { const tiles = this.windows.getVisibleTiles(ctx.currentSurface); if (tiles.length > 1) ctx.currentWindow = tiles[0]; return; } const visibles = this.windows.getVisibleWindows(ctx.currentSurface); if (visibles.length === 0) /* nothing to focus */ return; const idx = visibles.indexOf(window); if (!window || idx < 0) { /* unmanaged window -> focus master */ ctx.currentWindow = visibles[0]; return; } const num = visibles.length; const newIndex = (idx + (step % num) + num) % num; ctx.currentWindow = visibles[newIndex]; } /** * Focus a neighbor at the given direction. */ public focusDir(ctx: IDriverContext, dir: Direction) { const window = ctx.currentWindow; /* if no current window, select the first tile. */ if (window === null) { const tiles = this.windows.getVisibleTiles(ctx.currentSurface); if (tiles.length > 1) ctx.currentWindow = tiles[0]; return; } const neighbor = this.getNeighborByDirection(ctx, window, dir); if (neighbor) ctx.currentWindow = neighbor; } /** * Swap the position of the current window with the next or previous window. */ public swapOrder(window: Window, step: -1 | 1) { const srf = window.surface; const visibles = this.windows.getVisibleWindows(srf); if (visibles.length < 2) return; const vsrc = visibles.indexOf(window); const vdst = wrapIndex(vsrc + step, visibles.length); const dstWin = visibles[vdst]; this.windows.move(window, dstWin); } /** * Swap the position of the current window with a neighbor at the given direction. */ public swapDirection(ctx: IDriverContext, dir: Direction) { const window = ctx.currentWindow; if (window === null) { /* if no current window, select the first tile. */ const tiles = this.windows.getVisibleTiles(ctx.currentSurface); if (tiles.length > 1) ctx.currentWindow = tiles[0]; return; } const neighbor = this.getNeighborByDirection(ctx, window, dir); if (neighbor) this.windows.swap(window, neighbor); } /** * Move the given window towards the given direction by one step. * @param window a floating window * @param dir which direction */ public moveFloat(window: Window, dir: Direction) { const srf = window.surface; // TODO: configurable step size? const hStepSize = srf.workingArea.width * 0.05; const vStepSize = srf.workingArea.height * 0.05; let hStep, vStep; switch (dir) { case "up" : hStep = 0, vStep = -1; break; case "down" : hStep = 0, vStep = 1; break; case "left" : hStep = -1, vStep = 0; break; case "right": hStep = 1, vStep = 0; break; } const geometry = window.actualGeometry; const x = geometry.x + hStepSize * hStep; const y = geometry.y + vStepSize * vStep; window.forceSetGeometry(new Rect(x, y, geometry.width, geometry.height)); } public swapDirOrMoveFloat(ctx: IDriverContext, dir: Direction) { const window = ctx.currentWindow; if (!window) return; const state = window.state; if (Window.isFloatingState(state)) this.moveFloat(window, dir); else if (Window.isTiledState(state)) this.swapDirection(ctx, dir); } /** * Toggle float mode of window. */ public toggleFloat(window: Window) { window.state = (!window.tileable) ? WindowState.Tiled : WindowState.Floating; } /** * Toggle float on all windows on the given surface. * * The behaviours of this operation depends on the number of floating * windows: windows will be tiled if more than half are floating, and will * be floated otherwise. */ public floatAll(ctx: IDriverContext, srf: ISurface) { const windows = this.windows.getVisibleWindows(srf); const numFloats = windows.reduce<number>((count, window) => { return (window.state === WindowState.Floating) ? count + 1 : count; }, 0); if (numFloats < windows.length / 2) { windows.forEach((window) => { /* TODO: do not use arbitrary constants */ window.floatGeometry = window.actualGeometry.gap(4, 4, 4, 4); window.state = WindowState.Floating; }); ctx.showNotification("Float All"); } else { windows.forEach((window) => { window.state = WindowState.Tiled; }); ctx.showNotification("Tile All"); } } /** * Set the current window as the "master". * * The "master" window is simply the first window in the window list. * Some layouts depend on this assumption, and will make such windows more * visible than others. */ public setMaster(window: Window) { this.windows.setMaster(window); } /** * Change the layout of the current surface to the next. */ public cycleLayout(ctx: IDriverContext, step: 1 | -1) { const layout = this.layouts.cycleLayout(ctx.currentSurface, step); if (layout) ctx.showNotification(layout.description); } /** * Set the layout of the current surface to the specified layout. */ public setLayout(ctx: IDriverContext, layoutClassID: string) { const layout = this.layouts.setLayout(ctx.currentSurface, layoutClassID); if (layout) ctx.showNotification(layout.description); } /** * Let the current layout override shortcut. * * @returns True if the layout overrides the shortcut. False, otherwise. */ public handleLayoutShortcut(ctx: IDriverContext, input: Shortcut, data?: any): boolean { const layout = this.layouts.getCurrentLayout(ctx.currentSurface); if (layout.handleShortcut) return layout.handleShortcut(new EngineContext(ctx, this), input, data); return false; } private getNeighborByDirection(ctx: IDriverContext, basis: Window, dir: Direction): Window | null{ let vertical: boolean; let sign: -1 | 1; switch (dir) { case "up" : vertical = true ; sign = -1; break; case "down" : vertical = true ; sign = 1; break; case "left" : vertical = false; sign = -1; break; case "right": vertical = false; sign = 1; break; default: return null; } const candidates = this.windows.getVisibleTiles(ctx.currentSurface) .filter((vertical) ? ((tile) => tile.geometry.y * sign > basis.geometry.y * sign) : ((tile) => tile.geometry.x * sign > basis.geometry.x * sign)) .filter((vertical) ? ((tile) => overlap(basis.geometry.x, basis.geometry.maxX, tile.geometry.x, tile.geometry.maxX)) : ((tile) => overlap(basis.geometry.y, basis.geometry.maxY, tile.geometry.y, tile.geometry.maxY))); if (candidates.length === 0) return null; const min = sign * candidates.reduce( (vertical) ? ((prevMin, tile): number => Math.min(tile.geometry.y * sign, prevMin)) : ((prevMin, tile): number => Math.min(tile.geometry.x * sign, prevMin)), Infinity); const closest = candidates.filter( (vertical) ? (tile) => tile.geometry.y === min : (tile) => tile.geometry.x === min); return closest.sort((a, b) => b.timestamp - a.timestamp)[0]; } }
the_stack
import { IDataSet } from '../../src/base/engine'; import { pivot_dataset } from '../base/datasource.spec'; import { PivotView } from '../../src/pivotview/base/pivotview'; import { createElement, remove, EmitType } from '@syncfusion/ej2-base'; import { GroupingBar } from '../../src/common/grouping-bar/grouping-bar'; import { FieldList } from '../../src/common/actions/field-list'; import { CalculatedField } from '../../src/common/calculatedfield/calculated-field'; import * as util from '../utils.spec'; import { profile, inMB, getMemoryProfile } from '../common.spec'; // Spec for pivot context menu describe('Pivot Context Menu Spec', () => { beforeAll(() => { 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; } }); describe(' context menu in default grid', () => { let originalTimeout: number; let pivotGridObj: PivotView; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:500px; width:100%' }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll((done: Function) => { // if (document.getElementById(elem.id)) { // remove(document.getElementById(elem.id)); // } originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000; if (!document.getElementById(elem.id)) { document.body.appendChild(elem); } //document.body.appendChild(elem); let dataBound: EmitType<Object> = () => { done(); }; PivotView.Inject(CalculatedField, GroupingBar, FieldList); pivotGridObj = new PivotView({ dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], enableSorting: true, rows: [{ name: 'product', caption: 'Items' }, { name: 'eyeColor' }], columns: [{ name: 'gender', caption: 'Population' }, { name: 'isActive' }], values: [{ name: 'balance' }, { name: 'quantity' }], filters: [], }, enableValueSorting: true, allowDrillThrough: true, allowExcelExport: true, allowPdfExport: true, showValuesButton: true, allowCalculatedField: true, dataBound: dataBound, gridSettings: { contextMenuItems: ['Collapse', 'Drillthrough', 'Expand', 'Excel Export', 'Pdf Export', 'Csv Export', 'Sort Ascending', 'Sort Descending', 'Aggregate', 'CalculatedField'] } }); pivotGridObj.appendTo('#PivotGrid'); }); beforeEach((done: Function) => { setTimeout(() => { done(); }, 2000); }); it('check', () => { expect(true).toBeTruthy(); }) it('contextmenu in values-content', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuesheader'); let cell: HTMLElement = document.querySelector('.e-valuesheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu in values content', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#PivotGrid_grid_cmenu') !== null) expect(true); done(); }, 1000); }); it('contextmenu in values-content', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu select drill through', (done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_drillthrough_menu') as HTMLElement).click(); done(); }, 1000); }); it('drillthrough check', function (done) { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(document.querySelector('#PivotGrid_drillthrough') !== null).toBe(true); done(); }, 1000); }); it('dialog close click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.getElementsByClassName('e-btn-icon e-icon-dlg-close e-icons')[0] as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu open calculated field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_CalculatedField') as HTMLElement).click(); done(); }, 1000); }); it('dialog close click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#PivotGridcalculateddialog') !== null).toBe(true); done(); }, 1000); }); it('dialog close click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.getElementsByClassName('e-btn-icon e-icon-dlg-close e-icons')[0] as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-rowsheader'); let cell: HTMLElement = document.querySelector('.e-rowsheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu expand', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_expand') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { expect(document.querySelector('e-collapse')).toBe(null); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-rowsheader'); let cell: HTMLElement = document.querySelector('.e-rowsheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu collapse', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_collapse') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { expect(document.querySelector('.e-collapse') === null).toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu pdf export', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_exporting'); setTimeout(() => { util.triggerMouseEvent(target, 'mouseover'); (document.querySelector('#' + pivotGridObj.element.id + '_pdf') as HTMLElement).click(); expect(document.querySelector('.e-collapse') === null).toBeTruthy(); done(); }, 1000); }); it('contextmenu open', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu excel export', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_exporting'); setTimeout(() => { util.triggerMouseEvent(target, 'mouseover'); (document.querySelector('#' + pivotGridObj.element.id + '_excel') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu csv export', (done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_exporting'); setTimeout(() => { util.triggerMouseEvent(target, 'mouseover'); (document.querySelector('#' + pivotGridObj.element.id + '_csv') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuesheader'); let cell: HTMLElement = document.querySelector('.e-valuesheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value sorting ascending', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_sortasc') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { expect(document.querySelector('.e-ascending')).toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuesheader'); let cell: HTMLElement = document.querySelector('.e-valuesheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value sorting descending', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_sortdesc') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { expect(document.querySelector('.e-descending')).toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuesheader'); let cell: HTMLElement = document.querySelector('.e-valuesheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('contextmenu open', () => { expect(document.querySelector('.e-descending')).toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate count', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate count click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggCount') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', (done: Function) => { // expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "46").toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "46").toBeTruthy(); done(); }, 1000); pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate dcount', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate dcount click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggDistinctCount') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', (done: Function) => { // expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "46").toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "46").toBeTruthy(); done(); }, 1000); pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate product', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate product click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggProduct') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', (done: Function) => { // expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "6.588638896563111e+152").toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "6.588638896563111e+152").toBeTruthy(); done(); }, 1000); pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate average', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate avg click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggAvg') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', (done: Function) => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "2409.7805263157893").toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "2409.7805263157893").toBeTruthy(); done(); }, 1000); pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate minimum', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate Min click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggMin') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', (done: Function) => { // expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "1195.56").toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "1195.56").toBeTruthy(); done(); }, 1000); pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate maximum', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate Max click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggMax') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', (done: Function) => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "3958.73").toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "3958.73").toBeTruthy(); done(); }, 1000); pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate sum', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate sum click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggSum') as HTMLElement).click(); done(); }, 1000); // expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText).toBe("104702.76999999997"); }); it('contextmenu open', (done: Function) => { // expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "104702.76999999997").toBeTruthy(); //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-valuescontent') as HTMLElement).innerText.trim() === "104702.76999999997").toBeTruthy(); done(); }, 1000); pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu value aggregate more option', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('aggregate click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.querySelector('#' + pivotGridObj.element.id + '_AggMoreOption') as HTMLElement).click(); done(); }, 1000); }); it('contextmenu open', () => { expect(document.querySelector('#PivotGrid_ValueDialog') !== null).toBe(true); pivotGridObj.allowDrillThrough = false; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('dialog close click', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { (document.getElementsByClassName('e-btn-icon e-icon-dlg-close e-icons')[0] as HTMLElement).click(); done(); }, 1000); }); it('context menu hide drillthrough', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_drillthrough_menu').classList.contains('e-disabled') === true); done(); }, 1000); }); it('contextmenu open', () => { pivotGridObj.enableValueSorting = false; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuesheader'); let cell: HTMLElement = document.querySelector('.e-valuesheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu hide sorting', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_sortasc').classList.contains('e-disabled') === true); expect(document.querySelector('#' + pivotGridObj.element.id + '_sortdesc').classList.contains('e-disabled') === true); done(); }, 1000); }); it('contextmenu open calc disabled', () => { pivotGridObj.allowCalculatedField = false; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu check calculated field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_CalculatedField').classList.contains('e-disabled') === true); done(); }, 1000); }); it('contextmenu open pdf disabled', () => { pivotGridObj.allowPdfExport = false; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu check pdf menu', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_exporting'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); }); it('check pdf field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_pdf').classList.contains('e-disabled') === true); done(); }, 1000); }); it('contextmenu open excel disabled', () => { pivotGridObj.allowExcelExport = false; pivotGridObj.allowPdfExport = true; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu check pdf menu', (done: Function) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_exporting'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); }); it('check pdf field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_excel').classList.contains('e-disabled') === true); expect(document.querySelector('#' + pivotGridObj.element.id + '_csv').classList.contains('e-disabled') === true); done(); done(); }, 1000); }); it('contextmenu open excel disabled', () => { pivotGridObj.allowExcelExport = false; pivotGridObj.allowPdfExport = false; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu check excel and csv field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_exporting'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('check excel and csv field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_exporting').classList.contains('e-disabled') === true); expect(document.querySelector('#' + pivotGridObj.element.id + '_excel').classList.contains('e-disabled') === true); expect(document.querySelector('#' + pivotGridObj.element.id + '_csv').classList.contains('e-disabled') === true); done(); }, 1000); }); it('contextmenu open calculated field disabled', () => { pivotGridObj.allowCalculatedField = false; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu check calculated field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_CalculatedField'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('check calc field in disabled state', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_CalculatedField').classList.contains('e-disabled') === true); done(); }, 1000); pivotGridObj.dataSourceSettings.valueAxis = 'row'; }); it('contextmenu open values in row ', () => { pivotGridObj.dataSourceSettings.valueAxis = 'row'; //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); let cell: HTMLElement = document.querySelector('.e-valuescontent'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('context menu check calculated field', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { let target: HTMLElement = document.querySelector('#' + pivotGridObj.element.id + '_aggregate'); util.triggerMouseEvent(target, 'mouseover'); done(); }, 1000); }); it('check calc field in disabled state', (done: Function) => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(document.querySelector('#' + pivotGridObj.element.id + '_aggregate').classList.contains('e-disabled') === true); done(); }, 1000); }); it('contextmenu open values in column header ', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-columnsheader'); let cell: HTMLElement = document.querySelector('.e-columnsheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('contextmenu open headertext ', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-headertext'); let cell: HTMLElement = document.querySelector('.e-headertext'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('contextmenu open rowsheader ', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-rowsheader'); let cell: HTMLElement = document.querySelector('.e-rowsheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); it('contextmenu open rowsheader ', () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; pivotGridObj.lastCellClicked = document.querySelector('.e-rowsheader'); let cell: HTMLElement = document.querySelector('.e-rowsheader'); util.triggerMouseEvent(cell, 'contextmenu'); }); }); // describe('Context menu in disabled state', ()=>{ // let pivotGridObj: PivotView; // let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:500px; width:100%' }); // afterAll(() => { // if (pivotGridObj) { // pivotGridObj.destroy(); // } // remove(elem); // }); // beforeAll((done: Function) => { // if (!document.getElementById(elem.id)) { // document.body.appendChild(elem); // } // let dataBound: EmitType<Object> = () => { done(); }; // pivotGridObj = new PivotView({ // dataSourceSettings: { // dataSource: pivot_dataset as IDataSet[], // enableSorting: true, // rows: [{ name: 'product', caption: 'Items' }, { name: 'eyeColor' }], // columns: [{ name: 'gender', caption: 'Population' }, { name: 'isActive' }], // values: [{ name: 'balance' }, { name: 'quantity' }], // filters: [], // }, // enableValueSorting: false, // allowDrillThrough: false, // allowExcelExport:false, // allowPdfExport:false, // allowCalculatedField: false, // showValuesButton: true, // showGroupingBar:false, // dataBound: dataBound, // gridSettings : { // contextMenuItems:['Collapse','Drillthrough','Expand','EXCELExport','PDFExport','CSVExport', // 'Sort Ascending','Sort Descending','Aggregate','CalculatedField'] // } // }); // pivotGridObj.appendTo('#PivotGrid'); // }); // beforeEach((done: Function) => { // setTimeout(() => { done(); }, 1000); // }); // it('contextmenu in values-content', ()=>{ // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // pivotGridObj.lastCellClicked = document.querySelector('.e-valuesheader'); // let cell: HTMLElement = document.querySelector('.e-valuesheader'); // util.triggerMouseEvent(cell,'contextmenu'); // }); // it('context menu in values sorting', (done: Function) => { // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // setTimeout(() => { // expect(document.querySelector('#sortasc').classList.contains('e-disabled') === true); // expect(document.querySelector('#sortasc').classList.contains('e-disabled') === true); // done(); // }, 1000); // }); // it('contextmenu in values-content', ()=>{ // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); // let cell: HTMLElement = document.querySelector('.e-valuescontent'); // util.triggerMouseEvent(cell,'contextmenu'); // }); // it('context menu in values content', (done: Function) => { // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // setTimeout(() => { // expect(document.querySelector('#drillthrough').classList.contains('e-disabled') === true); // expect(document.querySelector('#CalculatedField').classList.contains('e-disabled') === true); // expect(document.querySelector('#exporting').classList.contains('e-disabled') === true); // done(); // }, 1000); // pivotGridObj.dataSource.valueAxis = 'row'; // }); // it('contextmenu in empty-content', ()=>{ // pivotGridObj.dataSource.valueAxis = 'row'; // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // pivotGridObj.lastCellClicked = document.querySelector('.e-valuescontent'); // let cell: HTMLElement = document.querySelector('.e-valuescontent'); // util.triggerMouseEvent(cell,'contextmenu'); // }); // it('context menu in empty content', (done: Function) => { // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // setTimeout(() => { // expect(document.querySelector('#drillthrough').classList.contains('e-disabled') === true); // expect(document.querySelector('#aggregate').classList.contains('e-disabled') === true); // done(); // }, 1000); // }); // }); 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 SteamID from 'steamid'; import pluralize from 'pluralize'; import TradeOfferManager, { Meta, OfferData, OurTheirItemsDict } from '@tf2autobot/tradeoffer-manager'; import Currencies from '@tf2autobot/tf2-currencies'; import { UnknownDictionaryKnownValues } from '../../../types/common'; import SKU from '@tf2autobot/tf2-sku'; import SchemaManager from '@tf2autobot/tf2-schema'; import Bot from '../../Bot'; import CommandParser from '../../CommandParser'; import { generateLinks, testSKU } from '../../../lib/tools/export'; // Manual review commands type ActionOnTrade = 'accept' | 'accepttrade' | 'decline' | 'declinetrade'; type ForceAction = 'faccept' | 'fdecline'; export default class ReviewCommands { constructor(private readonly bot: Bot) { this.bot = bot; } tradesCommand(steamID: SteamID): void { // Go through polldata and find active offers const pollData = this.bot.manager.pollData; const offersForReview: UnknownDictionaryKnownValues[] = []; const activeOffersNotForReview: UnknownDictionaryKnownValues[] = []; for (const id in pollData.received) { if (!Object.prototype.hasOwnProperty.call(pollData.received, id)) { continue; } if (pollData.received[id] !== TradeOfferManager.ETradeOfferState['Active']) { continue; } const data = pollData?.offerData[id] || null; if (data === null) { continue; } else if (data?.action?.action !== 'skip') { activeOffersNotForReview.push({ id: id, data: data }); continue; } offersForReview.push({ id: id, data: data }); } if (offersForReview.length === 0 && activeOffersNotForReview.length === 0) { return this.bot.sendMessage(steamID, '❌ There are no active offers/ pending review.'); } this.bot.sendMessage( steamID, (offersForReview.length > 0 ? this.generateTradesReply(offersForReview.sort((a, b) => a.id - b.id)) : '') + (offersForReview.length > 0 ? '\n\n-----------------\n\n' : '') + (activeOffersNotForReview.length > 0 ? this.generateActiveOfferReply(activeOffersNotForReview.sort((a, b) => a.id - b.id)) : '') ); } private generateTradesReply(offers: UnknownDictionaryKnownValues[]): string { const offersCount = offers.length; let reply = `There ${pluralize('is', offersCount)} ${offersCount} active ${pluralize( 'offer', offersCount )} that you can review:\n`; for (let i = 0; i < offersCount; i++) { const offer = offers[i]; reply += `\n- Offer #${offer.id as string} from ${(offer.data as OfferData).partner} (reason: ${( offer.data as OfferData ).meta.uniqueReasons.join(', ')})` + `\n⚠️ Send "!trade ${offer.id as string}" for more details.\n`; } return reply; } private generateActiveOfferReply(offers: UnknownDictionaryKnownValues[]): string { const offersCount = offers.length; let reply = `There ${pluralize('is', offersCount)} ${offersCount} ${pluralize( 'offer', offersCount )} that currently still active:\n`; for (let i = 0; i < offersCount; i++) { const offer = offers[i]; reply += `\n- Offer #${offer.id as string} from ${(offer.data as OfferData).partner}` + `\n⚠️ Send "!trade ${offer.id as string}" for more details, "!faccept ${ offer.id as string }" to force accept the trade, or "!fdecline ${offer.id as string}" to force decline the trade.\n`; } return reply; } tradeCommand(steamID: SteamID, message: string): void { const offerId = CommandParser.removeCommand(message).trim(); if (offerId === '') { return this.bot.sendMessage(steamID, '⚠️ Missing offer id. Example: "!trade 3957959294"'); } const state = this.bot.manager.pollData.received[offerId]; if (state === undefined) { return this.bot.sendMessage(steamID, 'Offer does not exist. ❌'); } if (state !== TradeOfferManager.ETradeOfferState['Active']) { // TODO: Add what the offer is now, accepted / declined and why return this.bot.sendMessage(steamID, 'Offer is not active. ❌'); } const offerData = this.bot.manager.pollData.offerData[offerId]; // Log offer details let reply = offerData?.action?.action === 'skip' ? `⚠️ Offer #${offerId} from ${offerData.partner} is pending for review` + `\nReason: ${offerData.meta.uniqueReasons.join(', ')}).\n\nSummary:\n\n` : `⚠️ Offer #${offerId} from ${offerData.partner} is still active.\n\nSummary:\n\n`; const keyPrice = this.bot.pricelist.getKeyPrice; const value = offerData.value; const items = offerData.dict || { our: null, their: null }; const summarizeItems = (dict: OurTheirItemsDict, schema: SchemaManager.Schema) => { if (dict === null) { return 'unknown items'; } const summary: string[] = []; for (const sku in dict) { if (!Object.prototype.hasOwnProperty.call(dict, sku)) { continue; } const name = testSKU(sku) ? schema.getName(SKU.fromString(sku), false) : sku; summary.push(name + (dict[sku] > 1 ? ` x${dict[sku]}` : '')); // dict[sku] = amount } if (summary.length === 0) { return 'nothing'; } return summary.join(', '); }; if (!value) { reply += 'Asked: ' + summarizeItems(items.our, this.bot.schema) + '\nOffered: ' + summarizeItems(items.their, this.bot.schema); } else { const valueDiff = new Currencies(value.their).toValue(keyPrice.metal) - new Currencies(value.our).toValue(keyPrice.metal); const valueDiffRef = Currencies.toRefined(Currencies.toScrap(Math.abs(valueDiff * (1 / 9)))).toString(); reply += 'Asked: ' + new Currencies(value.our).toString() + ' (' + summarizeItems(items.our, this.bot.schema) + ')\nOffered: ' + new Currencies(value.their).toString() + ' (' + summarizeItems(items.their, this.bot.schema) + (valueDiff > 0 ? `)\n📈 Profit from overpay: ${valueDiffRef} ref` : valueDiff < 0 ? `)\n📉 Loss from underpay: ${valueDiffRef} ref` : ')'); } const links = generateLinks(offerData.partner.toString()); reply += `\n\nSteam: ${links.steam}\nBackpack.tf: ${links.bptf}\nSteamREP: ${links.steamrep}` + (offerData?.action?.action === 'skip' ? `\n\n⚠️ Send "!accept ${offerId}" to accept or "!decline ${offerId}" to decline this offer.` : `\n\n⚠️ Send "!faccept ${offerId}" to force accept, or "!fdecline ${offerId}" to decline the trade now!`); this.bot.sendMessage(steamID, reply); } async actionOnTradeCommand(steamID: SteamID, message: string, command: ActionOnTrade): Promise<void> { const offerIdAndMessage = CommandParser.removeCommand(message); const offerIdRegex = /\d+/.exec(offerIdAndMessage); const isAccepting = ['accept', 'accepttrade'].includes(command); if (isNaN(+offerIdRegex) || !offerIdRegex) { return this.bot.sendMessage( steamID, `⚠️ Missing offer id. Example: "!${isAccepting ? 'accept' : 'decline'} 3957959294"` ); } const offerId = offerIdRegex[0]; const state = this.bot.manager.pollData.received[offerId]; if (state === undefined) { return this.bot.sendMessage(steamID, 'Offer does not exist. ❌'); } if (state !== TradeOfferManager.ETradeOfferState['Active']) { // TODO: Add what the offer is now, accepted / declined and why return this.bot.sendMessage(steamID, 'Offer is not active. ❌'); } const offerData = this.bot.manager.pollData.offerData[offerId]; if (offerData?.action?.action !== 'skip') { return this.bot.sendMessage(steamID, "Offer can't be reviewed. ❌"); } try { const offer = await this.bot.trades.getOffer(offerId); this.bot.sendMessage(steamID, `${isAccepting ? 'Accepting' : 'Declining'} offer...`); const partnerId = new SteamID(this.bot.manager.pollData.offerData[offerId].partner); const reply = offerIdAndMessage.substr(offerId.length); const adminDetails = this.bot.friends.getFriend(steamID); try { await this.bot.trades.applyActionToOffer( isAccepting ? 'accept' : 'decline', 'MANUAL', isAccepting ? (offer.data('meta') as Meta) : {}, offer ); if (isAccepting && this.bot.options.offerReceived.sendPreAcceptMessage.enable) { const isManyItems = offer.itemsToGive.length + offer.itemsToReceive.length > 50; if (isManyItems) { this.bot.sendMessage( offer.partner, this.bot.options.customMessage.accepted.manual.largeOffer ? this.bot.options.customMessage.accepted.manual.largeOffer : '.\nMy owner has manually accepted your offer. The trade may take a while to finalize due to it being a large offer.' + ' If the trade does not finalize after 5-10 minutes has passed, please send your offer again, or add me and use ' + 'the !sell/!sellcart or !buy/!buycart command.' ); } else { this.bot.sendMessage( offer.partner, this.bot.options.customMessage.accepted.manual.smallOffer ? this.bot.options.customMessage.accepted.manual.smallOffer : '.\nMy owner has manually accepted your offer. The trade should be finalized shortly.' + ' If the trade does not finalize after 1-2 minutes has passed, please send your offer again, or add me and use ' + 'the !sell/!sellcart or !buy/!buycart command.' ); } } // Send message to recipient if includes some messages if (reply) { const isShowOwner = this.bot.options.commands.message.showOwnerName; this.bot.sendMessage( partnerId, `/quote 💬 Message from ${ isShowOwner && adminDetails ? adminDetails.player_name : 'the owner' }: ${reply}` ); } } catch (err) { return this.bot.sendMessage( steamID, `❌ Ohh nooooes! Something went wrong while trying to ${ isAccepting ? 'accept' : 'decline' } the offer: ${(err as Error).message}` ); } } catch (err) { return this.bot.sendMessage( steamID, `❌ Ohh nooooes! Something went wrong while trying to ${ isAccepting ? 'accept' : 'decline' } the offer: ${(err as Error).message}` ); } } async forceAction(steamID: SteamID, message: string, command: ForceAction): Promise<void> { const offerIdAndMessage = CommandParser.removeCommand(message); const offerIdRegex = /\d+/.exec(offerIdAndMessage); const isForceAccepting = command === 'faccept'; if (isNaN(+offerIdRegex) || !offerIdRegex) { return this.bot.sendMessage( steamID, `⚠️ Missing offer id. Example: "!${isForceAccepting ? 'faccept' : 'fdecline'} 3957959294"` ); } const offerId = offerIdRegex[0]; const state = this.bot.manager.pollData.received[offerId]; if (state === undefined) { return this.bot.sendMessage(steamID, 'Offer does not exist. ❌'); } try { const offer = await this.bot.trades.getOffer(offerId); this.bot.sendMessage(steamID, `Force ${isForceAccepting ? 'accepting' : 'declining'} offer...`); const partnerId = new SteamID(this.bot.manager.pollData.offerData[offerId].partner); const reply = offerIdAndMessage.substr(offerId.length); const adminDetails = this.bot.friends.getFriend(steamID); try { await this.bot.trades.applyActionToOffer( isForceAccepting ? 'accept' : 'decline', 'MANUAL-FORCE', isForceAccepting ? (offer.data('meta') as Meta) : {}, offer ); // Send message to recipient if includes some messages if (reply) { const isShowOwner = this.bot.options.commands.message.showOwnerName; this.bot.sendMessage( partnerId, `/quote 💬 Message from ${ isShowOwner && adminDetails ? adminDetails.player_name : 'the owner' }: ${reply}` ); } } catch (err) { return this.bot.sendMessage( steamID, `❌ Ohh nooooes! Something went wrong while trying to force ${ isForceAccepting ? 'accept' : 'decline' } the offer: ${(err as Error).message}` ); } } catch (err) { return this.bot.sendMessage( steamID, `❌ Ohh nooooes! Something went wrong while trying to force ${ isForceAccepting ? 'accept' : 'decline' } the offer: ${(err as Error).message}` ); } } offerInfo(steamID: SteamID, message: string): void { const offerIdAndMessage = CommandParser.removeCommand(message); const offerIdRegex = /\d+/.exec(offerIdAndMessage); if (isNaN(+offerIdRegex) || !offerIdRegex) { return this.bot.sendMessage(steamID, `⚠️ Missing offer id. Example: "!offerinfo 3957959294"`); } const offerId = offerIdRegex[0]; const timestamp = this.bot.manager.pollData.timestamps[offerId]; if (timestamp === undefined) { return this.bot.sendMessage(steamID, 'Offer does not exist. ❌'); } try { const offer = this.bot.manager.pollData.offerData[offerId]; const show = {}; show[offerId] = offer; this.bot.sendMessage(steamID, '/code ' + JSON.stringify(show, null, 4)); } catch (err) { return this.bot.sendMessage(steamID, `❌ Error getting offer #${offerId} info: ${(err as Error).message}`); } } }
the_stack
import * as K from './Kit'; import {Err, Result, isResultOK, InterU} from './Kit'; import {$Values} from 'utility-types'; /** Not Really Parser Combinator Parsec<S,A,State,UserError> S is the input stream type. A is result value type. State is user custom state type. UserError is user custom ParseError.userError type. */ export interface ParseError<UserError> { position: number; parser?: Parser<any, any, any, any>; message?: string; userError?: UserError; } type Failed<UserError> = Err<ParseError<UserError>>; export type SimpleResult<A, UserError> = Result<A, ParseError<UserError>>; export type ParseResult<A, State, UserError> = Result<A, ParseError<UserError>> & { consumed: number; state: State; }; class ParseCtx<S extends K.Stream<S>, State, UserError> { public position: number = 0; // A shared and mutable range field. // So we can directly convert ParseCtx to TokenCtx and avoid temp object; public range: TokenRange = [0, 0]; public readonly recurMemo: Map< Parser<S, any, State, UserError>, Map<number, {position: number; state: State; result: SimpleResult<any, UserError>}> >; constructor(public readonly input: S, public state: State) { this.recurMemo = new Map(); } } export type GetParserResultType<P> = P extends Parser<any, infer A, any, any> ? A : never; /** Open end range @example "a" in "abc" range is [0,1] */ export type TokenRange = [number, number]; export interface TokenCtx<S, State> { readonly input: S; range: TokenRange; state: State; } export abstract class Parser<S extends K.Stream<S>, A, State, UserError> { /** Map result value. Changing state in the map function is allowed, ensure yourself the parser is unrecoverable. (Why that? Because we don't have *REAL* immutable data type.) */ map<B>(f: (v: A, ctx: TokenCtx<S, State>) => B): Parser<S, B, State, UserError> { return MapF.compose( this, (r, ctx) => { if (isResultOK(r)) { return {value: f(r.value, ctx)}; } else { return r; } } ); } /** Map result function return with UserError */ mapE<B>(f: (v: A, ctx: TokenCtx<S, State>) => Result<B, UserError>): Parser<S, B, State, UserError> { let p: Parser<S, B, State, UserError> = MapF.compose( this, (r, ctx) => { if (isResultOK(r)) { let r2 = f(r.value, ctx); if (isResultOK(r2)) { return r2; } else { return { error: { position: ctx.range[0], parser: p, userError: r2.error } }; } } else { return r; } } ); return p; } mapF<B>( f: (a: SimpleResult<A, UserError>, ctx: TokenCtx<S, State>) => SimpleResult<B, UserError> ): Parser<S, B, State, UserError> { return MapF.compose( this, f ); } /** Map result UserError */ mapError(f: (err: UserError) => UserError): Parser<S, A, State, UserError> { return MapF.compose( this, r => { if (isResultOK(r)) return r; if (r.error.userError) { r.error.userError = f(r.error.userError); } return r; } ); } /** We had allowed changing state in map function. But this is required by recoverable parsers in alternative branches */ stateF(f: (st: State, ctx: TokenCtx<S, State>) => State): StateF<S, A, State, UserError> { return new StateF(this, f); } slice(): Parser<S, S, State, UserError> { return this.map((_, ctx) => ctx.input.slice(ctx.range[0], ctx.range[1])); } opt(): Optional<S, A, State, UserError> { return new Optional(this); } trys(): TryParser<S, A, State, UserError> { return new TryParser(this); } followedBy(look: Parser<S, any, State, UserError>): Lookahead<S, A, State, UserError> { return new Lookahead(this, look, false); } notFollowedBy(look: Parser<S, any, State, UserError>): Lookahead<S, A, State, UserError> { return new Lookahead(this, look, true); } /** Right biased sequence */ thenR<B>(next: Parser<S, B, State, UserError>): Parser<S, B, State, UserError> { return new Seqs([this, next]).at(1); } /** Left biased sequence */ thenL(next: Parser<S, any, State, UserError>): Parser<S, A, State, UserError> { return new Seqs([this, next]).at(0); } and<B>(next: Parser<S, B, State, UserError>): Seqs<S, [A, B], State, UserError> { return new Seqs([this, next]); } between( left: Parser<S, any, State, UserError>, right: Parser<S, any, State, UserError> ): Parser<S, A, State, UserError> { return new Seqs([left, this, right]).at(1); } repeat(min: number = 0, max: number = Infinity): Repeat<S, A, State, UserError> { return new Repeat(this, min, max); } count(n: number) { return this.repeat(n, n); } many(): Repeat<S, A, State, UserError> { return this.repeat(); } some(): Repeat<S, A, State, UserError> { return this.repeat(1); } betweens(left: S, right: S): Parser<S, A, State, UserError> { return new Seqs([new Exact<S, State, UserError>(left), this, new Exact<S, State, UserError>(right)]).at(1); } /** Restricted monad bind, function f can not return Ref reference to other parsers */ thenF<B>(f: (a: A, ctx: TokenCtx<S, State>) => Parser<S, B, State, UserError>): Parser<S, B, State, UserError> { return new ThenF(this, f); } parse(s: S, initalState: State): ParseResult<A, State, UserError> { let context = new ParseCtx<S, State, UserError>(s, initalState); let result: any = this._parseWith(context); result.state = context.state; result.consumed = context.position; return result; } abstract _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError>; private _nullable?: boolean; isNullable(): boolean { if (typeof this._nullable === 'boolean') return this._nullable; // Default true to prevent left recursion. Object.defineProperty(this, '_nullable', {value: true, writable: true}); return (this._nullable = this._checkNullable()); } _checkNullable() { return false; } // Resolve Reference private _dereferenced?: boolean; // Get Ref parser dereferenced _getDeref(): Parser<S, A, State, UserError> { if (this._dereferenced) { return this; } else { // To hide trivial private properties from debug inspector // Default true to prevent recursion Object.defineProperty(this, '_dereferenced', {value: true, writable: true}); return this._deref(); } } _deref(): Parser<S, A, State, UserError> { return this; } /** Get NonNullable left first set */ _getFirstSet(): Array<Parser<any, any, any, any>> { return [this]; } // Description desc(): string { return this.constructor.name; } [K._inspect_]() { return this.desc(); } } export type FResult<A, UserError> = Result<A, UserError | string | true> & {consumed: number}; export class FParser<S extends K.Stream<S>, A, State, UserError> extends Parser<S, A, State, UserError> { constructor( private _f: (context: { readonly input: S; readonly position: number; readonly state: State; }) => FResult<A, UserError> ) { super(); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError> { let result: any = this._f(context); if (result.error) { let errorResult: Failed<UserError> = { error: { position: context.position, parser: this } }; if (typeof result.error === 'string') { errorResult.error.message = result.error; } else if (result.error !== true) { errorResult.error.userError = result.error; } return errorResult; } else { context.position += result.consumed; return {value: result.value}; } } } class MapF<S extends K.Stream<S>, A, B, State, UserError> extends Parser<S, B, State, UserError> { private constructor( private _p: Parser<S, A, State, any>, private _f: (v: SimpleResult<A, UserError>, ctx: TokenCtx<S, State>) => SimpleResult<B, UserError> ) { super(); } static compose<S extends K.Stream<S>, A, B, State, UserError>( p: Parser<S, A, State, UserError>, f: (v: SimpleResult<A, UserError>, ctx: TokenCtx<S, State>) => SimpleResult<B, UserError> ): MapF<S, A, B, State, UserError> { if (p instanceof MapF) { let g = p._f; return new MapF(p._p, (v, ctx) => f(g(v, ctx), ctx)); } return new MapF(p, f); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<B, UserError> { let position = context.position; let result: SimpleResult<A, UserError> = this._p._parseWith(context); let tokenCtx: TokenCtx<S, State> = context; context.range = [position, context.position]; return this._f(result, tokenCtx); } // Unsafe, because we allowed changing state in map function thenR<C>(next: Parser<S, C, State, UserError>): Parser<S, C, State, UserError> { return this._p.thenR(next); } thenL(next: Parser<S, any, State, UserError>): Parser<S, B, State, UserError> { return MapF.compose( this._p.thenL(next), this._f ); } _checkNullable(): boolean { return this._p.isNullable(); } _deref(): this { this._p = this._p._getDeref(); return this; } _getFirstSet() { return this._p._getFirstSet(); } } export class StateF<S extends K.Stream<S>, A, State, UserError> extends Parser<S, A, State, UserError> { constructor(private _p: Parser<S, A, State, UserError>, private _f: (st: State, ctx: TokenCtx<S, State>) => State) { super(); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError> { let startPos = context.position; let result = this._p._parseWith(context); if (isResultOK(result)) { context.range = [startPos, context.position]; context.state = this._f(context.state, context); } return result; } _checkNullable(): boolean { return this._p.isNullable(); } _deref(): this { this._p = this._p._getDeref(); return this; } _getFirstSet() { return this._p._getFirstSet(); } } /** Restricted Monad bind, function f can not return Ref reference to other parsers, in this way we dont need to check LeftRecur in parsing */ export class ThenF<S extends K.Stream<S>, A, B, State, UserError> extends Parser<S, B, State, UserError> { constructor( private _p: Parser<S, A, State, UserError>, private _f: (a: A, st: TokenCtx<S, State>) => Parser<S, B, State, UserError> ) { super(); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<B, UserError> { let position = context.position; let result = this._p._parseWith(context); if (isResultOK(result)) { let tokenCtx: TokenCtx<S, State> = context; tokenCtx.range = [position, context.position]; let nextP = this._f(result.value, tokenCtx); let nextResult = nextP._parseWith(context); return nextResult; } return result; } _deref(): this { this._p = this._p._getDeref(); return this; } _getFirstSet() { return this._p.isNullable() ? [] : this._p._getFirstSet(); } _checkNullable(): boolean { return this._p.isNullable(); } } export class Optional<S extends K.Stream<S>, A, State, UserError> extends Parser<S, K.Maybe<A>, State, UserError> { constructor(private _p: Parser<S, A, State, UserError>) { super(); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<K.Maybe<A>, UserError> { let {position, state} = context; let result = this._p._parseWith(context); if (!isResultOK(result) && context.position === position) { context.state = state; return {value: undefined}; } return result; } isNullable() { return true; } _deref(): this { this._p = this._p._getDeref(); return this; } _getFirstSet() { return this._p._getFirstSet(); } } export class TryParser<S extends K.Stream<S>, A, State, UserError> extends Parser<S, A, State, UserError> { constructor(private _p: Parser<S, A, State, UserError>) { super(); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError> { let {position, state} = context; let result = this._p._parseWith(context); if (!isResultOK(result)) { context.position = position; context.state = state; } return result; } _checkNullable(): boolean { return this._p.isNullable(); } _deref(): this { this._p = this._p._getDeref(); return this; } _getFirstSet() { return this._p._getFirstSet(); } } export class Lookahead<S extends K.Stream<S>, A, State, UserError> extends Parser<S, A, State, UserError> { constructor( private _p: Parser<S, A, State, UserError>, private _look: Parser<S, any, State, UserError>, private _negative: boolean ) { super(); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError> { let result = this._p._parseWith(context); if (isResultOK(result)) { let {position, state} = context; let a = this._look._parseWith(context); context.position = position; context.state = state; let ok = isResultOK(a); if (ok === this._negative) { if (ok) return {error: {position: position, parser: this}}; else return a; } } return result; } _checkNullable(): boolean { return this._look.isNullable(); } _deref(): this { this._p = this._p._getDeref(); this._look = this._look._getDeref(); return this; } _getFirstSet() { return this._p._getFirstSet(); } } export class Seqs<S extends K.Stream<S>, A extends Array<any>, State, UserError> extends Parser< S, A, State, UserError > { constructor(private _items: Array<Parser<S, any, State, UserError>>) { super(); if (!_items.length) throw new Error('Seqs can not be empty'); } thenR<B>(next: Parser<S, B, State, UserError>): Parser<S, B, State, UserError> { return new Seqs(this._items.concat([next])).map(a => a[a.length - 1]); } at<N extends number>(n: N): Parser<S, A[N], State, UserError> { return this.map(a => a[n]); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError> { let plist = this._items; let value: any = []; for (let i = 0; i < plist.length; i++) { let p = plist[i]; let result = p._parseWith(context); if (isResultOK(result)) { value.push(result.value); } else { return result; } } return {value}; } _checkNullable() { for (let p of this._items) { if (!p.isNullable()) return false; } return true; } _deref(): this { for (let i = 0; i < this._items.length; i++) { this._items[i] = this._items[i]._getDeref(); } return this; } _getFirstSet() { let all: any = []; for (let p of this._items) { let first = p._getFirstSet(); all = all.concat(first); if (!p.isNullable()) { return all; } } return all; } desc(): string { let seqs = this._items.map(p => p.desc()).join(','); return `Seqs(${seqs})`; } } export class Alts<S extends K.Stream<S>, A, State, UserError> extends Parser<S, A, State, UserError> { constructor(private _alts: Array<Parser<S, A, State, UserError>>) { super(); if (!_alts.length) throw new Error('Alts can not be empty'); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError> { let plist = this._alts; let len = plist.length; let result; let i = 0; let {position, state} = context; do { result = plist[i]._parseWith(context); if (isResultOK(result) || context.position !== position) return result; context.position = position; context.state = state; } while (++i < len); return result; } _checkNullable() { for (let p of this._alts) { if (p.isNullable()) return true; } return false; } _deref(): this { for (let i = 0; i < this._alts.length; i++) { this._alts[i] = this._alts[i]._getDeref(); } return this; } _getFirstSet() { let all: Parser<S, A, State, UserError>[] = []; for (let p of this._alts) { let aset = p._getFirstSet(); all = all.concat(aset); } return all; } desc() { let alts = this._alts.map(p => p.desc()).join(','); return `Alts(${alts})`; } } export class Repeat<S extends K.Stream<S>, A, State, UserError> extends Parser<S, A[], State, UserError> { constructor(private _p: Parser<S, A, State, UserError>, private _min: number = 0, private _max: number = Infinity) { super(); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A[], UserError> { let count = 0; let value = []; for (; count < this._max; count++) { let oldPosition = context.position; let result = this._p._parseWith(context); if (isResultOK(result)) { value.push(result.value); } else { if (context.position !== oldPosition || count < this._min) { return result; } break; } } return {value}; } isNullable() { return this._min === 0; } _deref(): this { this._p = this._p._getDeref(); if (this._p.isNullable()) { throw new Error('Repeat on nullable parser:' + this._p.desc()); } return this; } _getFirstSet() { return this._p._getFirstSet(); } desc() { return `${this._p.desc()}.repeat(${this._min},${this._max})`; } } // @singleton class Empty<State, UserError> extends Parser<any, undefined, State, UserError> { _parseWith(context: ParseCtx<any, State, UserError>): SimpleResult<undefined, UserError> { return {value: undefined}; } isNullable() { return true; } } // @singleton class EOF<State, UserError> extends Empty<State, UserError> { _parseWith(context: ParseCtx<any, State, UserError>): SimpleResult<undefined, UserError> { if (context.position === context.input.length) return {value: undefined}; else return {error: {position: context.position, parser: this}}; } } class FailParser<State, UserError> extends Parser<any, never, State, UserError> { constructor(private _msg: string, private _userError?: UserError) { super(); } _parseWith(context: ParseCtx<any, State, UserError>) { let a: Failed<UserError> = {error: {parser: this, position: context.position, message: this._msg}}; if (this._userError !== undefined) { a.error.userError = this._userError; } return a; } isNullable() { return true; } } export class Exact<S extends K.Stream<S>, State, UserError> extends Parser<S, S, State, UserError> { constructor(private _s: S) { super(); if (!_s.length) throw new Error('Exact match empty make no sense, please use Parsec.empty instead!'); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<S, UserError> { let l = this._s.length; let {input, position} = context; let s = input.slice(position, position + l); if (s === this._s || K.deepEqual(s, this._s)) { context.position += l; return {value: this._s}; } else { return {error: {position: position, parser: this}}; } } isNullable() { return false; } desc() { return `Exact(${JSON.stringify(this._s)})`; } } export interface RegexRepeat<State, UserError> { getRegexSource(): string; repeats(min: number, max: number): Parser<string, string, State, UserError>; counts(n: number): Parser<string, string, State, UserError>; } function _repeats<State, UserError>( this: RegexRepeat<State, UserError>, min = 0, max = Infinity ): Parser<string, string, State, UserError> { let re = '(?:' + this.getRegexSource() + ')'; let quantifier = '{' + min + ',' + (max === Infinity ? '' : max) + '}'; let p: MatchRegex<State, UserError> = new MatchRegex(new RegExp(re + quantifier, 'u')); return p.map(m => m[0]); } function _counts<State, UserError>( this: RegexRepeat<State, UserError>, n: number ): Parser<string, string, State, UserError> { return this.repeats(n, n); } abstract class CharsetBase<State, UserError> extends Parser<string, string, State, UserError> implements RegexRepeat<State, UserError> { _parseWith(context: ParseCtx<string, State, UserError>): SimpleResult<string, UserError> { let {position, input} = context; let cp = input.codePointAt(position); if (typeof cp === 'undefined') { return { error: {position: position, parser: this, message: 'EOF'} }; } else if (this._includeCodePoint(cp)) { let c = String.fromCodePoint(cp); context.position += c.length; return {value: c}; } else { return {error: {position: position, parser: this}}; } } abstract _includeCodePoint(cp: number): boolean; abstract getRegexSource(): string; repeats: (min?: number, max?: number) => Parser<string, string, State, UserError> = _repeats; counts: (n: number) => Parser<string, string, State, UserError> = _counts; isNullable() { return false; } _getDeref() { return this; } } export class CharsetParser<State, UserError> extends CharsetBase<State, UserError> { constructor(private _charset: K.Charset) { super(); } _includeCodePoint(cp: number): boolean { return this._charset.includeCodePoint(cp); } getRegexSource(): string { return this._charset.toRegex().source; } desc() { return `Charset(${JSON.stringify(this._charset.toPattern())})`; } } export class OneOf<State, UserError> extends CharsetBase<State, UserError> { _set: Set<number>; constructor(a: string) { super(); this._set = new Set(Array.from(a).map(K.Char.ord)); } _includeCodePoint(cp: number): boolean { return this._set.has(cp); } getRegexSource(): string { return K.Charset.fromCodePoints(Array.from(this._set)).toRegex().source; } desc() { return ( this.constructor.name + `(${JSON.stringify( Array.from(this._set) .map(K.Char.chr) .join('') )})` ); } } export class NoneOf<State, UserError> extends OneOf<State, UserError> { _includeCodePoint(cp: number): boolean { return !this._set.has(cp); } getRegexSource(): string { return K.Charset.fromCodePoints(Array.from(this._set)) .inverted() .toRegex().source; } } export class MatchRegex<State, UserError> extends Parser<string, string[] & RegExpExecArray, State, UserError> implements RegexRepeat<State, UserError> { _re: RegExp; _rawRe: RegExp; constructor(re: RegExp) { super(); this._rawRe = re; this._re = new RegExp(re.source, re.flags.replace('y', '') + 'y'); } _parseWith(context: ParseCtx<string, State, UserError>): SimpleResult<string[] & RegExpExecArray, UserError> { let {input, position} = context; this._re.lastIndex = position; let m = this._re.exec(input); if (m === null) { return {error: {position: position, parser: this}}; } else { context.position += m[0].length; return {value: m}; } } slice(): Parser<string, string, State, UserError> { return this.map(m => m[0]); } _checkNullable() { return this._re.test(''); } repeats: (min?: number, max?: number) => Parser<string, string, State, UserError> = _repeats; counts: (n: number) => Parser<string, string, State, UserError> = _counts; getRegexSource(): string { return this._rawRe.source; } desc() { return `Regex(${this._rawRe.toString()})`; } } interface AnyParserMap { [refName: string]: Parser<any, any, any, any>; } // @private class Ref extends Parser<any, any, any, any> { private _p?: Parser<any, any, any, any>; constructor(private _refName: string) { super(); } resolveRef(ruleMap: AnyParserMap) { let p = ruleMap[this._refName]; if (!p) { throw new Error('Referenced rule does not exist: ' + this._refName); } this._p = p; } isNullable() { return this._p!.isNullable(); } _getFirstSet() { return [this]; } _getDeref(): Parser<any, any, any, any> { return this._p!._getDeref(); } _parseWith(...args: any[]): never { throw new Error('Ref Parser ' + this._refName + ' should not be called'); } } class LeftRecur<S extends K.Stream<S>, A, State, UserError> extends Parser<S, A, State, UserError> { constructor(private _p: Parser<S, A, State, UserError>) { super(); if (_p.isNullable()) throw new Error('LeftRecur on nullable parser:' + _p.desc()); } _parseWith(context: ParseCtx<S, State, UserError>): SimpleResult<A, UserError> { let {recurMemo, position, state} = context; let memoMap = recurMemo.get(this); if (!memoMap) { memoMap = new Map(); recurMemo.set(this, memoMap); } let last = memoMap.get(position); if (last) { context.position = last.position; context.state = last.state; return last.result; } last = { position: position, state: state, result: {error: {position: position, parser: this}} }; memoMap.set(position, last); while (true) { context.position = position; context.state = state; let result = this._p._parseWith(context); if (context.position <= last.position) { return last.result; } else if (!isResultOK(result)) { return result; } last.result = result; last.position = context.position; } } isNullable(): boolean { return false; } _deref(): this { this._p = this._p._getDeref(); return this; } _getFirstSet() { return this._p._getFirstSet(); } desc() { return 'Recur(' + this._p.desc() + ')'; } } export interface GrammarMainDef<S extends K.Stream<S>, A, State, UserError> { Main: ParserDef<S, A, State, UserError>; } export type RecurParserDef<S extends K.Stream<S>, A, State, UserError> = () => Parser<S, A, State, UserError>; export type ParserDef<S extends K.Stream<S>, A, State, UserError> = | Parser<S, A, State, UserError> | RecurParserDef<S, A, State, UserError>; export type ParserUndef<F> = F extends (() => infer P) ? P : F extends Parser<any, any, any, any> ? F : never; export type FilterParserField<T> = { [K in keyof T]: T[K] extends Function | Parser<any, any, any, any> ? K : never; }[keyof T]; export type GrammarRuleMap<T> = { [K in FilterParserField<T>]: ParserUndef<T[K]>; // Distribute to ParserUndef }; export type GrammarDefTypes<T> = $Values<GrammarRuleMap<T>> extends Parser< infer Stream, infer Result, infer State, infer UserError > ? [Stream, Result, State, UserError] : never; interface AnyParserDefMap { [refName: string]: ParserDef<any, any, any, any>; } const _objectPrototypePropertyNames = new Set(Object.getOwnPropertyNames(Object.prototype)); /** * Get object all available property names,include its prototype chain but exclude top Object.prototype */ function getDefRuleNames(a: any): string[] { let names: string[] = []; let proto = a; while (proto && proto !== Object.prototype) { names = names.concat(Object.getOwnPropertyNames(proto)); proto = Object.getPrototypeOf(proto); } names = names.filter(n => !_objectPrototypePropertyNames.has(n)); return K.sortUnique(names); } export class Grammar<T> { readonly rules: GrammarRuleMap<T>; private constructor(_rawDef: T) { let rawDef = (_rawDef as unknown) as AnyParserDefMap; let ruleNames = getDefRuleNames(_rawDef).filter(k => rawDef[k] instanceof Function || rawDef[k] instanceof Parser); let ruleMap: AnyParserMap = Object.create(null); let thisObject: AnyParserDefMap = Object.create(null); let refMap: {[ruleName: string]: Ref} = Object.create(null); for (let k of ruleNames) { let p = rawDef[k]; if (typeof p === 'function') { refMap[k] = new Ref(k); thisObject[k] = () => refMap[k]; } else { thisObject[k] = p; } } for (let k of ruleNames) { let df = rawDef[k]; let p; if (typeof df === 'function') { p = df.call(thisObject); if (!(p instanceof Parser)) { throw new TypeError(`Grammar Definition clause "${k}" function must return Parser`); } } else { p = df; } if (p instanceof Parser) { // Allow extra utility non parser property in grammar class ruleMap[k] = p; } } let refNames = Object.getOwnPropertyNames(refMap); for (let k of refNames) { refMap[k].resolveRef(ruleMap); } for (let k of ruleNames) { // Fix left recursion let firstSet = ruleMap[k]._getFirstSet(); let selfRef = refMap[k]; if (firstSet.includes(selfRef)) { ruleMap[k] = new LeftRecur(ruleMap[k]); } } for (let k of refNames) { refMap[k].resolveRef(ruleMap); } for (let k of ruleNames) { ruleMap[k] = ruleMap[k]._getDeref(); } this.rules = <any>ruleMap; } parseWithState: T extends GrammarMainDef<infer S, infer A, infer State, infer UserError> ? (s: S, initalState: State) => ParseResult<A, State, UserError> : never = ((s: any, initalState: any = null) => { let rules = this.rules as any; if (rules.Main) { return rules.Main.parse(s, initalState); } }) as any; parse: T extends GrammarMainDef<infer S, infer A, null, infer UserError> ? (s: S) => ParseResult<A, null, UserError> : never = this.parseWithState as any; static def<T>(rawDef: T): $Values<GrammarRuleMap<T>> extends Parser<any, any, any, any> ? Grammar<T> : never { return new Grammar(rawDef as any) as any; } } /** We have to pre-specify these generic types due to TypeScript lacks of value polymorphism */ export function refine<S extends K.Stream<S>, State, UserError>() { const spaces = re(/\s*/); /** Parse by a custom function, it must return a consumed number in order to increase the position */ function parseBy<A, _S extends K.Stream<_S> = S, St = State, UErr = UserError>( f: (context: {readonly input: _S; readonly position: number; readonly state: St}) => FResult<A, UErr> ) { return new FParser(f); } function getState<St = State, UErr = UserError>(): Parser<any, St, St, UErr> { return parseBy(ctx => ({value: ctx.state, consumed: 0})); } function re<St = State, UErr = UserError>(re: RegExp): MatchRegex<St, UErr> { return new MatchRegex(re); } return { seqs, alts, bind, re, parseBy, getState, empty: new Empty<State, UserError>(), eof: new EOF<State, UserError>(), digit: re(/\d/).slice(), digits: re(/\d*/).slice(), digits1: re(/\d+/).slice(), hexDigit: re(/[A-F0-9]/i).slice(), hexDigits: re(/[A-F0-9]*/i).slice(), hexDigits1: re(/[A-F0-9]+/i).slice(), letter: re(/[A-Z]/i).slice(), letters: re(/[A-Z]*/i).slice(), letters1: re(/[A-Z]+/).slice(), spaces, spaces1: re(/\s+/), pure<A, St = State, UErr = UserError>(a: A): Parser<any, A, St, UErr> { return parseBy(_ => ({value: a, consumed: 0})); }, anyChar: new FParser<string, string, State, UserError>(ctx => { let cp = ctx.input.codePointAt(ctx.position); if (typeof cp === 'undefined') { return {error: 'EOF', consumed: 0}; } else { let c = String.fromCodePoint(cp); return { value: c, consumed: c.length }; } }), oneOf<St = State, UErr = UserError>(a: string): OneOf<St, UErr> { return new OneOf(a); }, noneOf<St = State, UErr = UserError>(a: string): NoneOf<St, UErr> { return new NoneOf(a); }, exact<_S extends K.Stream<_S> = S, St = State, UErr = UserError>(s: _S): Exact<_S, St, UErr> { return new Exact(s); }, charset<St = State, UErr = UserError>(ch: K.Charset): CharsetParser<St, UErr> { return new CharsetParser(ch); }, spaced<A, St = State, UErr = UserError>(p: Parser<string, A, St, UErr>): Parser<string, A, St, UErr> { let sp = spaces as Parser<string, any, any, any>; return seqs(sp, p, sp).at(1); }, fails<St = State, UErr = UserError>(msg: string): Parser<any, never, St, UErr> { return new FailParser(msg); }, failWith<St = State, UErr = UserError>(err: UErr): Parser<any, never, St, UErr> { return new FailParser('UserError', err); } }; function alts(): never; function alts(p: any): never; function alts<A extends [any, any, ...any[]], _S extends K.Stream<_S> = S, St = State, UErr = UserError>( ...parsers: {[I in keyof A]: Parser<_S, A[I], St, UErr>} ): Alts<_S, A[number], St, UErr>; function alts<T, _S extends K.Stream<_S> = S, St = State, UErr = UserError>( ...parsers: Array<Parser<_S, T, St, UErr>> ): Alts<_S, T, St, UErr>; function alts<_S extends K.Stream<_S> = S, St = State, UErr = UserError>(...parsers: any): Alts<_S, any, St, UErr> { return new Alts(parsers); } function seqs(): never; function seqs(p: any): never; function seqs<A extends [any, any, ...any[]], _S extends K.Stream<_S> = S, St = State, UErr = UserError>( ...parsers: {[I in keyof A]: Parser<_S, A[I], St, UErr>} ): Seqs<_S, A, St, UErr>; function seqs<T, _S extends K.Stream<_S> = S, St = State, UErr = UserError>( ...parsers: Array<Parser<_S, T, St, UErr>> ): Seqs<_S, T[], St, UErr>; function seqs<_S extends K.Stream<_S> = S, St = State, UErr = UserError>(...parsers: any): Seqs<_S, any, St, UErr> { return new Seqs(parsers); } /** Let bind, we had to disperse each let binding into single object literal because of JavaScript object literal does not guarentee the order of key. @example const P = Parsec.refine<string, 'State', 'SyntaxError'>(); let p: Parser<string, {name: string; value: number}, 'State', 'SyntaxError'> = P.bind( {name: P.re(/[A-Z_$]\w{0,}/i).slice()}, {_: P.exact('=')}, {value: P.digits1.map(Number)} ); */ function bind(): never; function bind<M extends [any, ...any[]], _S extends K.Stream<_S> = S, St = State, UErr = UserError>( ...bindings: {[I in keyof M]: {[K in keyof M[I]]: Parser<_S, M[I][K], St, UErr>}} ): Parser<_S, {[K in keyof InterU<M[number]>]: InterU<M[number]>[K]}, St, UErr>; function bind<A, _S extends K.Stream<_S> = S, St = State, UErr = UserError>( ...bindings: Array<{[k: string]: Parser<_S, A, St, UErr>}> ): Parser<_S, {[k: string]: A}, St, UErr>; function bind<_S extends K.Stream<_S> = S, St = State, UErr = UserError>( ..._bindings: any ): Parser<_S, any, St, UErr> { let bindings = _bindings as Array<{[k: string]: Parser<_S, any, St, UErr>}>; let {names, parsers} = bindings.reduce( (prev, cur) => { prev.names = prev.names.concat(Object.keys(cur)); prev.parsers = prev.parsers.concat(Object.values(cur)); return prev; }, {names: [] as string[], parsers: [] as Array<Parser<_S, any, St, UErr>>} ); let seq = new Seqs(parsers).map(values => { let a: {[k: string]: any} = {} as any; for (let i = 0; i < names.length; i++) { a[names[i]] = values[i]; } return a; }); return seq; } }
the_stack
namespace LiteMol.Visualization { export const enum CameraControlsState { NONE = -1, ROTATE = 0, ZOOM = 2, PAN = 1, TOUCH_ROTATE = 3, TOUCH_ZOOM_PAN = 4 }; // ported and modified from threejs Trackball Controls export class CameraControls { constructor(public camera: THREE.Camera, private domElement: HTMLElement, private scene: Scene) { this.init(); } enabled = true; //private screen = { left: 0, top: 0, width: 0, height: 0 }; rotateSpeed = 6; zoomSpeed = 6; panSpeed = 1.0; noRotate = false; noZoom = false; noPan = false; noRoll = true; staticMoving = true; dynamicDampingFactor = 0.2; minDistance = 1.5; maxDistance = 100000; keys = [65 /*A*/, 16 /*S*/, 17 /*D*/]; target = new THREE.Vector3(); // internals private EPS = 0.000001; private lastPosition = new THREE.Vector3(); private _state = CameraControlsState.NONE; private _keyDownState = CameraControlsState.NONE; private _prevState = CameraControlsState.NONE; private _eye = new THREE.Vector3(); private _rotateStart = new THREE.Vector3(); private _rotateEnd = new THREE.Vector3(); private _zoomStart = new THREE.Vector2(); private _zoomEnd = new THREE.Vector2(); private _touchZoomDistanceStart = 0; private _touchZoomDistanceEnd = 0; private _panStart = new THREE.Vector2(); private _panEnd = new THREE.Vector2(); // for reset private target0 = this.target.clone(); private position0 = this.camera.position.clone(); private up0 = this.camera.up.clone(); // events private changeEvent = { type: 'change', target: <any>void 0 }; private startEvent = { type: 'start', target: <any>void 0 }; private endEvent = { type: 'end', target: <any>void 0 }; events: THREE.EventDispatcher = new THREE.EventDispatcher(); private _mouseOnScreen = new THREE.Vector2(); private getMouseOnScreen() { this.scene.mouseInfo.setExactPosition(); let rs = this.scene.renderState, pos = this.scene.mouseInfo.exactPosition; this._mouseOnScreen.set(pos.x / rs.width, pos.y / rs.height); return this._mouseOnScreen; } private _mouseOnBallProjection = new THREE.Vector3(); private _objectUp = new THREE.Vector3(); private _mouseOnBall = new THREE.Vector3(); private getMouseProjectionOnBall() { this.scene.mouseInfo.setExactPosition(); let rs = this.scene.renderState, pos = this.scene.mouseInfo.exactPosition; let cX = 0.5 * rs.width, cY = 0.5 * rs.height, u = (pos.x - cX) / (rs.width * .5), v = -(pos.y - cY) / (rs.height * .5); this._mouseOnBall.set(u, v, 0.0); let length = this._mouseOnBall.length(); if (this.noRoll) { if (length < Math.SQRT1_2) { this._mouseOnBall.z = Math.sqrt(1.0 - length * length); } else { this._mouseOnBall.z = .5 / length; } } else if (length > 1.0) { this._mouseOnBall.normalize(); } else { this._mouseOnBall.z = Math.sqrt(1.0 - length * length); } this._eye.copy(this.camera.position).sub(this.target); this._mouseOnBallProjection.copy(this.camera.up).setLength(this._mouseOnBall.y) this._mouseOnBallProjection.add(this._objectUp.copy(this.camera.up).cross(this._eye).setLength(this._mouseOnBall.x)); this._mouseOnBallProjection.add(this._eye.setLength(this._mouseOnBall.z)); return this._mouseOnBallProjection; } private _rotationAxis = new THREE.Vector3(); private _rotationQuaternion = new THREE.Quaternion(); private rotateCamera() { var angle = Math.acos(this._rotateStart.dot(this._rotateEnd) / this._rotateStart.length() / this._rotateEnd.length()); if (angle) { this._rotationAxis.crossVectors(this._rotateStart, this._rotateEnd).normalize(); angle *= this.rotateSpeed; this._rotationQuaternion.setFromAxisAngle(this._rotationAxis, -angle); this._eye.applyQuaternion(this._rotationQuaternion); this.camera.up.applyQuaternion(this._rotationQuaternion); this._rotateEnd.applyQuaternion(this._rotationQuaternion); if (this.staticMoving) { this._rotateStart.copy(this._rotateEnd); } else { this._rotationQuaternion.setFromAxisAngle(this._rotationAxis, angle * (this.dynamicDampingFactor - 1.0)); this._rotateStart.applyQuaternion(this._rotationQuaternion); } } } private zoomCamera() { if (this._state === CameraControlsState.TOUCH_ZOOM_PAN) { var factor = this._touchZoomDistanceStart / this._touchZoomDistanceEnd; this._touchZoomDistanceStart = this._touchZoomDistanceEnd; this._eye.multiplyScalar(factor); } else { var factor = 1.0 - (this._zoomEnd.y - this._zoomStart.y) * this.zoomSpeed; if (factor !== 1.0 && factor > 0.0) { this._eye.multiplyScalar(factor); if (this.staticMoving) { this._zoomStart.copy(this._zoomEnd); } else { this._zoomStart.y += (this._zoomEnd.y - this._zoomStart.y) * this.dynamicDampingFactor; } } } }; private _panMouseChange = new THREE.Vector2(); private _panObjectUp = new THREE.Vector3(); private _panPan = new THREE.Vector3(); private panCamera() { this._panMouseChange.copy(this._panEnd).sub(this._panStart); if (this._panMouseChange.lengthSq()) { this._panMouseChange.multiplyScalar(this._eye.length() * this.panSpeed); this._panPan.copy(this._eye).cross(this.camera.up).setLength(this._panMouseChange.x); this._panPan.add(this._panObjectUp.copy(this.camera.up).setLength(this._panMouseChange.y)); this.camera.position.add(this._panPan); this.target.add(this._panPan); if (this.staticMoving) { this._panStart.copy(this._panEnd); } else { this._panStart.add(this._panMouseChange.subVectors(this._panEnd, this._panStart).multiplyScalar(this.dynamicDampingFactor)); } } } private _panToDelta = new THREE.Vector3(); private _panToVector = new THREE.Vector3(); panTo({x, y, z}: { x: number; y: number; z: number }) { this._panToVector.set(x, y, z) this._panToDelta.subVectors(this._panToVector, this.target); this.camera.position.add(this._panToDelta); this.camera.lookAt(this._panToVector); this.target.copy(this._panToVector); this._eye.subVectors(this.camera.position, this.target); this.lastPosition.copy(this.camera.position); if (this._panToDelta.lengthSq() > this.EPS) { this.events.dispatchEvent(this.changeEvent); } } panAndMoveToDistance({x, y, z}: { x: number; y: number; z: number }, distance: number) { this._panToVector.set(x, y, z); this._panToDelta.subVectors(this._panToVector, this.target); this.camera.position.add(this._panToDelta); this.camera.lookAt(this._panToVector); this.target.copy(this._panToVector); this._eye.subVectors(this.camera.position, this.target); this._eye.setLength(distance); this.camera.position.addVectors(this.target, this._eye); this.checkDistances(); this.lastPosition.copy(this.camera.position); this.events.dispatchEvent(this.changeEvent); } private checkDistances() { if (!this.noZoom || !this.noPan) { if (this._eye.lengthSq() > this.maxDistance * this.maxDistance) { this.camera.position.addVectors(this.target, this._eye.setLength(this.maxDistance)); } if (this._eye.lengthSq() < this.minDistance * this.minDistance) { this.camera.position.addVectors(this.target, this._eye.setLength(this.minDistance)); } } } update() { this._eye.subVectors(this.camera.position, this.target); if (!this.noRotate) { this.rotateCamera(); } if (!this.noZoom) { this.zoomCamera(); } if (!this.noPan) { this.panCamera(); } this.camera.position.addVectors(this.target, this._eye); this.checkDistances(); this.camera.lookAt(this.target); if (this.lastPosition.distanceToSquared(this.camera.position) > this.EPS) { this.events.dispatchEvent(this.changeEvent); this.lastPosition.copy(this.camera.position); } } reset() { this._state = CameraControlsState.NONE; this._prevState = CameraControlsState.NONE; this.target.copy(this.target0); this.camera.position.copy(this.position0); this.camera.up.copy(this.up0); this._eye.subVectors(this.camera.position, this.target); this.camera.lookAt(this.target); this.events.dispatchEvent(this.changeEvent); this.lastPosition.copy(this.camera.position); } getState() { return { state: this._state, prevState: this._prevState, target: this.target.clone(), objPos: this.camera.position.clone(), objUp: this.camera.up.clone(), eye: this._eye.clone(), lastPosition: this.lastPosition.clone() } } setState(state: any) { this._state = state.state; this._prevState = state.prevState; this.target.copy(state.target); this.camera.position.copy(state.objPos); this.camera.up.copy(state.objUp); this._eye.copy(state.eye); this.camera.lookAt(this.target); this.events.dispatchEvent(this.changeEvent); this.lastPosition.copy(state.lastPosition); } private keydown(event: KeyboardEvent) { if (this.enabled === false) return; window.removeEventListener('keydown', this.eventHandlers.keydown, false); window.addEventListener('keyup', this.eventHandlers.keyup, false); this._prevState = this._state; if (this._state !== CameraControlsState.NONE) { return; } else if (event.keyCode === this.keys[CameraControlsState.ROTATE] && !this.noRotate) { this._state = CameraControlsState.ROTATE; } else if (event.keyCode === this.keys[CameraControlsState.ZOOM] && !this.noZoom) { this._state = CameraControlsState.ZOOM; } else if (event.keyCode === this.keys[CameraControlsState.PAN] && !this.noPan) { this._state = CameraControlsState.PAN; } this._keyDownState = this._state; } private keyup(event: KeyboardEvent) { if (this.enabled === false) return; this._state = this._prevState; this._keyDownState = CameraControlsState.NONE; window.removeEventListener('keyup', this.eventHandlers.keyup, false); window.addEventListener('keydown', this.eventHandlers.keydown, false); } private mousedown(event: MouseEvent) { if (this.enabled === false) return; event.preventDefault(); //event.stopPropagation(); this.scene.mouseInfo.updatePosition(event.clientX, event.clientY); if (this._keyDownState !== CameraControlsState.NONE) { this._state = this._keyDownState; } if (this._state === CameraControlsState.NONE) { this._state = event.button; } if (this._state === CameraControlsState.ROTATE && !this.noRotate) { this._rotateStart.copy(this.getMouseProjectionOnBall()); this._rotateEnd.copy(this._rotateStart); } else if (this._state === CameraControlsState.ZOOM && !this.noZoom) { this._zoomStart.copy(this.getMouseOnScreen()); this._zoomEnd.copy(this._zoomStart); } else if (this._state === CameraControlsState.PAN && !this.noPan) { this._panStart.copy(this.getMouseOnScreen()); this._panEnd.copy(this._panStart) } window.addEventListener('mousemove', this.eventHandlers.mousemove, false); window.addEventListener('mouseup', this.eventHandlers.mouseup, false); this.events.dispatchEvent(this.startEvent); } mousemove(event: MouseEvent) { if (this.enabled === false) return; event.preventDefault(); this.scene.mouseInfo.updatePosition(event.clientX, event.clientY); //event.stopPropagation(); if (this._state === CameraControlsState.ROTATE && !this.noRotate) { this._rotateEnd.copy(this.getMouseProjectionOnBall()); } else if (this._state === CameraControlsState.ZOOM && !this.noZoom) { this._zoomEnd.copy(this.getMouseOnScreen()); } else if (this._state === CameraControlsState.PAN && !this.noPan) { this._panEnd.copy(this.getMouseOnScreen()); } this.update(); } mouseup(event: MouseEvent) { if (this.enabled === false) return; event.preventDefault(); //event.stopPropagation(); this._state = CameraControlsState.NONE; window.removeEventListener('mousemove', this.eventHandlers.mousemove, false); window.removeEventListener('mouseup', this.eventHandlers.mouseup, false); this.events.dispatchEvent(this.endEvent); } private touchstart(event: TouchEvent) { //console.log("trouch start"); if (this.enabled === false) return; switch (event.touches.length) { case 1: this._state = CameraControlsState.TOUCH_ROTATE; this.scene.mouseInfo.updatePosition(event.touches[0].clientX, event.touches[0].clientY); this._rotateStart.copy(this.getMouseProjectionOnBall(/*event.touches[0].clientX, event.touches[0].clientY*/)); this._rotateEnd.copy(this._rotateStart); break; case 2: this._state = CameraControlsState.TOUCH_ZOOM_PAN; var dx = event.touches[0].clientX - event.touches[1].clientX; var dy = event.touches[0].clientY - event.touches[1].clientY; this._touchZoomDistanceEnd = this._touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy); var x = (event.touches[0].clientX + event.touches[1].clientX) / 2; var y = (event.touches[0].clientY + event.touches[1].clientY) / 2; this.scene.mouseInfo.updatePosition(x, y); this._panStart.copy(this.getMouseOnScreen(/*x, y*/)); this._panEnd.copy(this._panStart); break; default: this._state = CameraControlsState.NONE; } this.events.dispatchEvent(this.startEvent); } private touchmove(event: TouchEvent) { if (this.enabled === false) return; event.preventDefault(); event.stopPropagation(); switch (event.touches.length) { case 1: this.scene.mouseInfo.updatePosition(event.touches[0].clientX, event.touches[0].clientY); this._rotateEnd.copy(this.getMouseProjectionOnBall(/*event.touches[0].clientX, event.touches[0].clientY*/)); this.update(); break; case 2: var dx = event.touches[0].clientX - event.touches[1].clientX; var dy = event.touches[0].clientY - event.touches[1].clientY; this._touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy); var x = (event.touches[0].clientX + event.touches[1].clientX) / 2; var y = (event.touches[0].clientY + event.touches[1].clientY) / 2; this.scene.mouseInfo.updatePosition(x, y); this._panEnd.copy(this.getMouseOnScreen(/*x, y*/)); this.update(); break; default: this._state = CameraControlsState.NONE; } } private touchend(event: TouchEvent) { if (this.enabled === false) return; let touches = event.touches; if (!touches.length) { touches = event.changedTouches; } switch (touches.length) { case 1: this.scene.mouseInfo.updatePosition(touches[0].clientX, touches[0].clientY); this._rotateEnd.copy(this.getMouseProjectionOnBall(/*event.touches[0].clientX, event.touches[0].clientY*/)); this._rotateStart.copy(this._rotateEnd); break; case 2: this._touchZoomDistanceStart = this._touchZoomDistanceEnd = 0; var x = (touches[0].clientX + touches[1].clientX) / 2; var y = (touches[0].clientY + touches[1].clientY) / 2; this.scene.mouseInfo.updatePosition(x, y); this._panEnd.copy(this.getMouseOnScreen(/*x, y*/)); this._panStart.copy(this._panEnd); break; } this._state = CameraControlsState.NONE; this.events.dispatchEvent(this.endEvent); } private preventContextMenu(event: Event) { event.preventDefault(); } private eventHandlers = { 'keydown': (event: KeyboardEvent) => this.keydown(event), 'keyup': (event: KeyboardEvent) => this.keyup(event), 'mousedown': (event: MouseEvent) => this.mousedown(event), 'mouseup': (event: MouseEvent) => this.mouseup(event), 'mousemove': (event: MouseEvent) => this.mousemove(event), 'touchstart': (event: TouchEvent) => this.touchstart(event), 'touchmove': (event: TouchEvent) => this.touchmove(event), 'touchend': (event: TouchEvent) => this.touchend(event) } private init() { this.domElement.addEventListener('contextmenu', this.preventContextMenu, false); this.domElement.addEventListener('mousedown', this.eventHandlers.mousedown, false); //this.domElement.addEventListener('mousewheel', mousewheel, false); //this.domElement.addEventListener('DOMMouseScroll', mousewheel, false); // firefox this.domElement.addEventListener('touchstart', this.eventHandlers.touchstart, false); this.domElement.addEventListener('touchend', this.eventHandlers.touchend, false); this.domElement.addEventListener('touchmove', this.eventHandlers.touchmove, false); window.addEventListener('keydown', this.eventHandlers.keydown, false); // window.addEventListener('keyup', keyup, false); //this.handleResize(); // force an update at start this.update(); } destroy() { this.domElement.removeEventListener('contextmenu', this.preventContextMenu, false); this.domElement.removeEventListener('mousedown', this.eventHandlers.mousedown, false); //scope.domElement.removeEventListener('mousewheel', onMouseWheel, false); //scope.domElement.removeEventListener('DOMMouseScroll', onMouseWheel, false); // firefox //scope.domElement.removeEventListener('keydown', keydown, false); window.removeEventListener('keydown', this.eventHandlers.keydown, false); //scope.domElement.removeEventListener('keyup', keyup, false); this.domElement.removeEventListener('touchstart', this.eventHandlers.touchstart, false); this.domElement.removeEventListener('touchend', this.eventHandlers.touchend, false); this.domElement.removeEventListener('touchmove', this.eventHandlers.touchmove, false); this.camera = <any>void 0; this.domElement = <any>void 0; }; } }
the_stack
import * as cxschema from '@aws-cdk/cloud-assembly-schema'; import * as cxapi from '@aws-cdk/cx-api'; import * as AWS from 'aws-sdk'; import { Mode, SdkProvider } from '../api'; import { ContextProviderPlugin } from './provider'; /** * Provides load balancer context information. */ export class LoadBalancerContextProviderPlugin implements ContextProviderPlugin { constructor(private readonly aws: SdkProvider) { } async getValue(query: cxschema.LoadBalancerContextQuery): Promise<cxapi.LoadBalancerContextResponse> { const options = { assumeRoleArn: query.lookupRoleArn }; const elbv2 = (await this.aws.forEnvironment(cxapi.EnvironmentUtils.make(query.account, query.region), Mode.ForReading, options)).elbv2(); if (!query.loadBalancerArn && !query.loadBalancerTags) { throw new Error('The load balancer lookup query must specify either `loadBalancerArn` or `loadBalancerTags`'); } const loadBalancers = await findLoadBalancers(elbv2, query); if (loadBalancers.length === 0) { throw new Error(`No load balancers found matching ${JSON.stringify(query)}`); } if (loadBalancers.length > 1) { throw new Error(`Multiple load balancers found matching ${JSON.stringify(query)} - please provide more specific criteria`); } const loadBalancer = loadBalancers[0]; const ipAddressType = loadBalancer.IpAddressType === 'ipv4' ? cxapi.LoadBalancerIpAddressType.IPV4 : cxapi.LoadBalancerIpAddressType.DUAL_STACK; return { loadBalancerArn: loadBalancer.LoadBalancerArn!, loadBalancerCanonicalHostedZoneId: loadBalancer.CanonicalHostedZoneId!, loadBalancerDnsName: loadBalancer.DNSName!, vpcId: loadBalancer.VpcId!, securityGroupIds: loadBalancer.SecurityGroups ?? [], ipAddressType: ipAddressType, }; } } // Decreases line length type LoadBalancerListenerQuery = cxschema.LoadBalancerListenerContextQuery; type LoadBalancerListenerResponse = cxapi.LoadBalancerListenerContextResponse; /** * Provides load balancer listener context information */ export class LoadBalancerListenerContextProviderPlugin implements ContextProviderPlugin { constructor(private readonly aws: SdkProvider) { } async getValue(query: LoadBalancerListenerQuery): Promise<LoadBalancerListenerResponse> { const options = { assumeRoleArn: query.lookupRoleArn }; const elbv2 = (await this.aws.forEnvironment(cxapi.EnvironmentUtils.make(query.account, query.region), Mode.ForReading, options)).elbv2(); if (!query.listenerArn && !query.loadBalancerArn && !query.loadBalancerTags) { throw new Error('The load balancer listener query must specify at least one of: `listenerArn`, `loadBalancerArn` or `loadBalancerTags`'); } return query.listenerArn ? this.getListenerByArn(elbv2, query) : this.getListenerByFilteringLoadBalancers(elbv2, query); } /** * Look up a listener by querying listeners for query's listener arn and then * resolve its load balancer for the security group information. */ private async getListenerByArn(elbv2: AWS.ELBv2, query: LoadBalancerListenerQuery) { const listenerArn = query.listenerArn!; const listenerResults = await elbv2.describeListeners({ ListenerArns: [listenerArn] }).promise(); const listeners = (listenerResults.Listeners ?? []); if (listeners.length === 0) { throw new Error(`No load balancer listeners found matching arn ${listenerArn}`); } const listener = listeners[0]; const loadBalancers = await findLoadBalancers(elbv2, { ...query, loadBalancerArn: listener.LoadBalancerArn!, }); if (loadBalancers.length === 0) { throw new Error(`No associated load balancer found for listener arn ${listenerArn}`); } const loadBalancer = loadBalancers[0]; return { listenerArn: listener.ListenerArn!, listenerPort: listener.Port!, securityGroupIds: loadBalancer.SecurityGroups ?? [], }; } /** * Look up a listener by starting from load balancers, filtering out * unmatching load balancers, and then by querying the listeners of each load * balancer and filtering out unmatching listeners. */ private async getListenerByFilteringLoadBalancers(elbv2: AWS.ELBv2, args: LoadBalancerListenerQuery) { // Find matching load balancers const loadBalancers = await findLoadBalancers(elbv2, args); if (loadBalancers.length === 0) { throw new Error(`No associated load balancers found for load balancer listener query ${JSON.stringify(args)}`); } return this.findMatchingListener(elbv2, loadBalancers, args); } /** * Finds the matching listener from the list of load balancers. This will * error unless there is exactly one match so that the user is prompted to * provide more specific criteria rather than us providing a nondeterministic * result. */ private async findMatchingListener(elbv2: AWS.ELBv2, loadBalancers: AWS.ELBv2.LoadBalancers, query: LoadBalancerListenerQuery) { const loadBalancersByArn = indexLoadBalancersByArn(loadBalancers); const loadBalancerArns = Object.keys(loadBalancersByArn); const matches = Array<cxapi.LoadBalancerListenerContextResponse>(); for await (const listener of describeListenersByLoadBalancerArn(elbv2, loadBalancerArns)) { const loadBalancer = loadBalancersByArn[listener.LoadBalancerArn!]; if (listenerMatchesQueryFilter(listener, query) && loadBalancer) { matches.push({ listenerArn: listener.ListenerArn!, listenerPort: listener.Port!, securityGroupIds: loadBalancer.SecurityGroups ?? [], }); } } if (matches.length === 0) { throw new Error(`No load balancer listeners found matching ${JSON.stringify(query)}`); } if (matches.length > 1) { throw new Error(`Multiple load balancer listeners found matching ${JSON.stringify(query)} - please provide more specific criteria`); } return matches[0]; } } /** * Find load balancers by the given filter args. */ async function findLoadBalancers(elbv2: AWS.ELBv2, args: cxschema.LoadBalancerFilter) { // List load balancers let loadBalancers = await describeLoadBalancers(elbv2, { LoadBalancerArns: args.loadBalancerArn ? [args.loadBalancerArn] : undefined, }); // Filter by load balancer type loadBalancers = loadBalancers.filter(lb => lb.Type === args.loadBalancerType); // Filter by load balancer tags if (args.loadBalancerTags) { loadBalancers = await filterLoadBalancersByTags(elbv2, loadBalancers, args.loadBalancerTags); } return loadBalancers; } /** * Helper to paginate over describeLoadBalancers * @internal */ export async function describeLoadBalancers(elbv2: AWS.ELBv2, request: AWS.ELBv2.DescribeLoadBalancersInput) { const loadBalancers = Array<AWS.ELBv2.LoadBalancer>(); let page: AWS.ELBv2.DescribeLoadBalancersOutput | undefined; do { page = await elbv2.describeLoadBalancers({ ...request, Marker: page?.NextMarker, }).promise(); loadBalancers.push(...Array.from(page.LoadBalancers ?? [])); } while (page.NextMarker); return loadBalancers; } /** * Describes the tags of each load balancer and returns the load balancers that * match the given tags. */ async function filterLoadBalancersByTags(elbv2: AWS.ELBv2, loadBalancers: AWS.ELBv2.LoadBalancers, loadBalancerTags: cxschema.Tag[]) { const loadBalancersByArn = indexLoadBalancersByArn(loadBalancers); const loadBalancerArns = Object.keys(loadBalancersByArn); const matchingLoadBalancers = Array<AWS.ELBv2.LoadBalancer>(); // Consume the items of async generator. for await (const tags of describeTags(elbv2, loadBalancerArns)) { if (tagsMatch(tags, loadBalancerTags) && loadBalancersByArn[tags.ResourceArn!]) { matchingLoadBalancers.push(loadBalancersByArn[tags.ResourceArn!]); } } return matchingLoadBalancers; } /** * Generator function that yields `TagDescriptions`. The API doesn't support * pagination, so this generator breaks the resource list into chunks and issues * the appropriate requests, yielding each tag description as it receives it. * @internal */ export async function* describeTags(elbv2: AWS.ELBv2, resourceArns: string[]) { // Max of 20 resource arns per request. const chunkSize = 20; for (let i = 0; i < resourceArns.length; i += chunkSize) { const chunk = resourceArns.slice(i, Math.min(i + chunkSize, resourceArns.length)); const chunkTags = await elbv2.describeTags({ ResourceArns: chunk, }).promise(); for (const tag of chunkTags.TagDescriptions ?? []) { yield tag; } } } /** * Determines if the given TagDescription matches the required tags. * @internal */ export function tagsMatch(tagDescription: AWS.ELBv2.TagDescription, requiredTags: cxschema.Tag[]) { const tagsByName: Record<string, string | undefined> = {}; for (const tag of tagDescription.Tags ?? []) { tagsByName[tag.Key!] = tag.Value; } for (const tag of requiredTags) { if (tagsByName[tag.key] !== tag.value) { return false; } } return true; } /** * Async generator that produces listener descriptions by traversing the * pagination. Because describeListeners only lets you search by one load * balancer arn at a time, we request them individually and yield the listeners * as they come in. * @internal */ export async function* describeListenersByLoadBalancerArn(elbv2: AWS.ELBv2, loadBalancerArns: string[]) { for (const loadBalancerArn of loadBalancerArns) { let page: AWS.ELBv2.DescribeListenersOutput | undefined; do { page = await elbv2.describeListeners({ LoadBalancerArn: loadBalancerArn, Marker: page?.NextMarker, }).promise(); for (const listener of page.Listeners ?? []) { yield listener; } } while (page.NextMarker); } } /** * Determines if a listener matches the query filters. */ function listenerMatchesQueryFilter(listener: AWS.ELBv2.Listener, args: cxschema.LoadBalancerListenerContextQuery): boolean { if (args.listenerPort && listener.Port !== args.listenerPort) { // No match. return false; } if (args.listenerProtocol && listener.Protocol !== args.listenerProtocol) { // No match. return false; } return true; } /** * Returns a record of load balancers indexed by their arns */ function indexLoadBalancersByArn(loadBalancers: AWS.ELBv2.LoadBalancer[]): Record<string, AWS.ELBv2.LoadBalancer> { const loadBalancersByArn: Record<string, AWS.ELBv2.LoadBalancer> = {}; for (const loadBalancer of loadBalancers) { loadBalancersByArn[loadBalancer.LoadBalancerArn!] = loadBalancer; } return loadBalancersByArn; }
the_stack
import { TFormulaSchemaUnitInput, TSchemaUnitInput, TViewCreateInput } from '@nishans/fabricator'; import { DateViewFiltersValue, RelationSchemaUnit, RollupSchemaUnit } from '@nishans/types'; import { v4 as uuidv4 } from 'uuid'; import { Page } from '../../../libs/Api/Block'; import { purpose, source, status, subject } from '../data'; import { adders, CommonMultiSelectSchema, counterFormula, curriculumInfoSchemaUnits, goalViewItem } from '../util'; const CommonMultiSelectSchemaInput: TSchemaUnitInput[] = [ { type: 'multi_select', name: 'Purpose', options: purpose.map((purpose) => ({ ...purpose, id: uuidv4() })) }, { type: 'multi_select', name: 'Subject', options: subject.map(({ title, color }) => ({ value: title, color, id: uuidv4() })) }, { type: 'multi_select', name: 'Source', options: source.map((source) => ({ ...source, id: uuidv4() })) } ]; function goalProgress (goal_number: number): TFormulaSchemaUnitInput { return { type: 'formula', name: `Goal ${goal_number} Progress`, formula: [ { function: 'round', args: [ { function: 'multiply', args: [ { function: 'divide', args: [ { property: `Goal ${goal_number} Steps` }, { function: 'toNumber', args: [ { property: `Goal ${goal_number} Total Steps` } ] } ] }, 100 ] } ] }, 'object' ] }; } export const tasksTableViews = (name: string, value: DateViewFiltersValue): TViewCreateInput => { return { type: 'table', name, schema_units: [ { type: 'formula', name: 'On', sort: 'descending' }, { type: 'title', name: 'Task', format: 300, aggregation: 'count' }, ...CommonMultiSelectSchema, ...goalViewItem(1), ...goalViewItem(2), ...goalViewItem(3) ], filters: [ { type: 'formula', name: 'On', filter: { operator: 'date_is', value: { value, type: 'relative' } } } ] }; }; const tasksBoardViews = (name: string): TViewCreateInput => { return { type: 'board', name, board_cover_size: 'medium', group_by: name, schema_units: [ { type: 'title', name: 'Task', format: false, aggregation: 'count' }, { type: 'formula', name: 'On', sort: 'descending' }, ...(CommonMultiSelectSchema as any) ] }; }; export default async function step2 (target_page: Page) { const goals_collection_id = uuidv4(), goals_cvp_id = uuidv4(), tasks_collection_id = uuidv4(), tasks_cvp_id = uuidv4(); const task2goalRelation = (index: number): RelationSchemaUnit => { return { type: 'relation', collection_id: goals_collection_id, name: `Goal ${index}`, property: `task_${index}` }; }; const task2goalRollup = (index: number): RollupSchemaUnit => { return { collection_id: goals_collection_id, type: 'rollup', name: `Goal ${index} Total Steps`, aggregation: 'sum', relation_property: `goal_${index}`, target_property: 'total_steps', target_property_type: 'number' }; }; const goal2taskTotalTasksRollup = (index: number): RollupSchemaUnit => { return { collection_id: tasks_collection_id, type: 'rollup', name: `Total Tasks ${index}`, aggregation: 'count', relation_property: `task_${index}`, target_property: 'title', target_property_type: 'number' }; }; const goal2taskCompletedStepsRollup = (index: number): RollupSchemaUnit => { return { collection_id: tasks_collection_id, type: 'rollup', name: `Completed Steps ${index}`, aggregation: 'sum', relation_property: `task_${index}`, target_property: `goal_${index}_steps`, target_property_type: 'number' }; }; if (target_page) { const { collection_view_page } = await target_page.createBlocks([ { type: 'collection_view_page', name: [ [ 'Reading List' ] ], icon: 'https://notion-emojis.s3-us-west-2.amazonaws.com/v0/svg-twitter/1f4da.svg', rows: [], views: [ { type: 'gallery', name: 'All Books', gallery_cover_size: 'large', gallery_cover: { type: 'property', property: 'cover' }, schema_units: [ { type: 'title', name: 'Title', sort: 'ascending' }, { type: 'multi_select', name: 'Publisher' }, { type: 'text', name: 'Instructor' }, { type: 'multi_select', name: 'Subject', format: true, aggregation: 'unique' }, { type: 'select', name: 'Priority', format: true }, { type: 'select', name: 'Status', format: true }, { type: 'select', name: 'Phase', format: true }, { type: 'formula', name: 'Urgency', sort: 'descending', format: false } ] } ], schema: [ { type: 'multi_select', name: 'Publisher', options: [] }, { type: 'text', name: 'Instructor' }, { type: 'file', name: 'Cover' }, { type: 'url', name: 'Source' }, ...curriculumInfoSchemaUnits, { type: 'number', name: 'Pages' }, { type: 'number', name: 'Chapters' } ] }, { type: 'collection_view_page', name: [ [ 'Course List' ] ], rows: [], icon: 'https://notion-emojis.s3-us-west-2.amazonaws.com/v0/svg-twitter/1f4dd.svg', views: [ { type: 'gallery', name: 'All Books', gallery_cover_size: 'large', gallery_cover: { type: 'property', property: 'cover' }, schema_units: [ { type: 'title', name: 'Title', sort: 'ascending' }, { type: 'multi_select', name: 'Publisher' }, { type: 'text', name: 'Instructor' }, { type: 'multi_select', name: 'Subject', format: true, aggregation: 'unique' }, { type: 'select', name: 'Priority', format: true }, { type: 'select', name: 'Status', format: true }, { type: 'select', name: 'Phase', format: true }, { type: 'formula', name: 'Urgency', sort: 'descending', format: false } ] } ], schema: [ { type: 'multi_select', name: 'Publisher', options: [] }, { type: 'text', name: 'Instructor' }, { type: 'file', name: 'Cover' }, { type: 'url', name: 'Source' }, ...curriculumInfoSchemaUnits, { type: 'number', name: 'Videos' }, { type: 'number', name: 'Duration' }, { type: 'number', name: 'Chapters' } ] }, { id: goals_cvp_id, type: 'collection_view_page', name: [ [ 'Goals' ] ], icon: 'https://notion-emojis.s3-us-west-2.amazonaws.com/v0/svg-twitter/1f44a-1f3fc.svg', collection_id: goals_collection_id, rows: [], views: [ { type: 'table', name: 'Current Minimalistic', schema_units: [ // Progress schema_unit was referenced later /* { type: 'formula', name: 'Progress', format: 150, aggregation: 'average', sort: 'descending' }, */ { type: 'title', name: 'Goal', format: 300, aggregation: 'count' }, ...CommonMultiSelectSchema ], filters: [ { type: 'select', name: 'Status', filter: { operator: 'enum_is', value: { type: 'exact', value: 'Completing' } } } ] }, { type: 'table', name: 'Completed', schema_units: [ { type: 'date', name: 'Completed At', sort: 'descending', format: 200 }, { type: 'title', name: 'Goal', format: 300, aggregation: 'count' }, ...CommonMultiSelectSchema ], filters: [ { type: 'select', name: 'Status', filter: { operator: 'enum_is', value: { type: 'exact', value: 'Completed' } } } /* { type: 'formula', name: 'Progress', filter: { operator: 'number_less_than', value: { type: 'exact', value: 100 } } } */ ] } ], schema: [ { type: 'created_time', name: 'Created' }, ...CommonMultiSelectSchemaInput, { type: 'select', name: 'Status', options: status.map((status) => ({ ...status, id: uuidv4() })) }, { type: 'title', name: 'Goal' }, { type: 'date', name: 'Completed At' }, { type: 'number', name: 'Total Steps' }, { type: 'formula', name: 'Status Counter', formula: counterFormula('Status', [ 'Completing', 'To Complete' ]) } ] }, { id: tasks_cvp_id, type: 'collection_view_page', name: [ [ 'Tasks' ] ], icon: 'https://notion-emojis.s3-us-west-2.amazonaws.com/v0/svg-twitter/1f446-1f3fc.svg', collection_id: tasks_collection_id, rows: [], schema: [ { type: 'title', name: 'Task' }, ...CommonMultiSelectSchemaInput, task2goalRelation(1), task2goalRelation(2), task2goalRelation(3), task2goalRollup(1), task2goalRollup(2), task2goalRollup(3), { type: 'number', name: 'Goal 1 Steps' }, { type: 'number', name: 'Goal 2 Steps' }, { type: 'number', name: 'Goal 3 Steps' }, { type: 'date', name: 'Custom Date' }, { type: 'created_time', name: 'Created' }, { type: 'formula', name: 'On', formula: [ { function: 'if', args: [ { function: 'empty', args: [ { property: 'Custom Date' } ] }, { property: 'Created' }, { property: 'Custom Date' } ] }, 'object' ] }, goalProgress(1), goalProgress(2), goalProgress(3) ], views: [ tasksTableViews('Today', 'today'), tasksTableViews('Yesterday', 'yesterday'), tasksTableViews('Weekly', 'one_week_ago'), tasksBoardViews('Purpose'), tasksBoardViews('Subject'), { type: 'calendar', name: 'Monthly Calendar', calendar_by: 'On', schema_units: [ { type: 'multi_select', name: 'Purpose' }, { type: 'multi_select', name: 'Subject' }, { type: 'formula', name: 'On', sort: 'ascending', format: false } ] } ] } ]); const goals_cvp = collection_view_page.get(goals_cvp_id); if (goals_cvp) { const goals_collection = await goals_cvp.getCollection(); if (goals_collection) { await goals_collection.updateSchemaUnits((schema_unit) => { switch (schema_unit.schema_id) { case 'task_1': return { name: 'Task 1' }; case 'task_2': return { name: 'Task 2' }; case 'task_3': return { name: 'Task 3' }; default: false; } }); goals_collection.createSchemaUnits([ goal2taskCompletedStepsRollup(1), goal2taskCompletedStepsRollup(2), goal2taskCompletedStepsRollup(3), goal2taskTotalTasksRollup(1), goal2taskTotalTasksRollup(2), goal2taskTotalTasksRollup(3), { type: 'formula', name: 'Completed Steps', formula: adders([ { property: 'Completed Steps 1' }, { property: 'Completed Steps 2' }, { property: 'Completed Steps 3' } ]) }, { type: 'formula', name: 'Total Tasks', formula: adders([ { property: 'Total Tasks 1' }, { property: 'Total Tasks 2' }, { property: 'Total Tasks 3' } ]) }, { type: 'formula', name: 'Progress', formula: [ { function: 'if', args: [ { function: 'equal', args: [ { property: 'Total Steps' }, 0 ] }, 0, { function: 'round', args: [ { function: 'multiply', args: [ { function: 'divide', args: [ { property: 'Completed Steps' }, { property: 'Total Steps' } ] }, 100 ] } ] } ] }, 'object' ] } ]); // fs.writeFileSync(__dirname+"/data.json", JSON.stringify(target_page?.stack), 'utf-8'); } } } }
the_stack
import { HttpResponse, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs';import { HttpOptions } from '../../types'; import * as models from '../../models'; export interface UsersAPIClientInterface { /** * Arguments object for method `getUsers`. */ getUsersParams?: { /** The integer ID of the last User that you've seen. */ since?: number, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get all users. * This provides a dump of every user, in the order that they signed up for GitHub. * Note: Pagination is powered exclusively by the since parameter. Use the Link * header to get the URL for the next page of users. * * Response generated for [ 200 ] HTTP response code. */ getUsers( args?: UsersAPIClientInterface['getUsersParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUsers( args?: UsersAPIClientInterface['getUsersParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUsers( args?: UsersAPIClientInterface['getUsersParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; /** * Arguments object for method `getUsersUsername`. */ getUsersUsernameParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Get a single user. * Response generated for [ 200 ] HTTP response code. */ getUsersUsername( args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUsersUsername( args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUsersUsername( args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; /** * Arguments object for method `getUsersUsernameEvents`. */ getUsersUsernameEventsParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * If you are authenticated as the given user, you will see your private events. Otherwise, you'll only see public events. * Response generated for [ default ] HTTP response code. */ getUsersUsernameEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getUsersUsernameEventsOrg`. */ getUsersUsernameEventsOrgParams?: { /** Name of user. */ username: string, org: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * This is the user's organization dashboard. You must be authenticated as the user to view this. * Response generated for [ default ] HTTP response code. */ getUsersUsernameEventsOrg( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameEventsOrg( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameEventsOrg( args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getUsersUsernameFollowers`. */ getUsersUsernameFollowersParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List a user's followers * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameFollowers( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUsersUsernameFollowers( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUsersUsernameFollowers( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; /** * Arguments object for method `getUsersUsernameFollowingTargetUser`. */ getUsersUsernameFollowingTargetUserParams?: { /** Name of user. */ username: string, /** Name of user. */ targetUser: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * Check if one user follows another. * Response generated for [ 204 ] HTTP response code. */ getUsersUsernameFollowingTargetUser( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameFollowingTargetUser( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameFollowingTargetUser( args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getUsersUsernameGists`. */ getUsersUsernameGistsParams?: { /** Name of user. */ username: string, /** * The time should be passed in as UTC in the ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. * Example: "2012-10-09T23:39:01Z". * */ since?: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List a users gists. * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameGists( args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gists>; getUsersUsernameGists( args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gists>>; getUsersUsernameGists( args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gists>>; /** * Arguments object for method `getUsersUsernameKeys`. */ getUsersUsernameKeysParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List public keys for a user. * Lists the verified public keys for a user. This is accessible by anyone. * * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameKeys( args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gitignore>; getUsersUsernameKeys( args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gitignore>>; getUsersUsernameKeys( args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gitignore>>; /** * Arguments object for method `getUsersUsernameOrgs`. */ getUsersUsernameOrgsParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List all public organizations for a user. * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameOrgs( args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gitignore>; getUsersUsernameOrgs( args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gitignore>>; getUsersUsernameOrgs( args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gitignore>>; /** * Arguments object for method `getUsersUsernameReceivedEvents`. */ getUsersUsernameReceivedEventsParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * These are events that you'll only see public events. * Response generated for [ default ] HTTP response code. */ getUsersUsernameReceivedEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameReceivedEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameReceivedEvents( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getUsersUsernameReceivedEventsPublic`. */ getUsersUsernameReceivedEventsPublicParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List public events that a user has received * Response generated for [ default ] HTTP response code. */ getUsersUsernameReceivedEventsPublic( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameReceivedEventsPublic( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameReceivedEventsPublic( args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getUsersUsernameRepos`. */ getUsersUsernameReposParams?: { /** Name of user. */ username: string, /** If not set, server will use the default value: all */ type?: ('all' | 'public' | 'private' | 'forks' | 'sources' | 'member'), /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List public repositories for the specified user. * Response generated for [ 200 ] HTTP response code. */ getUsersUsernameRepos( args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repos>; getUsersUsernameRepos( args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repos>>; getUsersUsernameRepos( args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repos>>; /** * Arguments object for method `getUsersUsernameStarred`. */ getUsersUsernameStarredParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List repositories being starred by a user. * Response generated for [ default ] HTTP response code. */ getUsersUsernameStarred( args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameStarred( args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameStarred( args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `getUsersUsernameSubscriptions`. */ getUsersUsernameSubscriptionsParams?: { /** Name of user. */ username: string, /** * You can check the current version of media type in responses. * */ xGitHubMediaType?: string, /** Is used to set specified media type. */ accept?: string, xRateLimit?: number, xRateLimitRemaining?: number, xRateLimitReset?: number, xGitHubRequestId?: number, }; /** * List repositories being watched by a user. * Response generated for [ default ] HTTP response code. */ getUsersUsernameSubscriptions( args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUsersUsernameSubscriptions( args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUsersUsernameSubscriptions( args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; }
the_stack
import { DefaultSerializer, PairSerializer, Serializer, Collab, InitToken, isRuntime, Pre, AbstractCListCObject, CVariable, CSet, MovableCList, MovableCListEventsRecord, CObject, CMessenger, Optional, PositionedList, } from "@collabs/core"; import { ArrayListItemManager, CreatedListPositionSerializer, ListPosition, ListPositionSerializer, ListPositionSource, } from "./list_position_source"; export class MovableMutCListEntry< C extends Collab, VarT extends CVariable<ListPosition> > extends CObject { readonly value: C; readonly position: VarT; constructor(initToken: InitToken, value: Pre<C>, position: Pre<VarT>) { super(initToken); this.value = this.addChild("", value); this.position = this.addChild("0", position); } } export class MovableMutCListFromSet< C extends Collab, InsertArgs extends unknown[], VarT extends CVariable<ListPosition>, SetT extends CSet< MovableMutCListEntry<C, VarT>, [ListPosition, InsertArgs] >, Events extends MovableCListEventsRecord<C> = MovableCListEventsRecord<C> > extends AbstractCListCObject<C, InsertArgs, Events> implements MovableCList<C, InsertArgs>, PositionedList { protected readonly set: SetT; protected readonly createdPositionMessenger: CMessenger< [counter: number, startValueIndex: number, metadata: Uint8Array | null] >; protected readonly positionSource: ListPositionSource< MovableMutCListEntry<C, VarT>[] >; /** * variableConstructor should make sure that the * variable's initial value is initialValue, without * dispatching a Set event (i.e., pass it in VarT's * constructor, not as an operation, which wouldn't * make sense anyway). * * The set returned by setCallback must satisfy: * - Immediately after constructing with initial values, * values() returns them in the order corresponding to setInitialValuesArgs. */ constructor( initToken: InitToken, setCallback: ( setValueConstructor: ( setValueInitToken: InitToken, ...setValueArgs: [ListPosition, InsertArgs] ) => MovableMutCListEntry<C, VarT>, setInitialValuesArgs: [ListPosition, InsertArgs][], setArgsSerializer: Serializer<[ListPosition, InsertArgs]> ) => Pre<SetT>, private readonly variableConstructor: ( variableInitToken: InitToken, initialValue: ListPosition, variableSerializer: Serializer<ListPosition> ) => VarT, private readonly valueConstructor: ( valueInitToken: InitToken, ...args: InsertArgs ) => C, initialValuesArgs: InsertArgs[] = [], argsSerializer: Serializer<InsertArgs> = DefaultSerializer.getInstance() ) { super(initToken); const setInitialValuesArgs: [ListPosition, InsertArgs][] = initialValuesArgs.map((args, index) => [["", 0, index + 1], args]); this.set = this.addChild( "", setCallback( this.setValueConstructor.bind(this), setInitialValuesArgs, new PairSerializer(ListPositionSerializer.instance, argsSerializer) ) ); // For initial values, note that this.set Add events don't get dispatched. // Thus we don't have to worry that positionSource is not yet created for // them. // Here we use the assumption (stated in constructor docs) that values() // are in order. this.positionSource = new ListPositionSource( this.runtime.replicaID, ArrayListItemManager.getInstance(), [...this.set] ); this.createdPositionMessenger = this.addChild( "m", Pre(CMessenger)(CreatedListPositionSerializer.instance) ); this.createdPositionMessenger.on("Message", (e) => { const [counter, startValueIndex, metadata] = e.message; const pos: ListPosition = [e.meta.sender, counter, startValueIndex]; this.positionSource.receivePositions(pos, 1, metadata); }); // Maintain positionSource's values as a cache of // of the currently set locations, mapping to // the corresponding entry. // Also dispatch our own events. this.set.on("Add", (event) => { this.positionSource.add(event.value.position.value, [event.value]); this.emit("Insert", { startIndex: this.positionSource.findPosition( event.value.position.value )[0], count: 1, meta: event.meta, }); }); this.set.on("Delete", (event) => { this.positionSource.delete(event.value.position.value); this.emit("Delete", { startIndex: this.positionSource.findPosition( event.value.position.value )[0], count: 1, deletedValues: [event.value.value], meta: event.meta, }); }); } private setValueConstructor( setValueInitToken: InitToken, position: ListPosition, args: InsertArgs ) { const entry = new MovableMutCListEntry<C, VarT>( setValueInitToken, (valueInitToken) => this.valueConstructor(valueInitToken, ...args), (variableInitToken) => this.variableConstructor( variableInitToken, position, ListPositionSerializer.instance ) ); entry.position.on("Set", (event) => { // Maintain positionSource's values as a cache of // of the currently set locations, mapping to // the corresponding entry. // Also dispatch our own events. // Note that move is the only time variable.set // is called; setting the initial state is done // in the variableConstructor, not as a // variable.set operation, so it will not emit // a Set event. this.positionSource.delete(event.previousValue); this.positionSource.add(entry.position.value, [entry]); this.emit("Move", { startIndex: this.positionSource.findPosition(event.previousValue)[0], count: 1, resultingStartIndex: this.positionSource.findPosition( entry.position.value )[0], meta: event.meta, }); }); return entry; } insert(index: number, ...args: InsertArgs): C | undefined { const prevPos = index === 0 ? null : this.positionSource.getPosition(index - 1); // OPT: bulk inserts? Can just do createPositions once and deliver the // count on other side. const [counter, startValueIndex, metadata] = this.positionSource.createPositions(prevPos); const pos: ListPosition = [ this.runtime.replicaID, counter, startValueIndex, ]; this.createdPositionMessenger.sendMessage([ counter, startValueIndex, metadata, ]); return this.set.add(pos, args)?.value; } /** * Note: event will show as singleton deletes. * * @param startIndex [description] * @param count=1 [description] */ delete(startIndex: number, count = 1): void { if (count < 0 || !Number.isInteger(count)) { throw new Error(`invalid count: ${count}`); } // Get the values to delete. const toDelete = new Array<MovableMutCListEntry<C, VarT>>(count); for (let i = 0; i < count; i++) { const [item, offset] = this.positionSource.getItem(startIndex + i); toDelete[i] = item[offset]; } // Delete them. for (const value of toDelete) { this.set.delete(value); } } /** * Note: event will show as singleton moves. * * @param startIndex [description] * @param insertionIndex [description] * @param count=1 [description] * @return [description] */ move(startIndex: number, insertionIndex: number, count = 1): number { // Positions to insert at. const prevPos = insertionIndex === 0 ? null : this.positionSource.getPosition(insertionIndex - 1); const [counter, startValueIndex, metadata] = this.positionSource.createPositions(prevPos); this.createdPositionMessenger.sendMessage([ counter, startValueIndex, metadata, ]); // Values to move. const toMove = new Array<MovableMutCListEntry<C, VarT>>(count); for (let i = 0; i < count; i++) { // OPT: actually use items here. const [item, offset] = this.positionSource.getItem(startIndex + i); toMove[i] = item[offset]; } // Move them. for (let i = 0; i < count; i++) { toMove[i].position.set([ this.runtime.replicaID, counter, startValueIndex + i, ]); } // Return the new index of toMove[0]. return this.positionSource.findPosition([ this.runtime.replicaID, counter, startValueIndex, ])[0]; } get(index: number): C { const [item, offset] = this.positionSource.getItem(index); return item[offset].value; } *values(): IterableIterator<C> { for (const item of this.positionSource.items()) { for (const entry of item) { yield entry.value; } } } get length(): number { return this.set.size; } getPosition(index: number): string { const pos = this.positionSource.getPosition(index); return JSON.stringify(pos); } findPosition(position: string): [geIndex: number, isPresent: boolean] { const pos = <ListPosition>JSON.parse(position); return this.positionSource.findPosition(pos); } indexOf(searchElement: C, fromIndex = 0): number { // Avoid errors from searchElement.parent in case it // is the root. if (isRuntime(searchElement.parent)) return -1; if (this.set.has(searchElement.parent as MovableMutCListEntry<C, VarT>)) { const position = (searchElement.parent as MovableMutCListEntry<C, VarT>) .position.value; const index = this.positionSource.findPosition(position)[0]; if (fromIndex < 0) fromIndex += this.length; if (index >= fromIndex) return index; } return -1; } lastIndexOf(searchElement: C, fromIndex = this.length - 1): number { const index = this.indexOf(searchElement); if (index !== -1) { if (fromIndex < 0) fromIndex += this.length; if (index <= fromIndex) return index; } return -1; } includes(searchElement: C, fromIndex = 0): boolean { return this.indexOf(searchElement, fromIndex) !== -1; } /** * Returns a string "key" that uniquely identifies value and that does * not change when the value moves (either due to insertions/deletions * in front of it, or due to move operations). * * Useful for e.g. React lists - use the return value as the key. */ getKey(value: C): string { return (<Collab>value.parent).name; } canGC(): boolean { // OPT: return true if not yet mutated. // Also, note in docs that this won't be true even if empty, due to // tombstones. return false; } protected saveObject(): Uint8Array { return this.positionSource.save(); } protected loadObject(saveData: Optional<Uint8Array>) { if (!saveData.isPresent) return; // Note this.set is already loaded. Just need to load positionSource. // For filling in positionSource's values, create a map from positions // to entries. const entriesByPosition = new Map< string, Map<number, MovableMutCListEntry<C, VarT>>[] >(); for (const entry of this.set) { const pos = entry.position.value; let bySender = entriesByPosition.get(pos[0]); if (bySender === undefined) { bySender = []; entriesByPosition.set(pos[0], bySender); } let byCounter = bySender[pos[1]]; if (byCounter === undefined) { byCounter = new Map(); bySender[pos[1]] = byCounter; } byCounter.set(pos[2], entry); } function nextItem(count: number, startPos: ListPosition) { const bySender = entriesByPosition.get(startPos[0])!; const byCounter = bySender[startPos[1]]; const item = new Array<MovableMutCListEntry<C, VarT>>(count); for (let i = 0; i < count; i++) { item[i] = byCounter.get(startPos[2] + i)!; } return item; } this.positionSource.load(saveData.get(), nextItem); } }
the_stack
import * as React from "react"; import * as PropTypes from "prop-types"; import { Config } from "./Board"; import Table from "./Table"; import { getTranslate } from "../utils/getTransform"; import { addDragToSVGElement } from "../utils/addDragToSVGElement"; import { getTablePosition, setTablePosition, getContentLayout } from "../utils/layout"; import { TypeOut, TypeIn } from "./Content"; const originOffsetX = -20; import { DocEntry } from "../../getFileDocEntries"; export interface DataProps extends DocEntry { onChangeView?: (position?: { x: number; y: number }) => void; originMembers?: DocEntry[]; } export interface SingleFileProps extends DataProps, React.SVGAttributes<SVGGElement> {} const reType = /(\w+)(\[\])*/i; export class SingleFile extends React.Component<SingleFileProps> { static contextTypes = { config: PropTypes.object }; context: { config: Config }; tables: Table[] = []; rootEl: SVGGElement; wrapperEl: SVGGElement; tablesContainer: SVGGElement; backgroundEl: SVGRectElement; headerTextEl: SVGTextElement; headerEl: SVGRectElement; hue = Math.random() * 255; backgroundRect = { left: 0, top: 0, width: 0, height: 0 }; typeInOuts: { typeIn?: TypeIn; typeOuts?: TypeOut[]; }[] = []; docEntries: DocEntry[] = []; componentDidMount() { this.originTablesRect = this.tablesContainer.getBoundingClientRect(); this.originRootTranslate = this.getSVGRootTranslate(); addDragToSVGElement(this.headerEl, this.rootEl, this.props.onChangeView); this.screenMatrix = this.tablesContainer.getCTM(); this.redrawDOM(); } componentDidUpdate() { this.redrawDOM(); } getFileTranslate = () => { const transform = this.rootEl.getAttributeNS(null, "transform"); const position = getTranslate(transform); return position; } getSVGRootTranslate = () => { if (!this.rootEl) { const contentLayout = getContentLayout(); return { x: contentLayout.position.x, y: contentLayout.position.y }; } const boardEl: SVGSVGElement = this.rootEl.parentElement as any; const boardTranslate = getTranslate(boardEl.getAttributeNS(null, "transform")) || { x: 0, y: 0 }; return boardTranslate; } getTypeInOuts = () => { const { locals } = this.props; const { headerHeight, itemHeight } = this.context.config.tableStyle; this.screenMatrix = this.tablesContainer.getCTM(); const boardTranslate = this.getSVGRootTranslate(); if (!this.docEntries) return []; this.docEntries.forEach((docEntry, index) => { const { members, type, filename, name, tableWidth } = docEntry; const table = this.tables[index]; const tableRect = table ? table.rootEl.getBoundingClientRect() : { left: 0, top: 0 } as any; const typeOuts: TypeOut[] = []; let leftX = tableRect.left - boardTranslate.x + originOffsetX; leftX = leftX / this.screenMatrix.a; let rightX = leftX + tableWidth; let y = tableRect.top / this.screenMatrix.d + headerHeight / 2 - boardTranslate.y / this.screenMatrix.d; const typeInOutFile = { typeIn: { name, leftPosition: { x: leftX, y }, rightPosition: { x: rightX, y }, type, filename }, typeOuts }; this.typeInOuts[index] = typeInOutFile; if (members) { members.forEach((member, index) => { const escapedName = reType.test(member.type) ? member.type.match(reType)[1] : member.name; let localIndex = -1; if (escapedName) { for (const index in locals) { if (locals[index].name === escapedName) { localIndex = Number(index); break; } } } const y = tableRect.top / this.screenMatrix.d + headerHeight + itemHeight * index + itemHeight / 2 - boardTranslate.y / this.screenMatrix.d; typeOuts[index] = { leftPosition: { x: leftX, y }, rightPosition: { x: rightX, y }, toFileType: { isLocal: localIndex > -1 ? (!locals[localIndex].filename) : false, escapedName, type: member.type, filename: localIndex > -1 ? locals[localIndex].filename : void 0 } }; }); } const memberSize = docEntry.members ? docEntry.members.length : 0; const setPosition = (targetIndex: number, escapedName: string, type: string) => { let localIndex = -1; if (escapedName) { for (const index in locals) { if (locals[index].name === escapedName) { localIndex = Number(index); break; } } } typeOuts[targetIndex + memberSize] = { leftPosition: { x: leftX, y }, rightPosition: { x: rightX, y }, toFileType: { isLocal: localIndex > -1 ? (!locals[localIndex].filename) : false, escapedName, type, filename: localIndex > -1 ? locals[localIndex].filename : void 0 } }; }; if (docEntry.extends) { let index = 0; let targetIndex = 0; const extendsSize = docEntry.extends.length; while (index < extendsSize) { const extendsItem: DocEntry = docEntry.extends[index] as DocEntry; const escapedName = reType.test(extendsItem.name) ? extendsItem.name.match(reType)[1] : extendsItem.name; // Get ReactComponent Extends if (escapedName === "Component") { const reComponent = /(?:React\.)?(?:Component)\<?((\w+\,?\s?)+)\>?/im; const result = reComponent.exec(docEntry.valueDeclarationText); if (result[1]) { const escapedNames = result[1].split(",").map(str => str.trim()); setPosition(targetIndex, escapedNames[0], extendsItem.type); targetIndex += 1; setPosition(targetIndex, escapedNames[1], extendsItem.type); } } else { setPosition(targetIndex, escapedName, extendsItem.type); } index += 1; targetIndex += 1; } } }); return this.typeInOuts; } getAllExportDocEntry = (exportDocEntry: DocEntry) => { const { members } = this.props; let index = -1; if (members) { for (let i = 0; i < members.length; i++) { if (members[i].name === exportDocEntry.name) { index = i; break; } } } return index > -1 ? members[index] : exportDocEntry; } findMaxLetter = (docEntry: DocEntry) => { const headerCount = docEntry.name.length + docEntry.type.length; if (docEntry.members && docEntry.members.length > 0) { const maxCount = docEntry.members.reduce((prev, current) => { const letterCount = current.name ? current.name.length : 0 + current.type ? current.type.length : 0; return letterCount > prev ? letterCount : prev; }, 0); return headerCount > maxCount ? headerCount : maxCount; } else { return headerCount; } } screenMatrix: SVGMatrix; handleChangeTableView = (isCallback = true) => { const { onChangeView } = this.props; if (onChangeView) { onChangeView(this.getFileTranslate()); } this.redrawDOM(); } originRootTranslate: { x: number; y: number }; originTablesRect: ClientRect; redrawDOM = () => { const { members, fileWidth, fileHeight } = this.props; const hadMembers = members && members.length > 0; const tablesRect = this.tablesContainer.getBoundingClientRect(); const { widthPadding, headerHeight, heightPadding, headerFontSize } = this.context.config.fileStyle; this.wrapperEl.setAttributeNS(null, "display", "none"); const x = -widthPadding; const y = -headerHeight - heightPadding; this.screenMatrix = this.tablesContainer.getCTM(); const width = hadMembers ? `${tablesRect.width / this.screenMatrix.a + widthPadding * 2}` : `${fileWidth}`; const height = hadMembers ? `${tablesRect.height / this.screenMatrix.d + heightPadding * 2 + headerHeight}` : `${fileHeight}`; this.headerEl.setAttributeNS(null, "transform", `translate(${x}, ${y})`); this.headerEl.setAttributeNS(null, "width", width); this.backgroundEl.setAttributeNS(null, "transform", `translate(${x}, ${y})`); this.backgroundEl.setAttributeNS(null, "width", width); this.backgroundEl.setAttributeNS(null, "height", height); this.headerTextEl.setAttributeNS(null, "transform", `translate(${x + 4}, ${y + (headerHeight + headerFontSize) / 2})`); const wrapperRect = this.wrapperEl.getBoundingClientRect(); const offsetX = (tablesRect.left - wrapperRect.left) / this.screenMatrix.a + x; const offsetY = (tablesRect.top - wrapperRect.top) / this.screenMatrix.d + y; this.wrapperEl.setAttributeNS(null, "display", ""); this.wrapperEl.setAttributeNS(null, "transform", `translate(${offsetX}, ${offsetY})`); } render() { let { name, filename, members, exports, resolvedModules, onChangeView, rowIndex, fileWidth, fileHeight, valueDeclarationText, memberLayouts, exportLayouts, escapedName, exportMembers, originMembers, ...attributes } = this.props; const { config } = this.context; const justShowExport = config.showType === "export"; this.typeInOuts = []; const { headerFontSize, headerHeight } = this.context.config.fileStyle; if (exports) { exports = exports .map(exportDocEntry => this.getAllExportDocEntry(exportDocEntry)) .filter(docEntry => docEntry.name !== "default"); } const docEntries = justShowExport ? exports : members; this.docEntries = docEntries; const x = 0; const y = 0; return ( <g ref={rootEl => this.rootEl = rootEl} {...attributes}> <g ref={wrapperEl => this.wrapperEl = wrapperEl} display="none"> <rect width={fileWidth} height={fileHeight} fill="#e5e5e5" stroke={config.theme.accent} // strokeWidth="1" // strokeOpacity=".75" // strokeDasharray="2 4" pointerEvents="none" ref={backgroundEl => this.backgroundEl = backgroundEl} transform={`translate(${x}, ${y})`} /> <rect cursor="move" width={fileWidth} height={headerHeight} transform={`translate(${x}, ${y})`} ref={headerEl => this.headerEl = headerEl} fill="#000" /> <text x="0" y="0" fill="#fff" fontSize={headerFontSize} pointerEvents="none" transform={`translate(${x + 4}, ${y + (headerHeight + headerFontSize) / 2})`} ref={headerTextEl => this.headerTextEl = headerTextEl} > {filename} {/* {(filename && filename.length > 60) ? `${filename.slice(0, 60)}...` : filename} */} </text> </g> <g ref={tablesContainer => this.tablesContainer = tablesContainer}> {docEntries && docEntries.map((docEntry, index) => { const position = getTablePosition(filename, docEntry.name); return ( <Table {...(justShowExport ? this.getAllExportDocEntry(docEntry) : docEntry)} onChangeView={(position) => { this.handleChangeTableView(); setTablePosition(filename, docEntry.name, position); }} ref={table => this.tables[index] = table} key={index} transform={`translate(${position.x}, ${position.y})`} /> ); })} </g> </g> ); } } export default SingleFile;
the_stack
export var hwcrypto = (function hwcrypto() { "use strict"; var _debug = function(x) { // console.log(x); }; _debug("hwcrypto.js activated"); // Fix up IE8 window.addEventListener = window.addEventListener || window.attachEvent; // Returns "true" if a plugin is present for the MIME function hasPluginFor(mime) { return navigator.mimeTypes && mime in navigator.mimeTypes; } // Checks if a function is present (used for Chrome) function hasExtensionFor(cls) { return typeof window[cls] === "function"; } function _hex2array(str) { if (typeof str == "string") { var len = Math.floor(str.length / 2); var ret = new Uint8Array(len); for (var i = 0; i < len; i++) { ret[i] = parseInt(str.substr(i * 2, 2), 16); } return ret; } } function _array2hex(args) { var ret = ""; for (var i = 0; i < args.length; i++) ret += (args[i] < 16 ? "0" : "") + args[i].toString(16); return ret.toLowerCase(); } function _mimeid(mime) { return "hwc" + mime.replace("/", "").replace("-", ""); } function loadPluginFor(mime) { var element = _mimeid(mime); if (document.getElementById(element)) { _debug("Plugin element already loaded"); return document.getElementById(element); } _debug("Loading plugin for " + mime + " into " + element); // Must insert tag as string (not as an Element object) so that IE9 can access plugin methods var objectTag = '<object id="' + element + '" type="' + mime + '" style="width: 1px; height: 1px; position: absolute; visibility: hidden;"></object>'; var div = document.createElement("div"); div.setAttribute("id", "pluginLocation" + element); document.body.appendChild(div); // Must not manipulate body's innerHTML directly, otherwise previous Element references get lost document.getElementById("pluginLocation" + element).innerHTML = objectTag; return document.getElementById(element); } // Important constants var digidoc_mime = "application/x-digidoc"; var digidoc_chrome = "TokenSigning"; // Some error strings var USER_CANCEL = "user_cancel"; var NO_CERTIFICATES = "no_certificates"; var INVALID_ARGUMENT = "invalid_argument"; var DRIVER_ERROR = "driver_error"; var TECHNICAL_ERROR = "technical_error"; var NO_IMPLEMENTATION = "no_implementation"; var NOT_ALLOWED = "not_allowed"; // Probe all existing backends in a failsafe manner. function probe() { var msg = "probe() detected "; // First try Chrome extensions if (hasExtensionFor(digidoc_chrome)) { _debug(msg + digidoc_chrome); } if (hasPluginFor(digidoc_mime)) { _debug(msg + digidoc_mime); } } // TODO: remove window.addEventListener("load", function(event) { // There's a timeout because chrome content script needs to be loaded probe(); }); // Backend for DigiDoc plugin function DigiDocPlugin() { this._name = "NPAPI/BHO for application/x-digidoc"; var p = loadPluginFor(digidoc_mime); // keeps track of detected certificates and their ID-s var certificate_ids = {}; function code2str(err) { _debug("Error: " + err + " with: " + p.errorMessage); switch (parseInt(err)) { case 1: return USER_CANCEL; case 2: return NO_CERTIFICATES; case 15: return DRIVER_ERROR; case 17: // invalid hash length return INVALID_ARGUMENT; case 19: return NOT_ALLOWED; default: _debug("Unknown error: " + err + " with: " + p.errorMessage); return TECHNICAL_ERROR; } } function code2err(err) { return new Error(code2str(err)); } this.check = function() { return new Promise(function(resolve, reject) { // IE8 cannot access the newly inserted plugin object before the end of call queue setTimeout(function() { resolve(typeof p.version !== "undefined"); }, 0); }); }; this.getVersion = function() { return new Promise(function(resolve, reject) { var v = p.version; resolve(v); }); }; this.getCertificate = function(options) { // Ignore everything except language if (options && options.lang) { p.pluginLanguage = options.lang; } return new Promise(function(resolve, reject) { try { var ver = p.version.split("."); var v = ver[0] >= 3 && ver[1] >= 13 ? p.getCertificate(options.filter) : p.getCertificate(); if (parseInt(p.errorCode) !== 0) { reject(code2err(p.errorCode)); } else { // Store plugin-internal ID certificate_ids[v.cert] = v.id; resolve({ hex: v.cert }); } } catch (ex) { _debug(ex); reject(code2err(p.errorCode)); } }); }; this.sign = function(cert, hash, options) { return new Promise(function(resolve, reject) { // get the ID of the certificate var cid = certificate_ids[cert.hex]; if (cid) { try { //var v = p.sign(cid, hash, 'en'); // FIXME: only BHO requires language but does not use it var language = options.lang || "en"; //p.pluginLanguage = language; var info = options.info || ""; var ver = p.version.split("."); var v = ver[0] >= 3 && ver[1] >= 13 ? p.sign(cid, hash.hex, language, info) : p.sign(cid, hash.hex, language); resolve({ hex: v }); } catch (ex) { _debug(JSON.stringify(ex)); reject(code2err(p.errorCode)); } } else { _debug("invalid certificate: " + cert); reject(new Error(INVALID_ARGUMENT)); } }); }; } // Backend for Digidoc Chrome Extension function DigiDocExtension() { this._name = "Chrome native messaging extension"; var p = null; this.check = function() { return new Promise(function(resolve, reject) { if (!hasExtensionFor(digidoc_chrome)) { return resolve(false); } // FIXME: remove this from content script! p = new window[digidoc_chrome](); if (p) { resolve(true); } else { resolve(false); } }); }; this.getVersion = function() { return p.getVersion(); }; this.getCertificate = function(options) { return p.getCertificate(options); }; this.sign = function(cert, hash, options) { return p.sign(cert, hash, options); }; } // Dummy function NoBackend() { this._name = "No implementation"; this.check = function() { return new Promise(function(resolve, reject) { resolve(true); }); }; this.getVersion = function() { return Promise.reject(new Error(NO_IMPLEMENTATION)); }; this.getCertificate = function() { return Promise.reject(new Error(NO_IMPLEMENTATION)); }; this.sign = function() { return Promise.reject(new Error(NO_IMPLEMENTATION)); }; } // Active backend var _backend = null; // To be exposed var fields = {}; function _testAndUse(Backend) { return new Promise(function(resolve, reject) { var b = new Backend(); b.check().then(function(isLoaded) { if (isLoaded) { _debug("Using backend: " + b._name); _backend = b; resolve(true); } else { _debug(b._name + " check() failed"); resolve(false); } }); }); } function _autodetect(force) { return new Promise(function(resolve, reject) { _debug("Autodetecting best backend"); if (typeof force === "undefined") { force = false; } if (_backend !== null && !force) { return resolve(true); } function tryDigiDocPlugin() { _testAndUse(DigiDocPlugin).then(function(result) { if (result) { resolve(true); } else { resolve(_testAndUse(NoBackend)); } }); } // IE BHO if ( navigator.userAgent.indexOf("MSIE") != -1 || navigator.userAgent.indexOf("Trident") != -1 ) { _debug("Assuming IE BHO, testing"); return tryDigiDocPlugin(); } // Chrome/Firefox/Edge extension or NPAPI if ( /*navigator.userAgent.indexOf("Chrome") != -1 &&*/ hasExtensionFor( digidoc_chrome ) ) { _testAndUse(DigiDocExtension).then(function(result) { if (result) { resolve(true); } else { tryDigiDocPlugin(); } }); return; } // Other browsers with NPAPI support if (hasPluginFor(digidoc_mime)) { return tryDigiDocPlugin(); } // No backend supported resolve(_testAndUse(NoBackend)); }); } // Use a specific backend or autodetect fields.use = function(backend) { return new Promise(function(resolve, reject) { if (typeof backend === "undefined" || backend === "auto") { _autodetect().then(function(result) { resolve(result); }); } else { if (backend === "chrome") { resolve(_testAndUse(DigiDocExtension)); } else if (backend === "npapi") { resolve(_testAndUse(DigiDocPlugin)); } else { resolve(false); // unknown backend } } }); }; // Give debugging information. fields.debug = function() { return new Promise(function(resolve, reject) { var hwversion = "hwcrypto.js @@hwcryptoversion"; _autodetect().then(function(result) { _backend.getVersion().then( function(version) { resolve(hwversion + " with " + _backend._name + " " + version); }, function(error) { resolve(hwversion + " with failing backend " + _backend._name); } ); }); }); }; // Get a certificate fields.getCertificate = function(options) { if (typeof options !== "object") { _debug("getCertificate options parameter must be an object"); return Promise.reject(new Error(INVALID_ARGUMENT)); } // If options does not specify a language, set to 'en' if (options && !options.lang) { options.lang = "en"; } return _autodetect().then(function(result) { // FIXME: dummy security check in website context if ( window.location.protocol !== "https:" && window.location.protocol !== "file:" ) { return Promise.reject(new Error(NOT_ALLOWED)); } return _backend.getCertificate(options).then(function(certificate) { // Add binary value as well if (certificate.hex && !certificate.encoded) certificate.encoded = _hex2array(certificate.hex); return certificate; }); }); }; // Sign a hash fields.sign = function(cert, hash, options) { if (arguments.length < 2) return Promise.reject(new Error(INVALID_ARGUMENT)); // If options does not specify a language, set to 'en' if (options && !options.lang) { options.lang = "en"; } // Hash type and value must be present if (!hash.type || (!hash.value && !hash.hex)) return Promise.reject(new Error(INVALID_ARGUMENT)); // Convert Hash to hex and vice versa. // TODO: All backends currently expect the presence of Hex. if (hash.hex && !hash.value) { _debug( "DEPRECATED: hash.hex as argument to sign() is deprecated, use hash.value instead" ); hash.value = _hex2array(hash.hex); } if (hash.value && !hash.hex) hash.hex = _array2hex(hash.value); return _autodetect().then(function(result) { // FIXME: dummy security check in website context if ( window.location.protocol !== "https:" && window.location.protocol !== "file:" ) { return Promise.reject(new Error(NOT_ALLOWED)); } return _backend.sign(cert, hash, options).then(function(signature) { // Add binary value as well // TODO: all backends return hex currently if (signature.hex && !signature.value) signature.value = _hex2array(signature.hex); return signature; }); }); }; // Constants for errors fields.NO_IMPLEMENTATION = NO_IMPLEMENTATION; fields.USER_CANCEL = USER_CANCEL; fields.NOT_ALLOWED = NOT_ALLOWED; fields.NO_CERTIFICATES = NO_CERTIFICATES; fields.TECHNICAL_ERROR = TECHNICAL_ERROR; fields.INVALID_ARGUMENT = INVALID_ARGUMENT; return fields; })();
the_stack
require('./dimension-tile.css'); import * as React from 'react'; import { Duration } from 'chronoshift'; import { List } from 'immutable'; import { $, r, Dataset, SortAction, TimeRange, RefExpression, Expression, TimeBucketAction, NumberRange } from 'plywood'; import { formatterFromData, collect, formatGranularity, formatTimeBasedOnGranularity, formatNumberRange } from '../../../common/utils/index'; import { Fn } from '../../../common/utils/general/general'; import { Clicker, Essence, Timekeeper, VisStrategy, Dimension, SortOn, SplitCombine, Filter, FilterSelection, FilterMode, Colors, Granularity, ContinuousDimensionKind, getBestGranularityForRange, granularityEquals, granularityToString, getDefaultGranularityForKind, getGranularities } from '../../../common/models/index'; import { setDragGhost, classNames } from '../../utils/dom/dom'; import { QueryRunner } from '../../utils/query-runner/query-runner'; import { DragManager } from '../../utils/drag-manager/drag-manager'; import { STRINGS, getLocale } from '../../config/constants'; import { PIN_TITLE_HEIGHT, PIN_ITEM_HEIGHT, PIN_PADDING_BOTTOM, MAX_SEARCH_LENGTH, SEARCH_WAIT } from '../../config/constants'; import { SvgIcon } from '../svg-icon/svg-icon'; import { Checkbox } from '../checkbox/checkbox'; import { Loader } from '../loader/loader'; import { QueryError } from '../query-error/query-error'; import { HighlightString } from '../highlight-string/highlight-string'; import { SearchableTile, TileAction } from '../searchable-tile/searchable-tile'; import { TileHeaderIcon } from "../tile-header/tile-header"; const TOP_N = 100; const FOLDER_BOX_HEIGHT = 30; export interface DimensionTileProps extends React.Props<any> { clicker: Clicker; essence: Essence; timekeeper: Timekeeper; dimension: Dimension; sortOn: SortOn; colors?: Colors; onClose?: any; getUrlPrefix?: () => string; } export interface DimensionTileState { loading?: boolean; dataset?: Dataset; error?: any; fetchQueued?: boolean; unfolded?: boolean; foldable?: boolean; showSearch?: boolean; searchText?: string; selectedGranularity?: Granularity; filterMode?: FilterMode; } export class DimensionTile extends React.Component<DimensionTileProps, DimensionTileState> { public mounted: boolean; public collectTriggerSearch: Fn; constructor() { super(); this.state = { loading: false, dataset: null, error: null, fetchQueued: false, unfolded: true, foldable: false, showSearch: false, selectedGranularity: null, searchText: '' }; this.collectTriggerSearch = collect(SEARCH_WAIT, () => { if (!this.mounted) return; var { essence, timekeeper, dimension, sortOn } = this.props; var { unfolded } = this.state; this.fetchData(essence, timekeeper, dimension, sortOn, unfolded); }); } fetchData(essence: Essence, timekeeper: Timekeeper, dimension: Dimension, sortOn: SortOn, unfolded: boolean, selectedGranularity?: Granularity): void { var { searchText } = this.state; var { dataCube, colors } = essence; var filter = essence.getEffectiveFilter(timekeeper); // don't remove filter if time if (unfolded && dataCube.isMandatoryFilter(dimension.expression)) { filter = filter.remove(dimension.expression); } filter = filter.setExclusionforDimension(false, dimension); var filterExpression = filter.toExpression(); if (!unfolded && colors && colors.dimension === dimension.name && colors.values) { filterExpression = filterExpression.and(dimension.expression.in(colors.toSet())); } if (searchText) { filterExpression = filterExpression.and(dimension.expression.contains(r(searchText), 'ignoreCase')); } var query: any = $('main') .filter(filterExpression); var sortExpression: Expression = null; if (dimension.canBucketByDefault()) { const dimensionExpression = dimension.expression as RefExpression; const attributeName = dimensionExpression.name; const filterSelection: FilterSelection = essence.filter.getSelection(dimensionExpression); if (!selectedGranularity) { if (filterSelection) { var range = dimension.kind === 'time' ? essence.evaluateSelection(filterSelection as Expression, timekeeper) : (filterSelection as Expression).getLiteralValue().extent(); selectedGranularity = getBestGranularityForRange(range, true, dimension.bucketedBy, dimension.granularities); } else { selectedGranularity = getDefaultGranularityForKind(dimension.kind as ContinuousDimensionKind, dimension.bucketedBy, dimension.granularities); } } this.setState({ selectedGranularity }); query = query.split($(attributeName).performAction(selectedGranularity), dimension.name); sortExpression = $(dimension.name); } else { query = query.split(dimension.expression, dimension.name); sortExpression = sortOn.getExpression(); } if (sortOn.measure) { query = query.performAction(sortOn.measure.toApplyAction()); } query = query.sort(sortExpression, SortAction.DESCENDING).limit(TOP_N + 1); this.setState({ loading: true, fetchQueued: false }); QueryRunner.fetch(dataCube, query, essence.timezone) .then( (dataset: Dataset) => { if (!this.mounted) return; this.setState({ loading: false, dataset, error: null }); }, (error) => { if (!this.mounted) return; this.setState({ loading: false, dataset: null, error }); } ); } updateFoldability(essence: Essence, dimension: Dimension, colors: Colors): boolean { var { unfolded } = this.state; var foldable = true; if (essence.filter.filteredOn(dimension.expression)) { // has filter if (colors) { foldable = false; unfolded = false; } else if (dimension.kind === "time") { foldable = false; unfolded = true; } } else { if (!colors) { foldable = false; unfolded = true; } } this.setState({ foldable, unfolded }); return unfolded; } componentWillMount() { var { essence, timekeeper, dimension, colors, sortOn } = this.props; var unfolded = this.updateFoldability(essence, dimension, colors); this.fetchData(essence, timekeeper, dimension, sortOn, unfolded); } componentWillReceiveProps(nextProps: DimensionTileProps) { var { essence, timekeeper, dimension, sortOn } = this.props; var { selectedGranularity } = this.state; var nextEssence = nextProps.essence; var nextTimekeeper = nextProps.timekeeper; var nextDimension = nextProps.dimension; var nextColors = nextProps.colors; var nextSortOn = nextProps.sortOn; var unfolded = this.updateFoldability(nextEssence, nextDimension, nextColors); // keep granularity selection if measures change or if autoupdate var currentSelection = essence.getPrimaryTimeSelection(); var nextSelection = nextEssence.getPrimaryTimeSelection(); var differentTimeFilterSelection = currentSelection ? !currentSelection.equals(nextSelection) : Boolean(nextSelection); if (differentTimeFilterSelection) { // otherwise render will try to format exiting dataset based off of new granularity (before fetchData returns) this.setState({ dataset: null }); } var persistedGranularity = differentTimeFilterSelection ? null : selectedGranularity; if ( essence.differentDataCube(nextEssence) || essence.differentEffectiveFilter(nextEssence, timekeeper, nextTimekeeper, null, unfolded ? dimension : null) || essence.differentColors(nextEssence) || !dimension.equals(nextDimension) || !sortOn.equals(nextSortOn) || essence.differentTimezoneMatters(nextEssence) || (!essence.timezone.equals(nextEssence.timezone)) && dimension.kind === 'time' || differentTimeFilterSelection ) { this.fetchData(nextEssence, nextTimekeeper, nextDimension, nextSortOn, unfolded, persistedGranularity); } this.setFilterModeFromProps(nextProps); } setFilterModeFromProps(props: DimensionTileProps) { if (props.colors) { this.setState({filterMode: Filter.INCLUDED}); } else { var filterMode = props.essence.filter.getModeForDimension(props.dimension); if (filterMode) this.setState({filterMode}); } } componentDidMount() { this.mounted = true; this.setFilterModeFromProps(this.props); } componentWillUnmount() { this.mounted = false; } onRowClick(value: any, e: MouseEvent) { var { clicker, essence, dimension, colors } = this.props; var { dataset, filterMode } = this.state; var { filter } = essence; if (colors && colors.dimension === dimension.name) { if (colors.limit) { if (!dataset) return; var values = dataset.data.slice(0, colors.limit).map((d) => d[dimension.name]); colors = Colors.fromValues(colors.dimension, values); } colors = colors.toggle(value); if (filter.filteredOn(dimension.expression)) { filter = filter.toggleValue(dimension.expression, value); clicker.changeFilter(filter, colors); } else { clicker.changeColors(colors); } } else { if (e.altKey || e.ctrlKey || e.metaKey) { let filteredOnMe = filter.filteredOnValue(dimension.expression, value); let singleFilter = filter.getLiteralSet(dimension.expression).size() === 1; if (filteredOnMe && singleFilter) { filter = filter.remove(dimension.expression); } else { filter = filter.remove(dimension.expression).addValue(dimension.expression, value); } } else { filter = filter.toggleValue(dimension.expression, value); } // If no longer filtered switch unfolded to true for later var { unfolded } = this.state; if (!unfolded && !filter.filteredOn(dimension.expression)) { this.setState({ unfolded: true }); } clicker.changeFilter(filter.setExclusionforDimension(filterMode === Filter.EXCLUDED, dimension)); } } changeFilterMode(value: FilterMode) { const { clicker, essence, dimension } = this.props; this.setState({filterMode: value}, () => { clicker.changeFilter(essence.filter.setExclusionforDimension(value === Filter.EXCLUDED, dimension)); }); } getFilterActions(): TileAction[] { const { essence, dimension } = this.props; const { filterMode } = this.state; if (!essence || !dimension) return null; const filter: Filter = essence.filter; const options: FilterMode[] = [Filter.INCLUDED, Filter.EXCLUDED]; return options.map((value) => { return { selected: filterMode === value, onSelect: this.changeFilterMode.bind(this, value), displayValue: (STRINGS as any)[value], keyString: value }; }); } toggleFold() { var { essence, timekeeper, dimension, sortOn } = this.props; var { unfolded } = this.state; unfolded = !unfolded; this.setState({ unfolded }); this.fetchData(essence, timekeeper, dimension, sortOn, unfolded); } onDragStart(e: DragEvent) { var { essence, dimension, getUrlPrefix } = this.props; var newUrl = essence.changeSplit(SplitCombine.fromExpression(dimension.expression), VisStrategy.FairGame).getURL(getUrlPrefix()); var dataTransfer = e.dataTransfer; dataTransfer.effectAllowed = 'all'; dataTransfer.setData("text/url-list", newUrl); dataTransfer.setData("text/plain", newUrl); DragManager.setDragDimension(dimension, 'dimension-tile'); setDragGhost(dataTransfer, dimension.title); } toggleSearch() { var { showSearch } = this.state; this.setState({ showSearch: !showSearch }); this.onSearchChange(''); } onSearchChange(text: string) { var { searchText, dataset, fetchQueued, loading } = this.state; var newSearchText = text.substr(0, MAX_SEARCH_LENGTH); if (searchText === newSearchText) return; // nothing to do; // If the user is just typing in more and there are already < TOP_N results then there is nothing to do if (newSearchText.indexOf(searchText) !== -1 && !fetchQueued && !loading && dataset && dataset.data.length < TOP_N) { this.setState({ searchText: newSearchText }); return; } this.setState({ searchText: newSearchText, fetchQueued: true }); this.collectTriggerSearch(); } getTitleHeader(): string { const { dimension } = this.props; const { selectedGranularity } = this.state; if (selectedGranularity && dimension.kind === 'time') { var duration = (selectedGranularity as TimeBucketAction).duration; return `${dimension.title} (${duration.getDescription()})`; } return dimension.title; } onSelectGranularity(selectedGranularity: Granularity) { if (selectedGranularity === this.state.selectedGranularity) return; var { essence, timekeeper, dimension, colors, sortOn } = this.props; var unfolded = this.updateFoldability(essence, dimension, colors); this.setState({ dataset: null }); this.fetchData(essence, timekeeper, dimension, sortOn, unfolded, selectedGranularity); } getGranularityActions(): TileAction[] { const { dimension } = this.props; const { selectedGranularity } = this.state; var granularities = dimension.granularities || getGranularities(dimension.kind as ContinuousDimensionKind, dimension.bucketedBy, true); return granularities.map((g) => { var granularityStr = granularityToString(g); return { selected: granularityEquals(selectedGranularity, g), onSelect: this.onSelectGranularity.bind(this, g), displayValue: formatGranularity(granularityStr), keyString: granularityStr }; }); } render() { const { clicker, essence, dimension, sortOn, colors, onClose } = this.props; const { loading, dataset, error, showSearch, unfolded, foldable, fetchQueued, searchText, selectedGranularity, filterMode } = this.state; const measure = sortOn.measure; const measureName = measure ? measure.name : null; const filterSet = essence.filter.getLiteralSet(dimension.expression); const continuous = dimension.isContinuous(); const excluded = filterMode === Filter.EXCLUDED; var maxHeight = PIN_TITLE_HEIGHT; var rows: Array<JSX.Element> = []; var folder: JSX.Element = null; var highlightControls: JSX.Element = null; var hasMore = false; if (dataset) { hasMore = dataset.data.length > TOP_N; var rowData = dataset.data.slice(0, TOP_N); if (!unfolded) { if (filterSet) { rowData = rowData.filter((d) => filterSet.contains(d[dimension.name])); } if (colors) { if (colors.values) { var colorsSet = colors.toSet(); rowData = rowData.filter((d) => colorsSet.contains(d[dimension.name])); } else { rowData = rowData.slice(0, colors.limit); } } } if (searchText) { var searchTextLower = searchText.toLowerCase(); rowData = rowData.filter((d) => { return String(d[dimension.name]).toLowerCase().indexOf(searchTextLower) !== -1; }); } var colorValues: string[] = null; if (colors) colorValues = colors.getColors(rowData.map(d => d[dimension.name])); var formatter = measure ? formatterFromData(rowData.map(d => d[measureName] as number), measure.getFormat()) : null; rows = rowData.map((d, i) => { var segmentValue = d[dimension.name]; var segmentValueStr = String(segmentValue); var className = 'row'; var checkbox: JSX.Element = null; if ((filterSet || colors) && !continuous) { var selected: boolean; if (colors) { selected = false; className += ' color'; } else { selected = essence.filter.filteredOnValue(dimension.expression, segmentValue); className += ' ' + (selected ? 'selected' : 'not-selected'); } checkbox = <Checkbox selected={selected} type={excluded ? 'cross' : 'check'} color={colorValues ? colorValues[i] : null} />; } if (segmentValue instanceof TimeRange) { segmentValueStr = formatTimeBasedOnGranularity(segmentValue, (selectedGranularity as TimeBucketAction).duration, essence.timezone, getLocale()); } else if (segmentValue instanceof NumberRange) { segmentValueStr = formatNumberRange(segmentValue); } var measureValueElement: JSX.Element = null; if (measure) { measureValueElement = <div className="measure-value">{formatter(d[measureName] as number)}</div>; } var row = <div className={className} key={segmentValueStr} onClick={this.onRowClick.bind(this, segmentValue)} > <div className="segment-value" title={segmentValueStr}> {checkbox} <HighlightString className="label" text={segmentValueStr} highlight={searchText}/> </div> {measureValueElement} {selected ? highlightControls : null} </div>; if (selected && highlightControls) highlightControls = null; // place only once return row; }); maxHeight += Math.max(2, rows.length) * PIN_ITEM_HEIGHT; if (foldable) { folder = <div className={classNames('folder', unfolded ? 'folded' : 'unfolded')} onClick={this.toggleFold.bind(this)} > <SvgIcon svg={require('../../icons/caret.svg')}/> {unfolded ? 'Show selection' : 'Show all'} </div>; maxHeight += FOLDER_BOX_HEIGHT; } } maxHeight += PIN_PADDING_BOTTOM; var message: JSX.Element = null; if (!loading && dataset && !fetchQueued && searchText && !rows.length) { message = <div className="message">{`No results for "${searchText}"`}</div>; } const className = classNames( 'dimension-tile', filterMode, (folder ? 'has-folder' : 'no-folder'), (colors ? 'has-colors' : 'no-colors'), {continuous} ); const style = { maxHeight }; var icons: TileHeaderIcon[] = [{ name: 'search', ref: 'search', onClick: this.toggleSearch.bind(this), svg: require('../../icons/full-search.svg'), active: showSearch }]; if (onClose !== null) { icons.push({ name: 'close', ref: 'close', onClick: onClose, svg: require('../../icons/full-remove.svg') }); } var actions: TileAction[] = null; if (dimension.canBucketByDefault()) { actions = this.getGranularityActions(); } else if (!continuous && !essence.colors) { actions = this.getFilterActions(); } return <SearchableTile style={style} title={this.getTitleHeader()} toggleChangeFn={this.toggleSearch.bind(this)} onDragStart={this.onDragStart.bind(this)} onSearchChange={this.onSearchChange.bind(this)} searchText={searchText} showSearch={showSearch} icons={icons} className={className} actions={actions} > <div className="rows"> {rows} {message} </div> { folder } {error ? <QueryError error={error}/> : null} {loading ? <Loader/> : null} </SearchableTile>; } }
the_stack
import { MuSchema } from './schema'; import { MuWriteStream, MuReadStream } from '../stream'; const muPrimitiveSize = { boolean: 0, uint8: 1, uint16: 2, uint32: 4, int8: 1, int16: 2, int32: 4, float32: 4, float64: 8, varint: 5, rvarint: 5, 'quantized-float': 5, }; const muType2ReadMethod = { boolean: 'readUint8', float32: 'readFloat32', float64: 'readFloat64', int8: 'readInt8', int16: 'readInt16', int32: 'readInt32', uint8: 'readUint8', uint16: 'readUint16', uint32: 'readUint32', utf8: 'readString', varint: 'readVarint', }; const muType2WriteMethod = { boolean: 'writeUint8', float32: 'writeFloat32', float64: 'writeFloat64', int8: 'writeInt8', int16: 'writeInt16', int32: 'writeInt32', uint8: 'writeUint8', uint16: 'writeUint16', uint32: 'writeUint32', utf8: 'writeString', varint: 'writeVarint', }; const muPrimitiveTypes = Object.keys(muPrimitiveSize); export type Struct<Spec extends { [prop:string]:MuSchema<any> }> = { [K in keyof Spec]:Spec[K]['identity']; }; export class MuStruct<Spec extends { [prop:string]:MuSchema<any> }> implements MuSchema<Struct<Spec>> { public readonly muType = 'struct'; public readonly muData:Spec; public readonly identity:Struct<Spec>; public readonly json:object; public pool:Struct<Spec>[]; public readonly alloc:() => Struct<Spec>; public readonly free:(struct:Struct<Spec>) => void; public readonly equal:(a:Struct<Spec>, b:Struct<Spec>) => boolean; public readonly clone:(struct:Struct<Spec>) => Struct<Spec>; public readonly assign:(dst:Struct<Spec>, src:Struct<Spec>) => Struct<Spec>; public readonly diff:(base:Struct<Spec>, target:Struct<Spec>, out:MuWriteStream) => boolean; public readonly patch:(base:Struct<Spec>, inp:MuReadStream) => Struct<Spec>; public readonly toJSON:(struct:Struct<Spec>) => Struct<any>; public readonly fromJSON:(json:Struct<any>) => Struct<Spec>; public readonly stats:() => { allocCount:number; freeCount:number; poolSize:number; }; constructor (spec:Spec) { // sort struct properties so primitives come first const props:string[] = Object.keys(spec).sort( (a:string, b:string) => { const ai = muPrimitiveTypes.indexOf(spec[a].muType); const bi = muPrimitiveTypes.indexOf(spec[b].muType); return (bi - ai) || (a < b ? -1 : (b < a) ? 1 : 0); }); const types:MuSchema<any>[] = props.map((prop) => spec[prop]); const json = { type: 'struct', subTypes: {}, }; props.forEach((prop) => { json.subTypes[prop] = spec[prop].json; }); const params:string[] = []; const args:any[] = []; let tokenCounter = 0; function token () : string { return '_v' + (++tokenCounter); } function inject (arg) : string { for (let i = 0; i < args.length; ++i) { if (args[i] === arg) { return params[i]; } } const param = token(); params.push(param); args.push(arg); return param; } const propRefs:string[] = props.map(inject); const typeRefs:string[] = types.map(inject); function block () { const vars:string[] = []; const body:string[] = []; return { vars, body, toString () { const localVars = (vars.length > 0) ? `var ${vars.join()};` : ''; return localVars + body.join(''); }, def (value) { //vars.push('_vN'), body.push('_vN=value') const tok = token(); vars.push(tok); if (value != undefined) { body.push(`${tok}=${value};`); } return tok; }, append (...code:string[]) { body.push.apply(body, code); }, }; } const prolog = block(); const epilog = block(); function func (name:string, params_:string[]) { const b = block(); const baseToString = b.toString; b.toString = function () { return `function ${name}(${params_.join()}){${baseToString()}}`; }; return b; } const methods = { alloc: func('alloc', []), free: func('free', ['s']), equal: func('equal', ['a', 'b']), clone: func('clone', ['s']), assign: func('assign', ['d', 's']), diff: func('diff', ['b', 't', 's']), patch: func('patch', ['b', 's']), toJSON: func('toJSON', ['s']), fromJSON: func('fromJSON', ['j']), stats: func('stats', []), }; const allocCountRef = prolog.def('-1'); const freeCountRef = prolog.def('0'); const poolRef = prolog.def('[]'); prolog.append('function MuStruct(){'); propRefs.forEach((pr, i) => { const type = types[i]; switch (type.muType) { case 'boolean': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'rvarint': prolog.append(`this[${pr}]=${type.identity};`); break; case 'float32': case 'float64': case 'quantized-float': // ensure prop is initialized to float to mitigate perf issue caused by V8 migration prolog.append(`this[${pr}]=0.5;this[${pr}]=${type.identity};`); break; case 'ascii': case 'fixed-ascii': case 'utf8': prolog.append(`this[${pr}]=${inject(type.identity)};`); break; default: prolog.append(`this[${pr}]=null;`); } }); prolog.append(`}function _alloc(){++${allocCountRef};if(${poolRef}.length>0){return ${poolRef}.pop()}return new MuStruct()}`); const identityRef = prolog.def('_alloc()'); propRefs.forEach((pr, i) => { const type = types[i]; switch (type.muType) { case 'ascii': case 'fixed-ascii': case 'utf8': case 'boolean': case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'rvarint': case 'quantized-float': break; default: prolog.append(`${identityRef}[${pr}]=${typeRefs[i]}.clone(${inject(type.identity)});`); break; } }); // alloc methods.alloc.append(`var s=_alloc();`); propRefs.forEach((pr, i) => { const type = types[i]; switch (type.muType) { case 'ascii': case 'fixed-ascii': case 'utf8': case 'boolean': case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'rvarint': case 'quantized-float': break; default: methods.alloc.append(`s[${pr}]=${typeRefs[i]}.alloc();`); break; } }); methods.alloc.append(`return s;`); // free methods.free.append(`${poolRef}.push(s);`); propRefs.forEach((pr, i) => { const type = types[i]; switch (type.muType) { case 'ascii': case 'fixed-ascii': case 'utf8': case 'boolean': case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'rvarint': case 'quantized-float': break; default: methods.free.append(`${typeRefs[i]}.free(s[${pr}]);`); break; } }); methods.free.append(`++${freeCountRef};`); // equal propRefs.forEach((pr, i) => { const type = types[i]; switch (type.muType) { case 'ascii': case 'fixed-ascii': case 'utf8': case 'boolean': case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'rvarint': methods.equal.append(`if(a[${pr}]!==b[${pr}]){return false}`); break; case 'quantized-float': methods.equal.append(`if(((${(<any>type).invPrecision}*a[${pr}])>>0)!==((${(<any>type).invPrecision}*b[${pr}])>>0)){return false}`); break; default: methods.equal.append(`if(!${typeRefs[i]}.equal(a[${pr}],b[${pr}])){return false}`); } }); methods.equal.append(`return true;`); // clone methods.clone.append(`var c=_alloc();`); propRefs.forEach((pr, i) => { const type = types[i]; switch (type.muType) { case 'ascii': case 'fixed-ascii': case 'utf8': case 'boolean': case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'rvarint': methods.clone.append(`c[${pr}]=s[${pr}];`); break; case 'quantized-float': methods.clone.append(`c[${pr}]=((${(<any>type).invPrecision}*s[${pr}])>>0)*${(<any>type).precision};`); break; default: methods.clone.append(`c[${pr}]=${typeRefs[i]}.clone(s[${pr}]);`); break; } }); methods.clone.append('return c;'); // assign propRefs.forEach((pr, i) => { const type = types[i]; switch (type.muType) { case 'ascii': case 'fixed-ascii': case 'utf8': case 'boolean': case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'rvarint': methods.assign.append(`d[${pr}]=s[${pr}];`); break; case 'quantized-float': methods.assign.append(`d[${pr}]=((${(<any>type).invPrecision}*s[${pr}])>>0)*${(<any>type).precision};`); break; default: methods.assign.append(`d[${pr}]=${typeRefs[i]}.assign(d[${pr}],s[${pr}]);`); } }); methods.assign.append('return d;'); // common constants const numProps = props.length; const trackerBytes = Math.ceil(numProps / 8); // diff let baseSize = trackerBytes; for (let i = 0; i < types.length; ++i) { const muType = types[i].muType; if (muType in muPrimitiveSize) { baseSize += muPrimitiveSize[muType]; } } methods.diff.append(`var head=s.offset;var tr=0;var np=0;s.grow(${baseSize});s.offset+=${trackerBytes};`); propRefs.forEach((pr, i) => { const muType = types[i].muType; switch (muType) { case 'boolean': methods.diff.append(`if(b[${pr}]!==t[${pr}]){++np;tr|=${1 << (i & 7)}}`); break; case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'varint': case 'utf8': methods.diff.append(`if(b[${pr}]!==t[${pr}]){s.${muType2WriteMethod[muType]}(t[${pr}]);++np;tr|=${1 << (i & 7)}}`); break; case 'rvarint': methods.diff.append(`if(b[${pr}]!==t[${pr}]){s.writeVarint(0xAAAAAAAA+(t[${pr}]-b[${pr}])^0xAAAAAAAA);++np;tr|=${1 << (i & 7)}}`); break; case 'ascii': methods.diff.append(`if(b[${pr}]!==t[${pr}]){s.grow(5+t[${pr}].length);s.writeVarint(t[${pr}].length);s.writeASCII(t[${pr}]);++np;tr|=${1 << (i & 7)}}`); break; case 'quantized-float': const br = methods.diff.def(`(${(<any>types[i]).invPrecision}*b[${pr}])>>0`); const tr = methods.diff.def(`(${(<any>types[i]).invPrecision}*t[${pr}])>>0`); methods.diff.append(`if(${br}!==${tr}){s.writeVarint((0xAAAAAAAA+(${tr}-${br})^0xAAAAAAAA)>>>0);++np;tr|=${1 << (i & 7)};}`); break; default: methods.diff.append(`if(${typeRefs[i]}.diff(b[${pr}],t[${pr}],s)){++np;tr|=${1 << (i & 7)}}`); } if ((i & 7) === 7) { methods.diff.append(`s.writeUint8At(head+${i >> 3},tr);tr=0;`); } }); if (numProps & 7) { methods.diff.append(`s.writeUint8At(head+${trackerBytes - 1},tr);`); } methods.diff.append(`if(np){return true}else{s.offset=head;return false}`); // patch methods.patch.append(`var t=_alloc(b);var head=s.offset;var tr=0;s.offset+=${trackerBytes};`); propRefs.forEach((pr, i) => { if (!(i & 7)) { methods.patch.append(`tr=s.readUint8At(head+${i >> 3});`); } const type = types[i]; const muType = type.muType; methods.patch.append(`;t[${pr}]=(tr&${1 << (i & 7)})?`); switch (muType) { case 'boolean': methods.patch.append(`!b[${pr}]:b[${pr}];`); break; case 'float32': case 'float64': case 'int8': case 'int16': case 'int32': case 'uint8': case 'uint16': case 'uint32': case 'utf8': case 'varint': methods.patch.append(`s.${muType2ReadMethod[muType]}():b[${pr}];`); break; case 'rvarint': methods.patch.append(`b[${pr}]+((0xAAAAAAAA^s.readVarint())-0xAAAAAAAA>>0):b[${pr}];`); break; case 'ascii': methods.patch.append(`s.readASCII(s.readVarint()):b[${pr}];`); break; case 'quantized-float': methods.patch.append(`(((${(<any>type).invPrecision}*b[${pr}])>>0)+(((0xAAAAAAAA^s.readVarint())-0xAAAAAAAA)>>0))*${(<any>type).precision}:b[${pr}];`); break; default: methods.patch.append(`${typeRefs[i]}.patch(b[${pr}],s):${typeRefs[i]}.clone(b[${pr}]);`); } }); methods.patch.append(`return t;`); // toJSON methods.toJSON.append(`var j={};`); propRefs.forEach((pr, i) => { methods.toJSON.append(`j[${pr}]=${typeRefs[i]}.toJSON(s[${pr}]);`); }); methods.toJSON.append(`return j;`); // fromJSON methods.fromJSON.append(`var s=_alloc();`); methods.fromJSON.append(`if(Object.prototype.toString.call(j)==='[object Object]'){`); propRefs.forEach((pr, i) => { methods.fromJSON.append(`s[${pr}]=${typeRefs[i]}.fromJSON(j[${pr}]);`); }); methods.fromJSON.append(`}`); methods.fromJSON.append(`return s;`); // stats methods.stats.append(`return {allocCount:${allocCountRef},freeCount:${freeCountRef},poolSize:${poolRef}.length};`); const muDataRef = prolog.def('{}'); propRefs.forEach((pr, i) => { prolog.append(`${muDataRef}[${pr}]=${typeRefs[i]};`); }); // write result epilog.append(`return {identity:${identityRef},muData:${muDataRef},pool:${poolRef},`); Object.keys(methods).forEach((name) => { prolog.append(methods[name].toString()); epilog.append(`${name}:${name},`); }); epilog.append('}'); prolog.append(epilog.toString()); params.push(prolog.toString()); const proc = Function.apply(null, params); const compiled = proc.apply(null, args); this.json = json; this.muData = compiled.muData; this.identity = compiled.identity; this.pool = compiled.pool; this.alloc = compiled.alloc; this.free = compiled.free; this.equal = compiled.equal; this.clone = compiled.clone; this.assign = compiled.assign; this.diff = compiled.diff; this.patch = compiled.patch; this.toJSON = compiled.toJSON; this.fromJSON = compiled.fromJSON; this.stats = compiled.stats; } }
the_stack
import { remote } from "electron" import getStroke from "perfect-freehand" import { getSvgPathFromStroke } from "lib/utils" import { RefObject } from "react" import { createSelectorHook, createState } from "@state-designer/react" import { mvPointer } from "hooks/usePointer" import * as defaultValues from "lib/defaults" // TODO: Fades should begin after a certain amount of time has passed since the last mark was made. enum MarkType { Freehand = "freehand", Ruled = "ruled", Ellipse = "ellipse", Rect = "rect", Arrow = "arrow", } interface MarkBase { pointerType: string pressure: boolean type: MarkType size: number color: string eraser: boolean strength: number points: number[][] } interface Mark extends MarkBase {} interface CompleteMark extends MarkBase { path: Path2D } type Elements = { frame: HTMLDivElement currentCanvas: HTMLCanvasElement marksCanvas: HTMLCanvasElement } type Refs = { [key in keyof Elements]: RefObject<Elements[key]> } const state = createState({ data: { isFading: true, isDragging: false, fadeDelay: 1, fadeDuration: 0.5, hideCursor: false, refs: undefined as Refs | undefined, color: "52, 205, 239", size: 32, pressure: true, fading: [] as CompleteMark[], marks: [] as CompleteMark[], currentMark: undefined as Mark | undefined, redos: [] as CompleteMark[], canvasSize: { width: 0, height: 0, }, selectedTool: "pencil", }, on: { SELECTED_COLOR: "setColor", SELECTED_SIZE: "setSize", LOADED: ["setRefs", { get: "elements", do: "setupCanvases" }, "activate"], }, states: { app: { initial: "loading", states: { loading: { on: { LOADED: [ { get: "elements", do: ["clearCurrentCanvas", "clearMarksCanvas"], }, { to: "ready", }, ], }, }, ready: { initial: "inactive", on: { FOCUSED_WINDOW: [], }, states: { inactive: { onEnter: ["pushMarksToFading", "clearCurrentMark", "deactivate"], on: { ACTIVATE_SHORTCUT: { to: ["active", "notDrawing"], }, ACTIVATED: { to: "active" }, ENTERED_CONTROLS: { to: "selecting" }, }, }, selecting: { onEnter: "activate", on: { LEFT_CONTROLS: { to: "inactive" }, SELECTED: { to: "active" }, STARTED_DRAWING: { to: "inactive" }, BLURRED_WINDOW: { to: "inactive" }, }, }, active: { onEnter: ["activate", { get: "elements", do: "resizeCanvases" }], on: { DEACTIVATED: { to: "inactive" }, BLURRED_WINDOW: { to: "inactive" }, CHANGED_COLOR_KEY: { do: "setColorFromKey" }, CHANGED_SIZE_KEY: { do: "setSizeFromKey" }, UNDO: { get: "elements", if: "hasMarks", do: [ "undoMark", "drawPreviousMarks", "clearCurrentCanvas", "drawCurrentMark", ], }, REDO: { get: "elements", if: "hasRedos", do: [ "redoMark", "drawPreviousMarks", "clearCurrentCanvas", "drawCurrentMark", ], }, RESIZED: { get: "elements", secretlyDo: [ "resizeCanvases", "drawPreviousMarks", "drawCurrentMark", ], }, UNLOADED: { do: "clearRefs", to: "loading", }, }, states: { tool: { on: { HARD_CLEARED: { get: "elements", do: [ "clearPreviousMarks", "clearCurrentMark", "clearCurrentCanvas", "clearMarksCanvas", ], to: ["inactive"], }, MEDIUM_CLEARED: { get: "elements", do: [ "clearPreviousMarks", "clearCurrentMark", "clearCurrentCanvas", "clearMarksCanvas", ], to: ["selecting"], }, SOFT_CLEARED: { get: "elements", do: [ "clearPreviousMarks", "clearCurrentMark", "clearCurrentCanvas", "clearMarksCanvas", ], }, TOGGLED_PRESSURE: { do: "togglePressure" }, SELECTED_PENCIL: { to: "pencil" }, SELECTED_RECT: { to: "rect" }, SELECTED_ARROW: { to: "arrow" }, SELECTED_ELLIPSE: { to: "ellipse" }, SELECTED_ERASER: { to: "eraser" }, STARTED_DRAWING: { get: "elements", do: "restoreFades", }, }, initial: "pencil", states: { pencil: { onEnter: "setToolPencil", on: { STARTED_DRAWING: { get: "elements", do: ["beginPencilMark", "drawCurrentMark"], }, }, }, rect: { onEnter: "setToolRect", on: { STARTED_DRAWING: { get: "elements", do: ["beginRectMark", "drawCurrentMark"], }, }, }, ellipse: { onEnter: "setToolEllipse", on: { STARTED_DRAWING: { get: "elements", do: ["beginEllipseMark", "drawCurrentMark"], }, }, }, arrow: { onEnter: "setToolArrow", on: { STARTED_DRAWING: { get: "elements", do: ["beginArrowMark", "drawCurrentMark"], }, }, }, eraser: { onEnter: "setToolEraser", on: { STARTED_DRAWING: { get: "elements", do: ["beginEraserMark", "drawCurrentMark"], }, SELECTED_COLOR: { to: "pencil" }, }, }, }, }, canvas: { initial: "notDrawing", states: { notDrawing: { on: { STARTED_DRAWING: { to: "drawing", // Yes for iPad, no for Wacom. Hmm... // if: "drawingWithPen", // to: ["cursorHidden", "drawing"], // else: { to: "drawing" }, }, }, onEnter: { wait: 0.8, secretlyDo: "pushMarksToFading", }, }, drawing: { onEnter: "clearRedos", on: { STOPPED_DRAWING: { get: "elements", secretlyDo: [ "completeMark", "clearCurrentMark", "drawPreviousMarks", "clearCurrentCanvas", ], to: ["notDrawing", "hasMarks"], }, MOVED_CURSOR: { get: "elements", secretlyDo: ["addPointToMark", "drawCurrentMark"], }, }, }, }, }, }, }, }, }, }, }, cursor: { initial: "cursorVisible", states: { cursorHidden: { on: { MOVED_CURSOR: { unless: "drawingWithPen", to: ["cursorVisible"], }, }, }, cursorVisible: {}, }, }, marks: { initial: "noMarks", states: { notFading: { on: { TOGGLED_FADING: { do: "toggleFading", to: "hasMarks", }, }, }, noMarks: { onEnter: { get: "elements", if: "isLoaded", secretlyDo: ["clearMarksCanvas", "drawPreviousMarks"], }, on: { TOGGLED_FADING: { do: "toggleFading", to: "notFading" }, }, }, hasMarks: { onEnter: [ { unless: "fadingEnabled", to: "notFading", }, { unless: ["hasFadingMarks", "hasMarks"], to: "noMarks", }, ], on: { TOGGLED_FADING: { get: "elements", secretlyDo: [ "toggleFading", "clearMarksCanvas", "drawPreviousMarks", ], to: "notFading", }, }, repeat: { onRepeat: [ { unless: ["hasFadingMarks", "hasMarks"], to: "noMarks", else: [ { get: "elements", secretlyDo: ["fadeMarks", "removeFadedMarks"], }, { secretlyDo: ["clearMarksCanvas", "drawPreviousMarks"], }, ], }, ], }, }, }, }, }, times: { fadeDelay(data) { return data.fadeDelay }, }, results: { elements(data) { if (!data.refs) return {} const frame = data.refs.frame.current const currentCanvas = data.refs.currentCanvas.current const marksCanvas = data.refs.marksCanvas.current if (!frame || !currentCanvas || !marksCanvas) { throw Error("Something is missing!") } return { frame, currentCanvas, marksCanvas, } }, }, conditions: { isLoaded(data) { return !!data.refs?.currentCanvas?.current }, fadingEnabled(data) { return data.isFading }, hasCurrentMark(data) { return !!data.currentMark }, hasMarks(data) { return data.marks.length > 0 }, hasRedos(data) { return data.redos.length > 0 }, hasFadingMarks(data) { return data.fading.length > 0 }, drawingWithPen(data) { const { pointerType } = getPointer() return pointerType === "pen" }, }, actions: { // Fading toggleFading(data) { const { isFading, fading, marks } = data data.isFading = !isFading if (!data.isFading) { marks.unshift(...fading) for (let mark of marks) { mark.strength = 1 } } }, fadeMarks(data) { const { fadeDuration, fading } = data const delta = 0.016 / fadeDuration for (let mark of fading) { mark.strength -= delta } }, removeFadedMarks(data) { data.fading = data.fading.filter((mark) => mark.strength > 0) }, // Pointer Capture activate() { const mainWindow = remote.getCurrentWindow() mainWindow.maximize() mainWindow.setIgnoreMouseEvents(false, { forward: false }) document.body.style.setProperty("cursor", "none") }, deactivate() { const mainWindow = remote.getCurrentWindow() mainWindow.setIgnoreMouseEvents(true, { forward: true }) document.body.style.setProperty("cursor", "auto") }, // Setup clearRefs(data) { data.refs = undefined }, setRefs(data, payload: Refs) { data.refs = payload }, setupCanvases(data, payload, elements: Elements) { { const cvs = elements.currentCanvas const ctx = cvs.getContext("2d") ctx.globalCompositeOperation = "source-over" ctx.save() } { const cvs = elements.marksCanvas const ctx = cvs.getContext("2d") ctx.save() } }, // Tools setColorFromKey(data, payload: { index: number }) { const { index } = payload const keys = Object.values(defaultValues.colors) if (keys[index]) { data.color = keys[index] } }, setSizeFromKey(data, payload: { index: number }) { const { index } = payload const keys = Object.values(defaultValues.sizes) if (keys[index]) { data.size = keys[index] } }, togglePressure(data) { data.pressure = !data.pressure }, setColor(data, payload) { data.color = payload }, setSize(data, payload) { data.size = payload }, // Marks pushMarksToFading(data) { data.fading.push(...data.marks) data.marks = [] }, clearPreviousMarks(data, payload, elements: Elements) { data.fading = [] data.marks = [] }, clearCurrentMark(data) { data.currentMark = undefined }, // Canvases resizeCanvases(data, payload, elements: Elements) { data.canvasSize = { width: elements.frame.offsetWidth, height: elements.frame.offsetHeight, } elements.marksCanvas.width = data.canvasSize.width elements.marksCanvas.height = data.canvasSize.height elements.currentCanvas.width = data.canvasSize.width elements.currentCanvas.height = data.canvasSize.height }, clearCurrentCanvas(data, payload, elements: Elements) { const cvs = elements.currentCanvas const ctx = cvs.getContext("2d") ctx.clearRect(0, 0, cvs.width, cvs.height) }, clearMarksCanvas(data, payload, elements: Elements) { const cvs = elements.marksCanvas const ctx = cvs.getContext("2d") ctx.clearRect(0, 0, cvs.width, cvs.height) }, hideOrShowCursor(data, payload) { const { pointerType } = getPointer() data.hideCursor = pointerType === "pen" }, restoreFades(data) {}, beginPencilMark(data) { const { x, y, pressure, pointerType } = getPointer() data.currentMark = { pointerType, pressure: data.pressure, type: MarkType.Freehand, size: data.size, color: `rgba(${data.color}, 1)`, strength: 1, eraser: false, points: [[x, y, pressure]], } }, beginEraserMark(data) { const { x, y, pressure, pointerType } = getPointer() data.currentMark = { pointerType, pressure: data.pressure, type: MarkType.Freehand, size: data.size, color: `rgba(${data.color}, 1)`, eraser: true, strength: 1, points: [[x, y, pressure]], } }, beginRectMark(data) { const { x, y, pressure, pointerType } = getPointer() data.currentMark = { pointerType, pressure: data.pressure, type: MarkType.Rect, size: data.size, color: `rgba(${data.color}, 1)`, eraser: false, strength: 1, points: [[x, y, pressure]], } }, beginEllipseMark(data) { const { x, y, pressure, pointerType } = getPointer() data.currentMark = { pointerType, pressure: data.pressure, type: MarkType.Ellipse, size: data.size, color: `rgba(${data.color}, 1)`, eraser: false, strength: 1, points: [[x, y, pressure]], } }, beginArrowMark(data) { const { x, y, pressure, pointerType } = getPointer() data.currentMark = { pointerType, pressure: data.pressure, type: MarkType.Arrow, size: data.size, color: `rgba(${data.color}, 1)`, eraser: false, strength: 1, points: [[x, y, pressure]], } }, addPointToMark(data) { const { points, type } = data.currentMark const { x, y, pressure, pointerType } = getPointer() if (pointerType !== data.currentMark.pointerType) { return } switch (type) { case MarkType.Freehand: { points.push([x, y, pressure]) break } case MarkType.Arrow: case MarkType.Ellipse: case MarkType.Rect: { points[1] = [x, y, pressure] break } } }, completeMark(data) { const { type } = data.currentMark let path: Path2D switch (type) { case MarkType.Freehand: { path = getFreehandPath(data.currentMark, data.pressure) break } case MarkType.Ellipse: { path = getEllipsePath(data.currentMark) break } case MarkType.Rect: { path = getRectPath(data.currentMark) break } case MarkType.Arrow: { path = getArrowPath(data.currentMark) break } } data.marks.push({ ...data.currentMark, path, }) }, drawPreviousMarks(data, payload, elements: Elements) { // First clear the top canvas... const cvs = elements.marksCanvas const ctx = cvs.getContext("2d") if (ctx) { ctx.clearRect(0, 0, cvs.width, cvs.height) ctx.globalCompositeOperation = "source-over" ctx.lineCap = "round" ctx.lineJoin = "round" for (let mark of [...data.marks, ...data.fading]) { ctx.fillStyle = mark.color ctx.strokeStyle = mark.color ctx.lineWidth = mark.size ctx.globalCompositeOperation = mark.eraser ? "destination-out" : "source-over" ctx.globalAlpha = easeOutQuad(Math.min(1, mark.strength)) if (mark.type === MarkType.Freehand) { ctx.fill(mark.path) } else { ctx.stroke(mark.path) } } } }, drawCurrentMark(data, payload, elements: Elements) { const mark = data.currentMark const cvs = elements.currentCanvas const ctx = cvs.getContext("2d") if (ctx) { ctx.clearRect(0, 0, cvs.width, cvs.height) if (mark === undefined) return if (mark.points.length === 0) return const { type } = mark let path: Path2D switch (type) { case MarkType.Freehand: { path = getFreehandPath(data.currentMark, data.pressure) break } case MarkType.Ellipse: { path = getEllipsePath(data.currentMark) break } case MarkType.Rect: { path = getRectPath(data.currentMark) break } case MarkType.Arrow: { path = getArrowPath(data.currentMark) break } } ctx.lineCap = "round" ctx.lineJoin = "round" ctx.lineWidth = mark.size ctx.fillStyle = mark.color ctx.strokeStyle = mark.color ctx.globalCompositeOperation = "source-over" if (mark.eraser) { ctx.globalCompositeOperation = "destination-out" ctx.strokeStyle = "rgba(144, 144, 144, 1)" } if (mark.type === MarkType.Freehand) { ctx.fill(path) } else { ctx.stroke(path) } } }, // Undos and redos undoMark(data) { if (data.marks.length > 0) { data.redos.push(data.marks.pop()) } else if (data.fading.length > 0) { data.redos.push(data.fading.pop()) } }, redoMark(data) { data.marks.push(data.redos.pop()) }, clearRedos(data) { data.redos = [] }, // Tools (yawn) setToolPencil(data) { data.selectedTool = "pencil" }, setToolEraser(data) { data.selectedTool = "eraser" }, setToolRect(data) { data.selectedTool = "rect" }, setToolEllipse(data) { data.selectedTool = "ellipse" }, setToolArrow(data) { data.selectedTool = "arrow" }, }, }) // Draw a mark onto the given canvas function getFreehandPath(mark: Mark, isPressure: boolean) { const { points } = mark const path = new Path2D( getSvgPathFromStroke( getStroke(points, { size: mark.size * 2, thinning: isPressure ? 0.618 : 0, simulatePressure: mark.pointerType !== "pen", }) ) ) return path } function getRectPath(mark: Mark) { const { points } = mark const path = new Path2D() if (points.length < 2) return path const x0 = Math.min(points[0][0], points[1][0]) const y0 = Math.min(points[0][1], points[1][1]) const x1 = Math.max(points[0][0], points[1][0]) const y1 = Math.max(points[0][1], points[1][1]) path.rect(x0, y0, x1 - x0, y1 - y0) return path } function getEllipsePath(mark: Mark) { const { points } = mark const path = new Path2D() if (points.length < 2) return path const x0 = Math.min(points[0][0], points[1][0]) const y0 = Math.min(points[0][1], points[1][1]) const x1 = Math.max(points[0][0], points[1][0]) const y1 = Math.max(points[0][1], points[1][1]) const w = x1 - x0 const h = y1 - y0 const cx = x0 + w / 2 const cy = y0 + h / 2 path.ellipse(cx, cy, w / 2, h / 2, 0, 0, Math.PI * 2) return path } function getArrowPath(mark: Mark) { const { points } = mark const path = new Path2D() if (points.length < 2) return path const [[x0, y0], [x1, y1]] = points const angle = Math.atan2(y1 - y0, x1 - x0) const distance = Math.hypot(y1 - y0, x1 - x0) const leg = (Math.min(distance / 2, 48) * mark.size) / 16 const [x2, y2] = projectPoint(x1, y1, angle + Math.PI * 1.2, leg) const [x3, y3] = projectPoint(x1, y1, angle - Math.PI * 1.2, leg) path.moveTo(x0, y0) path.lineTo(x1, y1) path.lineTo(x2, y2) path.moveTo(x1, y1) path.lineTo(x3, y3) return path } const easeOutQuad = (t: number) => t * (2 - t) export function getPointer() { return { x: mvPointer.x.get(), y: mvPointer.y.get(), dx: mvPointer.dx.get(), dy: mvPointer.dy.get(), pressure: mvPointer.p.get(), pointerType: mvPointer.pointerType, } } export function projectPoint(x0: number, y0: number, a: number, d: number) { return [Math.cos(a) * d + x0, Math.sin(a) * d + y0] } export const useSelector = createSelectorHook(state) export default state // state.onUpdate((update) => console.log(update.active, update.log[0]))
the_stack
import { grpc } from '@improbable-eng/grpc-web' import { ContextInterface } from '@textile/context' import { CreateRequest, DeleteRequest, DiscardRequest, FindByIDRequest, FindRequest, HasRequest, SaveRequest, StartTransactionRequest, VerifyRequest, WriteTransactionReply, WriteTransactionRequest, } from '@textile/threads-client-grpc/threads_pb' import { ThreadID } from '@textile/threads-id' import { QueryJSON } from './query' import { Transaction } from './Transaction' const decoder = new TextDecoder() const encoder = new TextEncoder() /** * WriteTransaction performs a mutating bulk transaction on the underlying store. * {@inheritDoc @textile/threads-client#Transaction} * @example * Create a new entry in our collection * ```typescript * import {Client, ThreadID} from '@textile/threads' * * interface Astronaut { * name: string * missions: number * _id: string * } * * async function createBuzz (client: Client, threadID: ThreadID) { * const buzz: Astronaut = { * name: 'Buzz', * missions: 2, * _id: '', * } * * const t = client.writeTransaction(threadID, 'astronauts') * await t.start() * await t.create([buzz]) * await t.end() // Commit * } * ``` * * @example * Abort an in-flight transaction * ```typescript * import {Client, ThreadID} from '@textile/threads' * * interface Astronaut { * name: string * missions: number * _id: string * } * * async function createBuzz (client: Client, threadID: ThreadID) { * const buzz: Astronaut = { * name: 'Buzz', * missions: 2, * _id: '', * } * * const t = client.writeTransaction(threadID, 'astronauts') * await t.start() * await t.create([buzz]) * await t.discard() // Abort * await t.end() * } * ``` */ export class WriteTransaction extends Transaction< WriteTransactionRequest, WriteTransactionReply > { constructor( protected readonly context: ContextInterface, protected readonly client: grpc.Client< WriteTransactionRequest, WriteTransactionReply >, protected readonly threadID: ThreadID, protected readonly modelName: string, ) { super(client, threadID, modelName) } /** * start begins the transaction. All operations between start and end will be applied as a single transaction upon a call to end. */ public async start(): Promise<void> { const startReq = new StartTransactionRequest() startReq.setDbid(this.threadID.toBytes()) startReq.setCollectionname(this.modelName) const req = new WriteTransactionRequest() req.setStarttransactionrequest(startReq) const metadata = JSON.parse(JSON.stringify(this.context)) this.client.start(metadata) this.client.send(req) } /** * create creates a new model instance in the given store. * @param values An array of model instances as JSON/JS objects. */ public async create<T = unknown>(values: T[]): Promise<string[]> { return new Promise<Array<string>>((resolve, reject) => { const createReq = new CreateRequest() const list: Uint8Array[] = [] values.forEach((v) => { list.push(encoder.encode(JSON.stringify(v))) }) createReq.setInstancesList(list) const req = new WriteTransactionRequest() req.setCreaterequest(createReq) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getCreatereply() const err = reply?.getTransactionerror() if (err) { reject(new Error(err)) } if (reply === undefined) { resolve([]) } else { resolve(reply.toObject().instanceidsList) } }) super.setReject(reject) this.client.send(req) }) } /** * verify verifies existing instance changes. * @param values An array of instances as JSON/JS objects. */ public async verify<T = unknown>(values: T[]): Promise<void> { return new Promise<void>((resolve, reject) => { const innerRequest = new VerifyRequest() const list = values.map((v) => encoder.encode(JSON.stringify(v))) innerRequest.setInstancesList(list) const req = new WriteTransactionRequest() req.setVerifyrequest(innerRequest) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getVerifyreply() const err = reply?.getTransactionerror() if (err) { reject(new Error(err)) } resolve() }) super.setReject(reject) this.client.send(req) }) } /** * save saves changes to an existing model instance in the given store. * @param values An array of model instances as JSON/JS objects. Each model instance must have a valid existing `ID` property. */ public async save<T = unknown>(values: T[]): Promise<void> { return new Promise<void>((resolve, reject) => { const saveReq = new SaveRequest() const list: Uint8Array[] = [] values.forEach((v) => { if (!('_id' in v)) { ;(v as any)._id = '' // The server will add an _id if empty. } list.push(encoder.encode(JSON.stringify(v))) }) saveReq.setInstancesList(list) const req = new WriteTransactionRequest() req.setSaverequest(saveReq) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getSavereply() const err = reply?.getTransactionerror() if (err) { reject(new Error(err)) } resolve() }) super.setReject(reject) this.client.send(req) }) } /** * delete deletes an existing model instance from the given store. * @param IDs An array of instance ids to delete. */ public async delete(IDs: string[]): Promise<void> { return new Promise<void>((resolve, reject) => { const deleteReq = new DeleteRequest() deleteReq.setInstanceidsList(IDs) const req = new WriteTransactionRequest() req.setDeleterequest(deleteReq) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getDeletereply() const err = reply?.getTransactionerror() if (err) { reject(new Error(err)) } resolve() }) super.setReject(reject) this.client.send(req) }) } /** * has checks whether a given instance exists in the given store. * @param IDs An array of instance ids to check for. */ public async has(IDs: string[]): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { const hasReq = new HasRequest() hasReq.setInstanceidsList(IDs) const req = new WriteTransactionRequest() req.setHasrequest(hasReq) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getHasreply() const err = reply?.getTransactionerror() if (err) { reject(new Error(err)) } resolve(reply ? reply.getExists() : false) }) super.setReject(reject) this.client.send(req) }) } /** * find queries the store for entities matching the given query parameters. See Query for options. * @param query The object that describes the query. See Query for options. Alternatively, see QueryJSON for the basic interface. */ public async find<T = unknown>(query: QueryJSON): Promise<Array<T>> { return new Promise<Array<T>>((resolve, reject) => { const findReq = new FindRequest() findReq.setQueryjson(encoder.encode(JSON.stringify(query))) const req = new WriteTransactionRequest() req.setFindrequest(findReq) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getFindreply() const err = reply?.getTransactionerror() if (err) { reject(new Error(err)) } if (reply === undefined) { resolve([]) } else { const ret: Array<T> = reply .getInstancesList_asU8() .map((instance) => JSON.parse(decoder.decode(instance))) resolve(ret) } }) this.setReject(reject) this.client.send(req) }) } /** * findByID queries the store for the id of an instance. * @param ID The id of the instance to search for. */ public async findByID<T = unknown>(ID: string): Promise<T | undefined> { return new Promise<T | undefined>((resolve, reject) => { const findReq = new FindByIDRequest() findReq.setInstanceid(ID) const req = new WriteTransactionRequest() req.setFindbyidrequest(findReq) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getFindbyidreply() const err = reply?.getTransactionerror() if (err) { reject(new Error(err)) } if (reply === undefined) { resolve(undefined) } else { resolve(JSON.parse(decoder.decode(reply.getInstance_asU8()))) } }) this.setReject(reject) this.client.send(req) }) } /** * Discard drops all active transaction changes. * It also invalidates the transaction, so it will fail upon calling end. * @example * Abort an in-flight transaction * ```typescript * import {Client, ThreadID} from '@textile/threads' * * interface Astronaut { * name: string * missions: number * _id: string * } * * async function example (client: Client, threadID: ThreadID) { * const buzz: Astronaut = { * name: 'Buzz', * missions: 2, * _id: '', * } * * const t = client.writeTransaction(threadID, 'astronauts') * await t.start() * await t.create([buzz]) * await t.discard() // Abort * await t.end() * } * ``` */ public async discard(): Promise<void> { return new Promise<void>((resolve, reject) => { const req = new WriteTransactionRequest() req.setDiscardrequest(new DiscardRequest()) this.client.onMessage((message: WriteTransactionReply) => { const reply = message.getDiscardreply() if (reply) { resolve() } else { reject(new Error('unexpected response type')) } }) super.setReject(reject) this.client.send(req) }) } }
the_stack
import { Raycaster, Vector3 } from "three"; import { Octree } from "../core/Octree"; import { PointContainer } from "./PointContainer"; import { PointData } from "./PointData"; import { PointOctant } from "./PointOctant"; import { RayPointIntersection } from "./RayPointIntersection"; /** * Recursively counts the points that are in the given octant. * * @param octant - An octant. * @return The amount of points. */ function countPoints<T>(octant: PointOctant<T>): number { const children = octant.children; let result = 0; if(children !== null) { for(let i = 0, l = children.length; i < l; ++i) { result += countPoints(children[i] as PointOctant<T>); } } else if(octant.data !== null) { const pointData = octant.data; result = pointData.points.length; } return result; } /** * Recursively adds a point to the octree. * * @param point - A point. * @param data - The data that belongs to the point. * @param octree - The octree. * @param octant - The current octant. * @param depth - The current depth. * @return Whether the operation was successful. */ function set<T>(point: Vector3, data: T, octree: PointOctree<T>, octant: PointOctant<T>, depth: number): boolean { let children = octant.children; let exists = false; let done = false; if(octant.contains(point, octree.getBias())) { if(children === null) { let index = 0; if(octant.data === null) { octant.data = new PointData<T>(); } else { const pointData = octant.data; const points = pointData.points; for(let i = 0, l = points.length; !exists && i < l; ++i) { exists = points[i].equals(point); index = i; } } const pointData = octant.data; if(exists) { pointData.data[index - 1] = data; done = true; } else if(pointData.points.length < octree.getMaxPoints() || depth === octree.getMaxDepth()) { pointData.points.push(point.clone()); pointData.data.push(data); done = true; } else { octant.split(); octant.redistribute(octree.getBias()); children = octant.children; } } if(children !== null) { ++depth; for(let i = 0, l = children.length; !done && i < l; ++i) { done = set(point, data, octree, children[i] as PointOctant<T>, depth); } } } return done; } /** * Recursively finds a point in the octree and removes it. * * @param point - A point. * @param octree - The octree. * @param octant - The current octant. * @param parent - The parent of the current octant. * @return The data entry of the removed point, or null if it didn't exist. */ function remove<T>(point: Vector3, octree: PointOctree<T>, octant: PointOctant<T>, parent: PointOctant<T>): T { const children = octant.children; let result = null; if(octant.contains(point, octree.getBias())) { if(children !== null) { for(let i = 0, l = children.length; result === null && i < l; ++i) { result = remove(point, octree, children[i] as PointOctant<T>, octant); } } else if(octant.data !== null) { const pointData = octant.data; const points = pointData.points; const data = pointData.data; for(let i = 0, l = points.length; i < l; ++i) { if(points[i].equals(point)) { const last = l - 1; result = data[i]; // If the point is NOT the last one in the array: if(i < last) { // Overwrite with the last point and data entry. points[i] = points[last]; data[i] = data[last]; } // Drop the last entry. points.pop(); data.pop(); if(parent !== null && countPoints(parent) <= octree.getMaxPoints()) { parent.merge(); } break; } } } } return result; } /** * Recursively finds a point in the octree and fetches the associated data. * * @param point - A point. * @param octree - The octree. * @param octant - The current octant octant. * @return The data entry that is associated with the given point, or null if it doesn't exist. */ function get<T>(point: Vector3, octree: PointOctree<T>, octant: PointOctant<T>): T { const children = octant.children; let result = null; if(octant.contains(point, octree.getBias())) { if(children !== null) { for(let i = 0, l = children.length; result === null && i < l; ++i) { result = get(point, octree, children[i] as PointOctant<T>); } } else if(octant.data !== null) { const pointData = octant.data; const points = pointData.points; const data = pointData.data; for(let i = 0, l = points.length; result === null && i < l; ++i) { if(point.equals(points[i])) { result = data[i]; } } } } return result; } /** * Recursively moves an existing point to a new position. * * @param point - The point. * @param position - The new position. * @param octree - The octree. * @param octant - The current octant. * @param parent - The parent of the current octant. * @param depth - The current depth. * @return The data entry of the updated point, or null if it didn't exist. */ function move<T>(point: Vector3, position: Vector3, octree: PointOctree<T>, octant: PointOctant<T>, parent: PointOctant<T>, depth: number): T { const children = octant.children; let result = null; if(octant.contains(point, octree.getBias())) { if(octant.contains(position, octree.getBias())) { // The point and the new position both fall into the current octant. if(children !== null) { ++depth; for(let i = 0, l = children.length; result === null && i < l; ++i) { const child = children[i] as PointOctant<T>; result = move(point, position, octree, child, octant, depth); } } else if(octant.data !== null) { // No divergence - the point can be updated in place. const pointData = octant.data; const points = pointData.points; const data = pointData.data; for(let i = 0, l = points.length; i < l; ++i) { if(point.equals(points[i])) { // The point exists! Update its position. points[i].copy(position); result = data[i]; break; } } } } else { // Retrieve the point and remove it. result = remove(point, octree, octant, parent); // Go back to the parent octant and add the updated point. set(position, result, octree, parent, depth - 1); } } return result; } /** * Recursively finds the closest point to the given one. * * @param point - The point. * @param maxDistance - The maximum distance. * @param skipSelf - Whether a point that is exactly at the given position should be skipped. * @param octant - The current octant. * @return The nearest point, or null if there is none. */ function findNearestPoint<T>(point: Vector3, maxDistance: number, skipSelf: boolean, octant: PointOctant<T>): PointContainer<T> { interface SortableOctant<T> { octant: PointOctant<T>; distance: number; } let result = null; let bestDistance = maxDistance; if(octant.children !== null) { // Sort the children: smallest distance to the point first, ASC. const sortedChildren: SortableOctant<T>[] = octant.children.map((child) => { // Precompute distances. const octant = child as PointOctant<T>; return { distance: octant.distanceToCenterSquared(point), octant }; }).sort((a, b) => a.distance - b.distance); // Traverse from closest to furthest. for(let i = 0, l = sortedChildren.length; i < l; ++i) { const child = sortedChildren[i].octant; if(child.contains(point, bestDistance)) { const intermediateResult = findNearestPoint( point, bestDistance, skipSelf, child ); if(intermediateResult !== null) { bestDistance = intermediateResult.distance; result = intermediateResult; if(bestDistance === 0.0) { break; } } } } } else if(octant.data !== null) { const pointData = octant.data; const points = pointData.points; const data = pointData.data; let index = -1; for(let i = 0, l = points.length; i < l; ++i) { if(points[i].equals(point)) { if(!skipSelf) { bestDistance = 0.0; index = i; break; } } else { const distance = point.distanceTo(points[i]); if(distance < bestDistance) { bestDistance = distance; index = i; } } } if(index >= 0) { result = new PointContainer(points[index], data[index], bestDistance); } } return result; } /** * Recursively finds points within a specific radius around a given point. * * @param point - The point. * @param radius - The radius. * @param skipSelf - Whether a point that is exactly at the given position should be skipped. * @param octant - The current octant. * @param result - An array to be filled with points. */ function findPoints<T>(point: Vector3, radius: number, skipSelf: boolean, octant: PointOctant<T>, result: PointContainer<T>[]): void { const children = octant.children; if(children !== null) { for(let i = 0, l = children.length; i < l; ++i) { const child = children[i] as PointOctant<T>; if(child.contains(point, radius)) { findPoints(point, radius, skipSelf, child, result); } } } else if(octant.data !== null) { const pointData = octant.data; const points = pointData.points; const data = pointData.data; for(let i = 0, l = points.length; i < l; ++i) { const p = points[i]; if(p.equals(point)) { if(!skipSelf) { result.push(new PointContainer(p.clone(), data[i], 0.0)); } } else { const rSq = radius * radius; const dSq = p.distanceToSquared(point); if(dSq <= rSq) { result.push(new PointContainer(p.clone(), data[i], Math.sqrt(dSq))); } } } } } /** * An octree that manages points. * * @param T - The type of the data. */ export class PointOctree<T> extends Octree { /** * An octant boundary bias. */ private bias: number; /** * The number of points per octant before a split occurs. * * This value works together with the maximum depth as a secondary limiting * factor. Smaller values cause splits to occur earlier which results in a * faster and deeper tree growth. */ private maxPoints: number; /** * The maximum tree depth level. * * Infinity is a valid value, but allowing infinitely small octants can result * in poor performance. */ private maxDepth: number; /** * Constructs a new point octree. * * @param min - The lower bounds of the tree. * @param max - The upper bounds of the tree. * @param bias - An octant boundary bias. The octree is considered "loose" with a bias greater than 0. * @param maxPoints - The maximum amount of distinct points per leaf octant. * @param maxDepth - The maximum tree depth level, starting at 0. */ constructor( min: Vector3, max: Vector3, bias = 0.0, maxPoints = 8, maxDepth = 8 ) { super(new PointOctant<T>(min, max)); this.bias = Math.max(0.0, bias); this.maxPoints = Math.max(1, Math.round(maxPoints)); this.maxDepth = Math.max(0, Math.round(maxDepth)); } /** * Returns the octree bias. * * @return The bias. */ getBias(): number { return this.bias; } /** * Returns the maximum amount of points per leaf octant. * * @return The maximum amount of points per leaf octant. */ getMaxPoints(): number { return this.maxPoints; } /** * Returns the maximum tree depth. * * @return The maximum tree depth. */ getMaxDepth(): number { return this.maxDepth; } /** * Counts the points in the given octant. * * @param octant - An octant. Defaults to the root octant. * @return The amount of points. */ countPoints(octant: PointOctant<T> = this.root as PointOctant<T>): number { return countPoints(octant); } /** * Inserts a point into the octree. * * If the point exists in the tree already, the data entry will be replaced. * * @param point - The point. * @param data - Data that belongs to the point. * @return Whether the operation was successful. */ set(point: Vector3, data: T): boolean { return set(point, data, this, this.root as PointOctant<T>, 0); } /** * Removes a point from the tree. * * @param point - The point. * @return The data entry of the removed point or null if it didn't exist. */ remove(point: Vector3): T { return remove(point, this, this.root as PointOctant<T>, null); } /** * Retrieves the data of the specified point. * * @param point - A position. * @return The data that belongs to the given point, or null if it doesn't exist. */ get(point: Vector3): T { return get(point, this, this.root as PointOctant<T>); } /** * Moves an existing point to a new position. Has no effect if the point * doesn't exist. * * @param point - The point. * @param position - The new position. * @return The data of the updated point, or null if it didn't exist. */ move(point: Vector3, position: Vector3): T { return move(point, position, this, this.root as PointOctant<T>, null, 0); } /** * Finds the closest point to the given one. * * @param point - A point. * @param maxDistance - An upper limit for the distance between the points. * @param skipSelf - Whether a point that is exactly at the given position should be skipped. * @return The nearest point, or null if there is none. */ findNearestPoint(point: Vector3, maxDistance = Number.POSITIVE_INFINITY, skipSelf = false): PointContainer<T> { const root = this.root as PointOctant<T>; const result = findNearestPoint(point, maxDistance, skipSelf, root); if(result !== null) { result.point = result.point.clone(); } return result; } /** * Finds points within a specific radius around a given point. * * @param point - A position. * @param radius - A radius. * @param skipSelf - Whether a point that is exactly at the given position should be skipped. * @return A list of points. */ findPoints(point: Vector3, radius: number, skipSelf = false): PointContainer<T>[] { const result: PointContainer<T>[] = []; findPoints(point, radius, skipSelf, this.root as PointOctant<T>, result); return result; } /** * Finds the points that intersect with the given ray. * * @param raycaster - The raycaster. * @return The intersecting points. */ raycast(raycaster: Raycaster): RayPointIntersection<T>[] { const result: RayPointIntersection<T>[] = []; const octants = super.getIntersectingNodes(raycaster) as PointOctant<T>[]; if(octants.length > 0) { for(let i = 0, l = octants.length; i < l; ++i) { const octant = octants[i]; const pointData = octant.data; if(pointData !== null) { pointData.testPoints(raycaster, result); } } } return result; } }
the_stack
import { IdleTransaction, Transaction } from "@sentry/tracing"; import { Event } from "@sentry/types"; import { StallTrackingInstrumentation } from "../../src/js/tracing/stalltracking"; const hub = { captureEvent: jest.fn(), }; jest.mock("@sentry/hub", () => { const hubOriginal = jest.requireActual("@sentry/hub"); return { ...hubOriginal, getCurrentHub: () => hub, }; }); const getLastEvent = (): Event => { return hub.captureEvent.mock.calls[hub.captureEvent.mock.calls.length - 1][0]; }; const expensiveOperation = () => { const expensiveObject: { value: string[] } = { value: Array(100000).fill("expensive"), }; // This works in sync, so it should stall the js event loop for (let i = 0; i < 50; i++) { JSON.parse(JSON.stringify(expensiveObject)); } }; beforeEach(() => { jest.clearAllMocks(); }); describe("StallTracking", () => { it("Stall tracking detects a JS stall", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", sampled: true, }); transaction.initSpanRecorder(); stallTracking.onTransactionStart(transaction); expensiveOperation(); setTimeout(() => { stallTracking.onTransactionFinish(transaction); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeDefined(); if (measurements) { expect(measurements.stall_count.value).toBeGreaterThan(0); expect(measurements.stall_longest_time.value).toBeGreaterThan(0); expect(measurements.stall_total_time.value).toBeGreaterThan(0); } done(); }, 500); }); it("Stall tracking detects multiple JS stalls", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", sampled: true, }); transaction.initSpanRecorder(); stallTracking.onTransactionStart(transaction); expensiveOperation(); setTimeout(() => { expensiveOperation(); }, 200); setTimeout(() => { stallTracking.onTransactionFinish(transaction); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeDefined(); if (measurements) { expect(measurements.stall_count.value).toBe(2); expect(measurements.stall_longest_time.value).toBeGreaterThan(0); expect(measurements.stall_total_time.value).toBeGreaterThan(0); } done(); }, 500); }); it("Stall tracking timeout is stopped after finishing all transactions (single)", () => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", sampled: true, }); stallTracking.onTransactionStart(transaction); stallTracking.onTransactionFinish(transaction); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).not.toBe(null); expect(stallTracking.isTracking).toBe(false); }); it("Stall tracking timeout is stopped after finishing all transactions (multiple)", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction0 = new Transaction({ name: "Test Transaction 0", sampled: true, }); const transaction1 = new Transaction({ name: "Test Transaction 1", sampled: true, }); const transaction2 = new Transaction({ name: "Test Transaction 2", sampled: true, }); stallTracking.onTransactionStart(transaction0); stallTracking.onTransactionStart(transaction1); stallTracking.onTransactionFinish(transaction0); transaction0.finish(); const measurements0 = getLastEvent()?.measurements; expect(measurements0).toBeDefined(); setTimeout(() => { stallTracking.onTransactionFinish(transaction1); transaction1.finish(); const measurements1 = getLastEvent()?.measurements; expect(measurements1).toBeDefined(); }, 600); setTimeout(() => { stallTracking.onTransactionStart(transaction2); setTimeout(() => { stallTracking.onTransactionFinish(transaction2); transaction2.finish(); const measurements2 = getLastEvent()?.measurements; expect(measurements2).not.toBe(null); expect(stallTracking.isTracking).toBe(false); done(); }, 200); }, 500); // If the stall tracking does not correctly stop, the process will keep running. We detect this by passing --detectOpenHandles to jest. }); it("Stall tracking returns measurements format on finish", () => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", sampled: true, }); stallTracking.onTransactionStart(transaction); stallTracking.onTransactionFinish(transaction); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeDefined(); if (measurements) { expect(measurements.stall_count.value).toBe(0); expect(measurements.stall_longest_time.value).toBe(0); expect(measurements.stall_total_time.value).toBe(0); } }); it("Stall tracking returns null on a custom endTimestamp that is not a span's", () => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", sampled: true, }); stallTracking.onTransactionStart(transaction); stallTracking.onTransactionFinish(transaction, Date.now() / 1000); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeUndefined(); }); it("Stall tracking supports endTimestamp that is from the last span (trimEnd case)", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", trimEnd: true, sampled: true, }); transaction.initSpanRecorder(); stallTracking.onTransactionStart(transaction); const span = transaction.startChild({ description: "Test Span", }); let spanFinishTime: number | undefined; setTimeout(() => { spanFinishTime = Date.now() / 1000; span.finish(spanFinishTime); }, 100); setTimeout(() => { expect(spanFinishTime).toEqual(expect.any(Number)); stallTracking.onTransactionFinish(transaction); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeDefined(); if (measurements) { expect(measurements.stall_count.value).toEqual(expect.any(Number)); expect(measurements.stall_longest_time.value).toEqual( expect.any(Number) ); expect(measurements.stall_total_time.value).toEqual(expect.any(Number)); } done(); }, 400); }); it("Stall tracking rejects endTimestamp that is from the last span if trimEnd is false (trimEnd case)", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", trimEnd: false, sampled: true, }); transaction.initSpanRecorder(); stallTracking.onTransactionStart(transaction); const span = transaction.startChild({ description: "Test Span", }); let spanFinishTime: number | undefined; setTimeout(() => { spanFinishTime = Date.now() / 1000; span.finish(spanFinishTime); }, 100); setTimeout(() => { expect(spanFinishTime).toEqual(expect.any(Number)); stallTracking.onTransactionFinish(transaction, spanFinishTime); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeUndefined(); done(); }, 400); }); it("Stall tracking rejects endTimestamp even if it is a span time (custom endTimestamp case)", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", sampled: true, }); transaction.initSpanRecorder(); stallTracking.onTransactionStart(transaction); const span = transaction.startChild({ description: "Test Span", }); let spanFinishTime: number | undefined; setTimeout(() => { spanFinishTime = Date.now() / 1000; span.finish(spanFinishTime); }, 100); setTimeout(() => { expect(spanFinishTime).toEqual(expect.any(Number)); if (typeof spanFinishTime === "number") { stallTracking.onTransactionFinish(transaction, spanFinishTime + 0.015); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeUndefined(); } done(); }, 400); }); it("Stall tracking supports idleTransaction with unfinished spans", (done) => { const stallTracking = new StallTrackingInstrumentation(); const idleTransaction = new IdleTransaction({ name: "Test Transaction", trimEnd: true, sampled: true, }); idleTransaction.initSpanRecorder(); stallTracking.onTransactionStart(idleTransaction); idleTransaction.registerBeforeFinishCallback((_, endTimestamp) => { stallTracking.onTransactionFinish(idleTransaction, endTimestamp); }); // Span is never finished. idleTransaction.startChild({ description: "Test Span", }); setTimeout(() => { idleTransaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeDefined(); if (measurements) { expect(measurements.stall_count.value).toEqual(expect.any(Number)); expect(measurements.stall_longest_time.value).toEqual( expect.any(Number) ); expect(measurements.stall_total_time.value).toEqual(expect.any(Number)); } done(); }, 100); }); it("Stall tracking ignores unfinished spans in normal transactions", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", trimEnd: true, sampled: true, }); transaction.initSpanRecorder(); stallTracking.onTransactionStart(transaction); // Span is never finished. transaction.startChild({ description: "Test Span", }); // Span will be finished const span = transaction.startChild({ description: "To Finish", }); setTimeout(() => { span.finish(); }, 100); setTimeout(() => { stallTracking.onTransactionFinish(transaction); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeDefined(); if (measurements) { expect(measurements.stall_count.value).toEqual(expect.any(Number)); expect(measurements.stall_longest_time.value).toEqual( expect.any(Number) ); expect(measurements.stall_total_time.value).toEqual(expect.any(Number)); } done(); }, 500); }); it("Stall tracking only measures stalls inside the final time when trimEnd is used", (done) => { const stallTracking = new StallTrackingInstrumentation(); const transaction = new Transaction({ name: "Test Transaction", trimEnd: true, sampled: true, }); transaction.initSpanRecorder(); stallTracking.onTransactionStart(transaction); // Span will be finished const span = transaction.startChild({ description: "To Finish", }); setTimeout(() => { span.finish(); }, 200); setTimeout(() => { stallTracking.onTransactionFinish(transaction); transaction.finish(); const measurements = getLastEvent()?.measurements; expect(measurements).toBeDefined(); if (measurements) { expect(measurements.stall_count.value).toEqual(1); expect(measurements.stall_longest_time.value).toEqual( expect.any(Number) ); expect(measurements.stall_total_time.value).toEqual(expect.any(Number)); } done(); }, 500); setTimeout(() => { // this should be run after the span finishes, and not logged. expensiveOperation(); }, 300); expensiveOperation(); }); it("Stall tracking does not track the first transaction if more than 10 are running", () => { const stallTracking = new StallTrackingInstrumentation(); const transactions = new Array(11).fill(0).map((_, i) => { const transaction = new Transaction({ name: `Test Transaction ${i}`, sampled: true, }); stallTracking.onTransactionStart(transaction); return transaction; }); stallTracking.onTransactionFinish(transactions[0]); transactions[0].finish(); const measurements0 = getLastEvent()?.measurements; expect(measurements0).toBeUndefined(); stallTracking.onTransactionFinish(transactions[1]); transactions[1].finish(); const measurements1 = getLastEvent()?.measurements; expect(measurements1).toBeDefined(); transactions.slice(2).forEach((transaction) => { stallTracking.onTransactionFinish(transaction); transaction.finish(); }); }); });
the_stack
import cn from 'classnames' import * as PropTypes from 'prop-types' import * as React from 'react' import { useImperativeHandle, useMemo, useRef, useState } from 'react' import { useUncontrolledProp } from 'uncontrollable' import { caretDown } from './Icon' import Input from './Input' import List, { ListHandle } from './List' import { FocusListContext, useFocusList } from './FocusListContext' import BasePopup from './Popup' import InputAddon from './InputAddon' import Widget from './Widget' import WidgetPicker from './WidgetPicker' import { useMessagesWithDefaults } from './messages' import { BaseListboxInputProps, ChangeHandler, Filterable, PopupWidgetProps, SelectHandler, WidgetHTMLProps, WidgetProps, } from './shared' import { DataItem, WidgetHandle } from './types' import { useActiveDescendant } from './A11y' import * as CustomPropTypes from './PropTypes' import { TextAccessorFn, useAccessors } from './Accessors' import { useFilteredData } from './Filter' import useDropdownToggle from './useDropdownToggle' import useFocusManager from './useFocusManager' import { notify, useFirstFocusedRender, useInstanceId } from './WidgetHelpers' import { Spinner } from './Icon' function indexOf<TDataItem>( data: readonly TDataItem[], searchTerm: string, text: TextAccessorFn, ) { if (!searchTerm.trim()) return -1 for (let idx = 0; idx < data.length; idx++) if (text(data[idx]).toLowerCase() === searchTerm) return idx return -1 } let propTypes = { value: PropTypes.any, onChange: PropTypes.func, open: PropTypes.bool, onToggle: PropTypes.func, renderListItem: PropTypes.func, listComponent: PropTypes.elementType, renderListGroup: PropTypes.func, groupBy: CustomPropTypes.accessor, data: PropTypes.array, dataKey: CustomPropTypes.accessor, textField: CustomPropTypes.accessor, name: PropTypes.string, /** Do not show the auto complete list when it returns no results. */ hideEmptyPopup: PropTypes.bool, /** Hide the combobox dropdown indicator. */ hideCaret: PropTypes.bool, /** * * @type {(dataItem: ?any, metadata: { originalEvent: SyntheticEvent }) => void} */ onSelect: PropTypes.func, autoFocus: PropTypes.bool, disabled: CustomPropTypes.disabled.acceptsArray, readOnly: CustomPropTypes.disabled, busy: PropTypes.bool, /** Specify the element used to render the select (down arrow) icon. */ selectIcon: PropTypes.node, /** Specify the element used to render the busy indicator */ busySpinner: PropTypes.node, dropUp: PropTypes.bool, popupTransition: PropTypes.elementType, placeholder: PropTypes.string, /** Adds a css class to the input container element. */ containerClassName: PropTypes.string, inputProps: PropTypes.object, listProps: PropTypes.object, messages: PropTypes.shape({ openCombobox: CustomPropTypes.message, emptyList: CustomPropTypes.message, emptyFilter: CustomPropTypes.message, }), } export type ComboboxHandle = WidgetHandle export interface ComboboxProps<TDataItem = DataItem> extends WidgetHTMLProps, WidgetProps, PopupWidgetProps, Filterable<TDataItem>, BaseListboxInputProps<TDataItem, string | TDataItem> { name?: string /** * If a `data` item matches the current typed value select it automatically. */ autoSelectMatches?: boolean onChange?: ChangeHandler<TDataItem | string> onSelect?: SelectHandler<TDataItem | string> hideCaret?: boolean hideEmptyPopup?: boolean } declare interface Combobox { <TDataItem = DataItem>( props: ComboboxProps<TDataItem> & React.RefAttributes<ComboboxHandle>, ): React.ReactElement | null displayName?: string propTypes?: any } /** * --- * shortcuts: * - { key: alt + down arrow, label: open combobox } * - { key: alt + up arrow, label: close combobox } * - { key: down arrow, label: move focus to next item } * - { key: up arrow, label: move focus to previous item } * - { key: home, label: move focus to first item } * - { key: end, label: move focus to last item } * - { key: enter, label: select focused item } * - { key: any key, label: search list for item starting with key } * --- * * Select an item from the list, or input a custom value. The Combobox can also make suggestions as you type. * @public */ const ComboboxImpl: Combobox = React.forwardRef(function Combobox<TDataItem>( { id, className, containerClassName, placeholder, autoFocus, textField, dataKey, autoSelectMatches, focusFirstItem = false, value, defaultValue = '', onChange, open, defaultOpen = false, onToggle, filter = true, busy, disabled, readOnly, selectIcon = caretDown, hideCaret, hideEmptyPopup, busySpinner, dropUp, tabIndex, popupTransition, name, onSelect, onKeyDown, onBlur, onFocus, inputProps, listProps, groupBy, renderListItem, renderListGroup, optionComponent, listComponent: ListComponent = List, popupComponent: Popup = BasePopup, data: rawData = [], messages: userMessages, ...elementProps }: ComboboxProps<TDataItem>, outerRef: React.RefObject<ComboboxHandle>, ) { let [currentValue, handleChange] = useUncontrolledProp( value, defaultValue, onChange, ) const [currentOpen, handleOpen] = useUncontrolledProp( open, defaultOpen, onToggle, ) const ref = useRef<HTMLDivElement>(null) const inputRef = useRef<HTMLInputElement>(null) const listRef = useRef<ListHandle>(null) const [suggestion, setSuggestion] = useState<TDataItem | null>(null) const shouldFilter = useRef(false) const inputId = useInstanceId(id, '_input') const listId = useInstanceId(id, '_listbox') const activeId = useInstanceId(id, '_listbox_active_option') const accessors = useAccessors(textField, dataKey) const messages = useMessagesWithDefaults(userMessages) const toggle = useDropdownToggle(currentOpen, handleOpen) const isDisabled = disabled === true const isReadOnly = !!readOnly const data = useFilteredData( rawData, filter, shouldFilter.current ? accessors.text(currentValue) : void 0, accessors.text, ) const selectedItem = useMemo( () => data[accessors.indexOf(data, currentValue)], [data, currentValue, accessors], ) const list = useFocusList<TDataItem>({ activeId, scope: ref, focusFirstItem, anchorItem: currentOpen ? selectedItem : undefined, }) const [focusEvents, focused] = useFocusManager( ref, { disabled: isDisabled, onBlur, onFocus }, { didHandle(focused) { if (!focused) { shouldFilter.current = false toggle.close() setSuggestion(null) list.focus(undefined) } else { focus({ preventScroll: true }) } }, }, ) useActiveDescendant(ref, activeId, currentOpen, [list.getFocused()]) /** * Handlers */ const handleClick = (e: React.MouseEvent) => { if (readOnly || isDisabled) return // prevents double clicks when in a <label> e.preventDefault() focus() toggle() } const handleSelect = ( data: string | TDataItem, originalEvent: React.SyntheticEvent, ) => { toggle.close() shouldFilter.current = false setSuggestion(null) notify(onSelect, [data, { originalEvent }]) change(data, originalEvent, true) focus({ preventScroll: true }) } const handleInputKeyDown = ({ key, }: React.KeyboardEvent<HTMLInputElement>) => { if (key === 'Backspace' || key === 'Delete') { list.focus(null) } } const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { let idx = autoSelectMatches ? indexOf(rawData, event.target.value.toLowerCase(), accessors.text) : -1 shouldFilter.current = true setSuggestion(null) const nextValue = idx === -1 ? event.target.value : rawData[idx] change(nextValue, event) if (!nextValue) toggle.close() else toggle.open() } const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => { if (readOnly) return let { key, altKey, shiftKey } = e notify(onKeyDown, [e]) if (e.defaultPrevented) return const select = (item: TDataItem | undefined) => item != null && handleSelect(item, e) const setFocused = (el?: HTMLElement) => { if (!el) return setSuggestion(list.toDataItem(el)!) list.focus(el) } if (key === 'End' && currentOpen && !shiftKey) { e.preventDefault() setFocused(list.last()) } else if (key === 'Home' && currentOpen && !shiftKey) { e.preventDefault() setFocused(list.first()) } else if (key === 'Escape' && currentOpen) { e.preventDefault() setSuggestion(null) toggle.close() } else if (key === 'Enter' && currentOpen) { e.preventDefault() select(list.getFocused()!) } else if (key === 'ArrowDown') { e.preventDefault() if (currentOpen) { setFocused(list.next()) } else { return toggle.open() } } else if (key === 'ArrowUp') { e.preventDefault() if (altKey) return toggle.close() if (currentOpen) { setFocused(list.prev()) } } } /** * Methods */ function focus(opts?: FocusOptions) { if (inputRef.current) inputRef.current.focus(opts) } function change( nextValue: TDataItem | string, originalEvent?: React.SyntheticEvent, selected = false, ) { handleChange(nextValue, { lastValue: currentValue, originalEvent, source: selected ? 'listbox' : 'input', }) } /** * Rendering */ useImperativeHandle(outerRef, () => ({ focus, })) let shouldRenderPopup = useFirstFocusedRender(focused, currentOpen!) let valueItem = accessors.findOrSelf(data, currentValue) let inputValue = accessors.text(suggestion || valueItem) let completeType = filter ? ('list' as const) : ('none' as const) let popupOpen = currentOpen && (!hideEmptyPopup || !!data.length) let inputReadOnly = // @ts-ignore inputProps?.readOnly != null ? inputProps?.readOnly : readOnly let inputAddon: React.ReactNode = false if (!hideCaret) { inputAddon = ( <InputAddon busy={busy} icon={selectIcon} spinner={busySpinner} onClick={handleClick} disabled={!!isDisabled || isReadOnly} // FIXME label={messages.openCombobox()} /> ) } else if (busy) { inputAddon = ( <span aria-hidden="true" className="rw-btn rw-picker-caret"> {busySpinner || Spinner} </span> ) } return ( <Widget {...elementProps} ref={ref} open={currentOpen} dropUp={dropUp} focused={focused} disabled={isDisabled} readOnly={isReadOnly} {...focusEvents} onKeyDown={handleKeyDown} className={cn(className, 'rw-combobox')} > <WidgetPicker className={cn( containerClassName, hideCaret && 'rw-widget-input', hideCaret && !busy && 'rw-hide-caret', )} > <Input {...inputProps} role="combobox" name={name} id={inputId} className={cn( // @ts-ignore inputProps && inputProps.className, 'rw-combobox-input', !hideCaret && 'rw-widget-input', )} autoFocus={autoFocus} tabIndex={tabIndex} disabled={isDisabled} readOnly={inputReadOnly} aria-busy={!!busy} aria-owns={listId} aria-autocomplete={completeType} aria-expanded={currentOpen} aria-haspopup={true} placeholder={placeholder} value={inputValue} onChange={handleInputChange} onKeyDown={handleInputKeyDown} ref={inputRef} /> {inputAddon} </WidgetPicker> <FocusListContext.Provider value={list.context}> {shouldRenderPopup && ( <Popup dropUp={dropUp} open={popupOpen} transition={popupTransition} onEntering={() => listRef.current!.scrollIntoView()} > <ListComponent {...listProps} id={listId} tabIndex={-1} data={data} groupBy={groupBy} disabled={disabled} accessors={accessors} renderItem={renderListItem} renderGroup={renderListGroup} optionComponent={optionComponent} value={selectedItem} searchTerm={(valueItem && accessors.text(valueItem)) || ''} aria-hidden={!popupOpen} aria-labelledby={inputId} aria-live={popupOpen ? 'polite' : void 0} onChange={(d, meta) => handleSelect(d as TDataItem, meta.originalEvent!) } ref={listRef} messages={{ emptyList: rawData.length ? messages.emptyFilter : messages.emptyList, }} /> </Popup> )} </FocusListContext.Provider> </Widget> ) }) ComboboxImpl.displayName = 'Combobox' ComboboxImpl.propTypes = propTypes export default ComboboxImpl
the_stack
import { IAdaptiveCard, ICardElement } from 'adaptivecards'; // tslint:disable-next-line: no-submodule-imports import { IContainer } from 'adaptivecards/lib/schema'; import { ActivityTypes } from 'botbuilder'; import { Activity, CardFactory, MessageFactory } from 'botbuilder-core'; import { ActionTypes, Attachment } from 'botframework-schema'; import { readFileSync } from 'fs'; import { join } from 'path'; import { Card } from './card'; import { ICardData } from './cardData'; import { IReply } from './reply'; import { IResponseIdCollection } from './responseIdCollection'; import { ResponseTemplate } from './responseTemplate'; import { ResponsesUtil } from '../util/'; export class ResponseManager { private readonly defaultLocaleKey: string = 'default'; private static readonly simpleTokensRegex: RegExp = /\{(\w+)\}/g; private static readonly complexTokensRegex: RegExp = /\{[^{\}]+(?=})\}/g; public constructor(locales: string[], responseTemplates: IResponseIdCollection[]) { this.jsonResponses = new Map(); responseTemplates.forEach((responseTemplate: IResponseIdCollection): void => { const resourceName: string = responseTemplate.name; const resource: string = responseTemplate.pathToResource || join(__dirname, '..', 'resources'); this.loadResponses(resourceName, resource); locales.forEach((locale: string): void => { try { this.loadResponses(resourceName, resource, locale); } catch { // If satellite assembly doesn't exist, bot will fall back to default. } }); }); } public jsonResponses: Map<string, Map<string, ResponseTemplate>>; /** * Gets a simple response from template with Text, Speak, InputHint, and SuggestedActions set. * @param templateId The name of the response template. * @param tokens string map of tokens to replace in the response. * @returns An Activity. */ public getResponse(templateId: string, locale: string, tokens?: Map<string, string>): Partial<Activity> { const template: ResponseTemplate = this.getResponseTemplate(templateId, locale); // create the response the data items return this.parseResponse(template, tokens); } /** * Gets a simple response from template with Text, Speak, InputHint, and SuggestedActions set. * @param templateId The name of the response template. * @param locale The locale for the response template. * @param tokens string map of tokens to replace in the response. * @returns An Activity. */ public getLocalizedResponse(templateId: string, locale: string, tokens?: Map<string, string>): Partial<Activity> { const template: ResponseTemplate = this.getResponseTemplate(templateId, locale); // create the response the data items return this.parseResponse(template, tokens); } /** * Gets the Text of a response. * @param templateId The name of the response template. * @param tokens string map of tokens to replace in the response. * @returns The response text. */ public getResponseText(templateId: string, locale: string, tokens?: Map<string, string>): string { const text: string | undefined = this.getResponse(templateId, locale, tokens).text; return text !== undefined ? text : ''; } /** * Get a response with an Adaptive Card attachment. * @param cards The card(s) to add to the response. * @returns An Activity. */ public getCardResponse(cards: Card | Card[], locale: string): Partial<Activity> { const resourcePath: string = join(__dirname, '..', 'resources', 'cards'); if (cards instanceof Card) { const json: string = this.loadCardJson(cards.name, locale, resourcePath); const attachment: Attachment = this.buildCardAttachment(json, cards.data); return MessageFactory.attachment(attachment); } else { const attachments: Attachment[] = []; cards.forEach((card: Card): void => { const json: string = this.loadCardJson(card.name, locale, resourcePath); attachments.push(this.buildCardAttachment(json, card.data)); }); return MessageFactory.carousel(attachments); } } /** * Get a response from template with Text, Speak, InputHint, SuggestedActions, and an Adaptive Card attachment. * @param templateId The name of the response template. * @param cards The card(s) object to add to the response. * @param tokens Optional string map of tokens to replace in the response. */ public getCardResponseWithTemplateId(templateId: string, cards: Card | Card[], locale: string, tokens?: Map<string, string>): Partial<Activity> { const response: Partial<Activity> = this.getResponse(templateId, locale, tokens); const resourcePath: string = join(__dirname, '..', 'resources', 'cards'); if (cards instanceof Card) { const json: string = this.loadCardJson(cards.name, locale, resourcePath); const attachment: Attachment = this.buildCardAttachment(json, cards.data); return MessageFactory.attachment(attachment, response.text, response.speak, response.inputHint); } else { const attachments: Attachment[] = []; cards.forEach((card: Card): void => { const json: string = this.loadCardJson(card.name, locale, resourcePath); attachments.push(this.buildCardAttachment(json, card.data)); }); return MessageFactory.carousel(attachments, response.text, response.speak, response.inputHint); } } /** * Get a response from template with Text, Speak, InputHint, SuggestedActions, and a Card attachments with list items inside. * @param templateId The name of the response template. * @param card The main card container contains list. * @param tokens Optional string map of tokens to replace in the response. * @param containerName Target container. * @param containerItems Card list which will be injected to target container. * @returns An Activity. */ public getCardResponseWithContainer( templateId: string, card: Card, locale: string, tokens?: Map<string, string>, containerName?: string, containerItems?: Card[]): Partial<Activity> { const resourcePath: string = join(__dirname, '..', 'resources', 'cards'); const json: string = this.loadCardJson(card.name, locale, resourcePath); const mainCard: IAdaptiveCard = this.buildCard(json, card.data); if (containerName && mainCard.body) { const itemContainer: ICardElement | undefined = mainCard.body.find((item: ICardElement): boolean => { return item.type === 'Container' && item.id === containerName; }); const itemsAdaptiveContainer: IContainer = itemContainer as IContainer; if (itemsAdaptiveContainer !== undefined) { if (containerItems !== undefined) { containerItems.forEach((cardItem: Card): void => { const itemJson: string = this.loadCardJson(cardItem.name, locale, resourcePath); const itemCard: IAdaptiveCard = this.buildCard(itemJson, cardItem.data); if (itemCard.body !== undefined) { itemCard.body.forEach((body: any): void => { if (itemsAdaptiveContainer.items !== undefined) { itemsAdaptiveContainer.items.push(body); } }); } }); } } } const attachment: Attachment = CardFactory.adaptiveCard(mainCard); if (templateId) { const response: Partial<Activity> = this.getResponse(templateId, locale, tokens); return MessageFactory.attachment(attachment, response.text, response.speak, response.inputHint); } return MessageFactory.attachment(attachment); } public getResponseTemplate(templateId: string, locale: string): ResponseTemplate { let localeKey: string = locale; // warm up the JsonResponses loading to see if it actually exist. // If not, throw with the loading time exception that's actually helpful let key: string | undefined = this.getJsonResponseKeyForLocale(templateId, localeKey); // if no matching json file found for locale, try parent language if (key === undefined) { localeKey = localeKey.split('-')[0] .toLowerCase(); key = this.getJsonResponseKeyForLocale(templateId, localeKey); // fall back to default if (key === undefined) { localeKey = this.defaultLocaleKey; key = this.getJsonResponseKeyForLocale(templateId, localeKey); } } if (key === undefined) { throw new Error(); } // Get the bot response from the .json file const responseLocale: Map<string, ResponseTemplate> | undefined = this.jsonResponses.get(localeKey); if (!responseLocale || !responseLocale.has(key)) { throw new Error(`Unable to find response ${ templateId }`); } const response: ResponseTemplate | undefined = responseLocale.get(key); if (response === undefined) { throw new Error(); } return response; } public format(messageTemplate: string, tokens?: Map<string, string>): string { let result: string = messageTemplate; ResponseManager.complexTokensRegex.lastIndex = 0; let match: RegExpExecArray | null = ResponseManager.complexTokensRegex.exec(result); while (match) { const bindingJson: string = match[0]; const tokenKey: string = bindingJson .replace('{', '') .replace('}', ''); if (tokens && tokens.has(tokenKey)) { result = result.replace(bindingJson, tokens.get(tokenKey) || ''); } match = ResponseManager.complexTokensRegex.exec(result); } return result; } private loadResponses(resourceName: string, resourcePath: string, locale?: string): void { // if locale is not set, add resources under the default key. const localeKey: string = (locale !== undefined) ? locale : this.defaultLocaleKey; const jsonPath: string = ResponsesUtil.getResourcePath(resourceName, resourcePath, localeKey); try { const content: { [key: string]: Object } = JSON.parse(this.jsonFromFile(jsonPath)); const localeResponses: Map<string, ResponseTemplate> = this.jsonResponses.get(localeKey) || new Map<string, ResponseTemplate>(); Object.entries(content) .forEach((val: [string, Object]): void => { const key: string = val[0]; const value: ITemplate = val[1] as ITemplate; const template: ResponseTemplate = Object.assign(new ResponseTemplate(), value); localeResponses.set(key, template); }); this.jsonResponses.set(localeKey, localeResponses); } catch (err) { throw new Error(`Error deserializing ${ jsonPath }`); } } private getJsonResponseKeyForLocale(responseId: string, locale: string): string | undefined { if (this.jsonResponses.has(locale)) { const localeResponses: Map<string, ResponseTemplate> | undefined = this.jsonResponses.get(locale); if (localeResponses) { return localeResponses.has(responseId) ? responseId : undefined; } } return undefined; } private parseResponse(template: ResponseTemplate, data?: Map<string, string>): Partial<Activity> { const reply: IReply | undefined = template.reply; if (!reply) { throw new Error('There is no reply in the ResponseTemplate'); } if (reply.text) { reply.text = this.format(reply.text, data); } if (reply.speak) { reply.speak = this.format(reply.speak, data); } const activity: Partial<Activity> = { type: ActivityTypes.Message, text: reply.text, speak: reply.speak, inputHint: template.inputHint }; if (template.suggestedActions !== undefined && template.suggestedActions.length > 0) { activity.suggestedActions = { actions: [], to: [] }; template.suggestedActions.forEach((action: string): void => { if (activity.suggestedActions) { activity.suggestedActions.actions.push({ type: ActionTypes.ImBack, title: action, value: action }); } }); } activity.attachments = []; return activity; } private loadCardJson(cardName: string, locale: string, resourcePath: string): string { let jsonFile: string = join(resourcePath, `${ cardName }.${ locale }.json`); try { require.resolve(jsonFile); } catch (errLocale) { try { jsonFile = join(resourcePath, `${ cardName }.json`); require.resolve(jsonFile); } catch (error) { throw new Error(`Could not file Adaptive Card resource ${ jsonFile }`); } } return this.jsonFromFile(jsonFile); } private buildCardAttachment(json: string, data?: ICardData): Attachment { const card: IAdaptiveCard = this.buildCard(json, data); return CardFactory.adaptiveCard(card); } private buildCard(json: string, data?: ICardData): IAdaptiveCard { let jsonOut: string = json; // If cardData was provided if (data !== undefined) { // add all properties to the list const tokens: Map<string, string> = new Map<string, string>(); // get property names from cardData Object.entries(data) .forEach((entry: [string, string]): void => { if (!tokens.has(entry[0])) { tokens.set(entry[0], entry[1]); } }); // replace tokens in json ResponseManager.simpleTokensRegex.lastIndex = 0; let match: RegExpExecArray | null = ResponseManager.simpleTokensRegex.exec(jsonOut); while (match) { if (tokens.has(match[0])) { jsonOut = jsonOut.replace(match[0], tokens.get(match[0]) || ''); } match = ResponseManager.simpleTokensRegex.exec(jsonOut); } } // Deserialize/Serialize logic is needed to prevent JSON exception in prompts return JSON.parse(jsonOut); } private jsonFromFile(filePath: string): string { return readFileSync(filePath, 'utf8'); } } interface ITemplate { replies: IReply[]; suggestedActions: string[]; inputHint: string; }
the_stack
import { should } from 'chai'; import { tokenize, Input, Token } from './utils/tokenize'; describe("Methods", () => { before(() => { should(); }); describe("Methods", () => { it("single-line declaration with no parameters", async () => { const input = Input.InClass(`void Foo() { }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.Void, Token.Identifiers.MethodName("Foo"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace]); }); it("declaration with two parameters", async () => { const input = Input.InClass(` int Add(int x, int y) { return x + y; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.Int, Token.Identifiers.MethodName("Add"), Token.Punctuation.OpenParen, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("x"), Token.Punctuation.Comma, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("y"), Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Variables.ReadWrite("x"), Token.Operators.Arithmetic.Addition, Token.Variables.ReadWrite("y"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("declaration in with generic constraints", async () => { const input = Input.InClass(`TResult GetString<T, TResult>(T arg) where T : TResult { }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Type("TResult"), Token.Identifiers.MethodName("GetString"), Token.Punctuation.TypeParameters.Begin, Token.Identifiers.TypeParameterName("T"), Token.Punctuation.Comma, Token.Identifiers.TypeParameterName("TResult"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenParen, Token.Type("T"), Token.Identifiers.ParameterName("arg"), Token.Punctuation.CloseParen, Token.Keywords.Where, Token.Type("T"), Token.Punctuation.Colon, Token.Type("TResult"), Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace]); }); it("expression body", async () => { const input = Input.InClass(`int Add(int x, int y) => x + y;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.Int, Token.Identifiers.MethodName("Add"), Token.Punctuation.OpenParen, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("x"), Token.Punctuation.Comma, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("y"), Token.Punctuation.CloseParen, Token.Operators.Arrow, Token.Variables.ReadWrite("x"), Token.Operators.Arithmetic.Addition, Token.Variables.ReadWrite("y"), Token.Punctuation.Semicolon]); }); it("explicitly-implemented interface member", async () => { const input = Input.InClass(`string IFoo<string>.GetString();`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.String, Token.Type("IFoo"), Token.Punctuation.TypeParameters.Begin, Token.PrimitiveType.String, Token.Punctuation.TypeParameters.End, Token.Punctuation.Accessor, Token.Identifiers.MethodName("GetString"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.Semicolon]); }); it("declaration in interface", async () => { const input = Input.InInterface(`string GetString();`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.String, Token.Identifiers.MethodName("GetString"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.Semicolon]); }); it("declaration in interface with parameters", async () => { const input = Input.InInterface(`string GetString(string format, params object[] args);`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.String, Token.Identifiers.MethodName("GetString"), Token.Punctuation.OpenParen, Token.PrimitiveType.String, Token.Identifiers.ParameterName("format"), Token.Punctuation.Comma, Token.Keywords.Modifiers.Params, Token.PrimitiveType.Object, Token.Punctuation.OpenBracket, Token.Punctuation.CloseBracket, Token.Identifiers.ParameterName("args"), Token.Punctuation.CloseParen, Token.Punctuation.Semicolon]); }); it("declaration in interface with generic constraints", async () => { const input = Input.InInterface(`TResult GetString<T, TResult>(T arg) where T : TResult;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Type("TResult"), Token.Identifiers.MethodName("GetString"), Token.Punctuation.TypeParameters.Begin, Token.Identifiers.TypeParameterName("T"), Token.Punctuation.Comma, Token.Identifiers.TypeParameterName("TResult"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenParen, Token.Type("T"), Token.Identifiers.ParameterName("arg"), Token.Punctuation.CloseParen, Token.Keywords.Where, Token.Type("T"), Token.Punctuation.Colon, Token.Type("TResult"), Token.Punctuation.Semicolon]); }); it("declaration in interface with default implementation", async () => { const input = Input.InInterface(` int Add(int x, int y) { return x + y; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.Int, Token.Identifiers.MethodName("Add"), Token.Punctuation.OpenParen, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("x"), Token.Punctuation.Comma, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("y"), Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Variables.ReadWrite("x"), Token.Operators.Arithmetic.Addition, Token.Variables.ReadWrite("y"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("public override", async () => { const input = Input.InClass(`public override M() { }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Keywords.Modifiers.Override, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace ]); }); it("public virtual", async () => { const input = Input.InClass(`public virtual M() { }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Keywords.Modifiers.Virtual, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace ]); }); it("extension method", async () => { const input = Input.InClass(`public void M(this object o) { }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.PrimitiveType.Void, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Keywords.Modifiers.This, Token.PrimitiveType.Object, Token.Identifiers.ParameterName("o"), Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace ]); }); it("commented parameters are highlighted properly (issue omnisharp-vscode#802)", async () => { const input = Input.InClass(`public void methodWithParametersCommented(int p1, /*int p2*/, int p3) {}`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.PrimitiveType.Void, Token.Identifiers.MethodName("methodWithParametersCommented"), Token.Punctuation.OpenParen, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("p1"), Token.Punctuation.Comma, Token.Comment.MultiLine.Start, Token.Comment.MultiLine.Text("int p2"), Token.Comment.MultiLine.End, Token.Punctuation.Comma, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("p3"), Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace ]); }); it("return type is highlighted properly in interface (issue omnisharp-vscode#830)", async () => { const input = ` public interface test { Task test1(List<string> blah); Task test<T>(List<T> blah); }`; const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Keywords.Interface, Token.Identifiers.InterfaceName("test"), Token.Punctuation.OpenBrace, Token.Type("Task"), Token.Identifiers.MethodName("test1"), Token.Punctuation.OpenParen, Token.Type("List"), Token.Punctuation.TypeParameters.Begin, Token.PrimitiveType.String, Token.Punctuation.TypeParameters.End, Token.Identifiers.ParameterName("blah"), Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, Token.Type("Task"), Token.Identifiers.MethodName("test"), Token.Punctuation.TypeParameters.Begin, Token.Identifiers.TypeParameterName("T"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenParen, Token.Type("List"), Token.Punctuation.TypeParameters.Begin, Token.Type("T"), Token.Punctuation.TypeParameters.End, Token.Identifiers.ParameterName("blah"), Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace ]); }); it("attributes are highlighted properly (issue omnisharp-vscode#829)", async () => { const input = ` namespace Test { public class TestClass { [HttpPut] [Route("/meetups/{id}/users-going")] public void AddToGoingUsers(Guid id, string user) => _commandSender.Send(new MarkUserAsGoing(id, user.User)); [HttpPut] [Route("/meetups/{id}/users-not-going")] public void AddToNotGoingUsers(Guid id, string user) => _commandSender.Send(new MarkUserAsNotGoing(id, user.User)); [HttpPut] [Route("/meetups/{id}/users-not-sure-if-going")] public void AddToNotSureIfGoingUsers(Guid id, string user) => _commandSender.Send(new MarkUserAsNotSureIfGoing(id, user.User)); } }`; const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Namespace, Token.Identifiers.NamespaceName("Test"), Token.Punctuation.OpenBrace, Token.Keywords.Modifiers.Public, Token.Keywords.Class, Token.Identifiers.ClassName("TestClass"), Token.Punctuation.OpenBrace, // [HttpPut] // [Route("/meetups/{id}/users-going")] // public void AddToGoingUsers(Guid id, string user) => _commandSender.Send(new MarkUserAsGoing(id, user.User)); Token.Punctuation.OpenBracket, Token.Type("HttpPut"), Token.Punctuation.CloseBracket, Token.Punctuation.OpenBracket, Token.Type("Route"), Token.Punctuation.OpenParen, Token.Punctuation.String.Begin, Token.Literals.String("/meetups/{id}/users-going"), Token.Punctuation.String.End, Token.Punctuation.CloseParen, Token.Punctuation.CloseBracket, Token.Keywords.Modifiers.Public, Token.PrimitiveType.Void, Token.Identifiers.MethodName("AddToGoingUsers"), Token.Punctuation.OpenParen, Token.Type("Guid"), Token.Identifiers.ParameterName("id"), Token.Punctuation.Comma, Token.PrimitiveType.String, Token.Identifiers.ParameterName("user"), Token.Punctuation.CloseParen, Token.Operators.Arrow, Token.Variables.Object("_commandSender"), Token.Punctuation.Accessor, Token.Identifiers.MethodName("Send"), Token.Punctuation.OpenParen, Token.Keywords.New, Token.Type("MarkUserAsGoing"), Token.Punctuation.OpenParen, Token.Variables.ReadWrite("id"), Token.Punctuation.Comma, Token.Variables.Object("user"), Token.Punctuation.Accessor, Token.Variables.Property("User"), Token.Punctuation.CloseParen, Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, // [HttpPut] // [Route("/meetups/{id}/users-not-going")] // public void AddToNotGoingUsers(Guid id, string user) => _commandSender.Send(new MarkUserAsNotGoing(id, user.User)); Token.Punctuation.OpenBracket, Token.Type("HttpPut"), Token.Punctuation.CloseBracket, Token.Punctuation.OpenBracket, Token.Type("Route"), Token.Punctuation.OpenParen, Token.Punctuation.String.Begin, Token.Literals.String("/meetups/{id}/users-not-going"), Token.Punctuation.String.End, Token.Punctuation.CloseParen, Token.Punctuation.CloseBracket, Token.Keywords.Modifiers.Public, Token.PrimitiveType.Void, Token.Identifiers.MethodName("AddToNotGoingUsers"), Token.Punctuation.OpenParen, Token.Type("Guid"), Token.Identifiers.ParameterName("id"), Token.Punctuation.Comma, Token.PrimitiveType.String, Token.Identifiers.ParameterName("user"), Token.Punctuation.CloseParen, Token.Operators.Arrow, Token.Variables.Object("_commandSender"), Token.Punctuation.Accessor, Token.Identifiers.MethodName("Send"), Token.Punctuation.OpenParen, Token.Keywords.New, Token.Type("MarkUserAsNotGoing"), Token.Punctuation.OpenParen, Token.Variables.ReadWrite("id"), Token.Punctuation.Comma, Token.Variables.Object("user"), Token.Punctuation.Accessor, Token.Variables.Property("User"), Token.Punctuation.CloseParen, Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, // [HttpPut] // [Route("/meetups/{id}/users-not-sure-if-going")] // public void AddToNotSureIfGoingUsers(Guid id, string user) => _commandSender.Send(new MarkUserAsNotSureIfGoing(id, user.User)); Token.Punctuation.OpenBracket, Token.Type("HttpPut"), Token.Punctuation.CloseBracket, Token.Punctuation.OpenBracket, Token.Type("Route"), Token.Punctuation.OpenParen, Token.Punctuation.String.Begin, Token.Literals.String("/meetups/{id}/users-not-sure-if-going"), Token.Punctuation.String.End, Token.Punctuation.CloseParen, Token.Punctuation.CloseBracket, Token.Keywords.Modifiers.Public, Token.PrimitiveType.Void, Token.Identifiers.MethodName("AddToNotSureIfGoingUsers"), Token.Punctuation.OpenParen, Token.Type("Guid"), Token.Identifiers.ParameterName("id"), Token.Punctuation.Comma, Token.PrimitiveType.String, Token.Identifiers.ParameterName("user"), Token.Punctuation.CloseParen, Token.Operators.Arrow, Token.Variables.Object("_commandSender"), Token.Punctuation.Accessor, Token.Identifiers.MethodName("Send"), Token.Punctuation.OpenParen, Token.Keywords.New, Token.Type("MarkUserAsNotSureIfGoing"), Token.Punctuation.OpenParen, Token.Variables.ReadWrite("id"), Token.Punctuation.Comma, Token.Variables.Object("user"), Token.Punctuation.Accessor, Token.Variables.Property("User"), Token.Punctuation.CloseParen, Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace, Token.Punctuation.CloseBrace ]); }); it("shadowed methods are highlighted properly (issue omnisharp-vscode#1084)", async () => { const input = Input.InClass(` private new void foo1() //Correct highlight { } new void foo2() //Function name not highlighted { } `); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Private, Token.Keywords.Modifiers.New, Token.PrimitiveType.Void, Token.Identifiers.MethodName("foo1"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Comment.SingleLine.Start, Token.Comment.SingleLine.Text("Correct highlight"), Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace, Token.Keywords.Modifiers.New, Token.PrimitiveType.Void, Token.Identifiers.MethodName("foo2"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Comment.SingleLine.Start, Token.Comment.SingleLine.Text("Function name not highlighted"), Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace ]); }); it("comment at end of line does not change highlights - 1 (issue omnisharp-vscode#1091)", async () => { const input = Input.InClass(` public abstract void Notify(PlayerId playerId, ISessionResponse response); //the `); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Keywords.Modifiers.Abstract, Token.PrimitiveType.Void, Token.Identifiers.MethodName("Notify"), Token.Punctuation.OpenParen, Token.Type("PlayerId"), Token.Identifiers.ParameterName("playerId"), Token.Punctuation.Comma, Token.Type("ISessionResponse"), Token.Identifiers.ParameterName("response"), Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, Token.Comment.SingleLine.Start, Token.Comment.SingleLine.Text("the") ]); }); it("comment at end of line does not change highlights - 2 (issue omnisharp-vscode#1091)", async () => { const input = Input.InClass(` public abstract void Notify(PlayerId playerId, ISessionResponse response); //the `); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Keywords.Modifiers.Abstract, Token.PrimitiveType.Void, Token.Identifiers.MethodName("Notify"), Token.Punctuation.OpenParen, Token.Type("PlayerId"), Token.Identifiers.ParameterName("playerId"), Token.Punctuation.Comma, Token.Type("ISessionResponse"), Token.Identifiers.ParameterName("response"), Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, Token.Comment.SingleLine.Start, Token.Comment.SingleLine.Text("the") ]); }); it("comment at end of line does not change highlights - 3 (issue omnisharp-vscode#1091)", async () => { const input = Input.InClass(` public abstract void Notify(PlayerId playerId, ISessionResponse response); //the a `); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Keywords.Modifiers.Abstract, Token.PrimitiveType.Void, Token.Identifiers.MethodName("Notify"), Token.Punctuation.OpenParen, Token.Type("PlayerId"), Token.Identifiers.ParameterName("playerId"), Token.Punctuation.Comma, Token.Type("ISessionResponse"), Token.Identifiers.ParameterName("response"), Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, Token.Comment.SingleLine.Start, Token.Comment.SingleLine.Text("the a") ]); }); it("value is not incorrectly highlighted (issue omnisharp-vscode#268)", async () => { const input = ` namespace x { public class ClassA<T> { public class ClassAa<TT> { public bool MyMethod(string key, TT value) { return someObject.SomeCall(key, value); // on this line, 'value' is highlighted as though it were the keyword being used in a setter } } } } `; const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Namespace, Token.Identifiers.NamespaceName("x"), Token.Punctuation.OpenBrace, Token.Keywords.Modifiers.Public, Token.Keywords.Class, Token.Identifiers.ClassName("ClassA"), Token.Punctuation.TypeParameters.Begin, Token.Identifiers.TypeParameterName("T"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenBrace, Token.Keywords.Modifiers.Public, Token.Keywords.Class, Token.Identifiers.ClassName("ClassAa"), Token.Punctuation.TypeParameters.Begin, Token.Identifiers.TypeParameterName("TT"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenBrace, Token.Keywords.Modifiers.Public, Token.PrimitiveType.Bool, Token.Identifiers.MethodName("MyMethod"), Token.Punctuation.OpenParen, Token.PrimitiveType.String, Token.Identifiers.ParameterName("key"), Token.Punctuation.Comma, Token.Type("TT"), Token.Identifiers.ParameterName("value"), Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Variables.Object("someObject"), Token.Punctuation.Accessor, Token.Identifiers.MethodName("SomeCall"), Token.Punctuation.OpenParen, Token.Variables.ReadWrite("key"), Token.Punctuation.Comma, Token.Variables.ReadWrite("value"), Token.Punctuation.CloseParen, Token.Punctuation.Semicolon, Token.Comment.SingleLine.Start, Token.Comment.SingleLine.Text(" on this line, 'value' is highlighted as though it were the keyword being used in a setter"), Token.Punctuation.CloseBrace, Token.Punctuation.CloseBrace, Token.Punctuation.CloseBrace, Token.Punctuation.CloseBrace ]); }); it("parameters with default values (issue #30)", async () => { const input = Input.InClass(` void M(string p = null) { } `); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.Void, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.PrimitiveType.String, Token.Identifiers.ParameterName("p"), Token.Operators.Assignment, Token.Literals.Null, Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace ]); }); it("ref return", async () => { const input = Input.InClass(`ref int M() { return ref x; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.PrimitiveType.Int, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Keywords.Modifiers.Ref, Token.Variables.ReadWrite("x"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace ]); }); it("ref readonly return", async () => { const input = Input.InClass(`ref readonly int M() { return ref x; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.Keywords.Modifiers.ReadOnly, Token.PrimitiveType.Int, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Keywords.Modifiers.Ref, Token.Variables.ReadWrite("x"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace ]); }); it("expression body ref return", async () => { const input = Input.InClass(`ref int M() => ref x;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.PrimitiveType.Int, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Operators.Arrow, Token.Keywords.Modifiers.Ref, Token.Variables.ReadWrite("x"), Token.Punctuation.Semicolon]); }); it("expression body ref readonly return", async () => { const input = Input.InClass(`ref readonly int M() => ref x;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.Keywords.Modifiers.ReadOnly, Token.PrimitiveType.Int, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Operators.Arrow, Token.Keywords.Modifiers.Ref, Token.Variables.ReadWrite("x"), Token.Punctuation.Semicolon]); }); it("closing parenthesis of parameter list on next line", async () => { const input = Input.InClass(` void M( string s ) { }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.Void, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.PrimitiveType.String, Token.Identifiers.ParameterName("s"), Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace ]); }); it("parameters with multi-dimensional arrays (issue #86)", async () => { const input = Input.InClass(` public void LinearRegression(double[,] samples, double[] standardDeviations, int variables){ int info; alglib.linearmodel linearmodel; alglib.lrreport ar;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.PrimitiveType.Void, Token.Identifiers.MethodName("LinearRegression"), Token.Punctuation.OpenParen, Token.PrimitiveType.Double, Token.Punctuation.OpenBracket, Token.Punctuation.Comma, Token.Punctuation.CloseBracket, Token.Identifiers.ParameterName("samples"), Token.Punctuation.Comma, Token.PrimitiveType.Double, Token.Punctuation.OpenBracket, Token.Punctuation.CloseBracket, Token.Identifiers.ParameterName("standardDeviations"), Token.Punctuation.Comma, Token.PrimitiveType.Int, Token.Identifiers.ParameterName("variables"), Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.PrimitiveType.Int, Token.Identifiers.LocalName("info"), Token.Punctuation.Semicolon, Token.Type("alglib"), Token.Punctuation.Accessor, Token.Type("linearmodel"), Token.Identifiers.LocalName("linearmodel"), Token.Punctuation.Semicolon, Token.Type("alglib"), Token.Punctuation.Accessor, Token.Type("lrreport"), Token.Identifiers.LocalName("ar"), Token.Punctuation.Semicolon, ]); }); it("expression body and type constraint (issue #74)", async () => { const input = Input.InClass(` T id1<T>(T a) => a; T id2<T>(T a) where T : class => a;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Type("T"), Token.Identifiers.MethodName("id1"), Token.Punctuation.TypeParameters.Begin, Token.Identifiers.TypeParameterName("T"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenParen, Token.Type("T"), Token.Identifiers.ParameterName("a"), Token.Punctuation.CloseParen, Token.Operators.Arrow, Token.Variables.ReadWrite("a"), Token.Punctuation.Semicolon, Token.Type("T"), Token.Identifiers.MethodName("id2"), Token.Punctuation.TypeParameters.Begin, Token.Identifiers.TypeParameterName("T"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenParen, Token.Type("T"), Token.Identifiers.ParameterName("a"), Token.Punctuation.CloseParen, Token.Keywords.Where, Token.Type("T"), Token.Punctuation.Colon, Token.Keywords.Class, Token.Operators.Arrow, Token.Variables.ReadWrite("a"), Token.Punctuation.Semicolon ]); }); it("readonly members in struct (C# 8)", async () => { const input = Input.InClass(`readonly int M() { return x; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.ReadOnly, Token.PrimitiveType.Int, Token.Identifiers.MethodName("M"), Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Variables.ReadWrite("x"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace ]); }); }); });
the_stack
import * as angular from 'angular'; import { component, directive, registerNgModule, TestService } from './mocks'; import { Pipe, PipeTransform } from '../src'; describe('NgModule', () => { const moduleName = 'TestModule'; describe('has run and config methods', () => { it('module should have run and config blocks', () => { const NgModuleClass = registerNgModule(moduleName, [], [], []); expect(NgModuleClass.module.name).toBe(moduleName); expect(angular.module(moduleName)['_runBlocks'].length).toBe(1); expect(angular.module(moduleName)['_configBlocks'].length).toBe(1); expect(angular.module(moduleName)['_configBlocks'][0].length).toBe(3); expect(angular.module(moduleName)['_runBlocks'][0]).toBe(NgModuleClass.run); expect(angular.module(moduleName)['_configBlocks'][0][2][0]).toBe(NgModuleClass.config); }); }); describe('imports', () => { it('should define required module as dependency', () => { const importedModuleName = 'ImportedModule'; const importedModule = registerNgModule(importedModuleName, [], [], []); registerNgModule(moduleName, [importedModule], [], []); expect(angular.module(moduleName).requires).toEqual([importedModuleName]); }); }); describe('declarations', () => { describe('@Component:', () => { it('registers as component or directive', () => { registerNgModule(moduleName, [], [ component('camelCaseName'), // registers as component component('camel-case-name'), // registers as component component('[camelCaseName]'), // registers as directive component('[camel-case-name]'), // registers as directive ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; expect(invokeQueue.length).toEqual(4); invokeQueue.forEach((value: any, index: number) => { expect(value[0]).toEqual('$compileProvider'); if (index < 2) expect(value[1]).toEqual('component'); else expect(value[1]).toEqual('directive'); expect(value[2][0]).toEqual('camelCaseName'); }); }); describe('@Input and @Output', () => { it('assigns properties to @Component options bindings' , () => { registerNgModule(moduleName, [], [ component('camelCaseName') ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; const bindings = invokeQueue[0][2][1].bindings; expect(bindings).toBeDefined(); expect(bindings).toEqual({ testInput: '<?', testOutput: '&' }); }); }); describe('@HostListener', () => { it('injects $element and adds $postLink and $onDestroy lifecycle hooks' , () => { registerNgModule(moduleName, [], [ component('camelCaseName') ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; const ctrlProto = invokeQueue[0][2][1].controller.prototype; const inject = ctrlProto['constructor']['$inject']; inject.forEach(dependency => expect(typeof dependency).toBe('string')); expect(inject[0]).toEqual('$element'); expect(ctrlProto['$postLink']).toBeDefined(); expect(ctrlProto['$onDestroy']).toBeDefined(); }); }); describe('@ViewChild', () => { it('injects $element and adds $postLink and $onChanges lifecycle hooks' , () => { registerNgModule(moduleName, [], [ component('camelCaseName') ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; const ctrlProto = invokeQueue[0][2][1].controller.prototype; const inject = ctrlProto['constructor']['$inject']; inject.forEach(dependency => expect(typeof dependency).toBe('string')); expect(inject[0]).toEqual('$element'); expect(ctrlProto['$postLink']).toBeDefined(); expect(ctrlProto['$onChanges']).toBeDefined(); }); }); describe('lifecycle hooks', () => { it('replaces angular lifecycle hooks to angularjs lifecycle hooks' , () => { registerNgModule(moduleName, [], [ component('camelCaseName') ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; const ctrlProto = invokeQueue[0][2][1].controller.prototype; expect(ctrlProto['$onInit']).toBeDefined(); expect(ctrlProto['$postLink']).toBeDefined(); expect(ctrlProto['$onChanges']).toBeDefined(); expect(ctrlProto['$doCheck']).toBeDefined(); expect(ctrlProto['$onDestroy']).toBeDefined(); }); }); }); describe('@Directive:', () => { it('registers as directive', () => { registerNgModule(moduleName, [], [ directive('camelCaseName'), directive('camel-case-name'), directive('[camelCaseName]'), directive('[camel-case-name]'), ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; expect(invokeQueue.length).toEqual(4); invokeQueue.forEach((value: any) => { expect(value[0]).toEqual('$compileProvider'); expect(value[1]).toEqual('directive'); expect(value[2][0]).toEqual('camelCaseName'); }); }); describe('@Input and @Output', () => { it('assigns properties to @Directive bindToController bindings' , () => { const myDirective = directive('camelCaseName'); registerNgModule(moduleName, [], [ myDirective ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; const directiveObject = invokeQueue[0][2][1](); expect(directiveObject).toBeDefined(); expect(directiveObject.bindToController).toEqual({ testInput: '<?', testOutput: '&', }); }); }); describe('@HostListener', () => { it('injects $element and adds $postLink and $onDestroy lifecycle hooks' , () => { registerNgModule(moduleName, [], [ directive('[camel-case-name]') ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; const ctrlProto = invokeQueue[0][2][1]().controller.prototype; const inject = ctrlProto['constructor']['$inject']; inject.forEach(dependency => expect(typeof dependency).toBe('string')); expect(inject[0]).toEqual('$element'); expect(ctrlProto['$postLink']).toBeDefined(); expect(ctrlProto['$onDestroy']).toBeDefined(); }); }); describe('@ViewChild', () => { it('injects $element and adds $postLink and $onChanges lifecycle hooks' , () => { registerNgModule(moduleName, [], [ directive('[camel-case-name]') ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; const ctrlProto = invokeQueue[0][2][1]().controller.prototype; const inject = ctrlProto['constructor']['$inject']; inject.forEach(dependency => expect(typeof dependency).toBe('string')); expect(inject[0]).toEqual('$element'); expect(ctrlProto['$postLink']).toBeDefined(); expect(ctrlProto['$onChanges']).toBeDefined(); }); }); }); }); describe('providers', () => { describe('provided as array of classes', () => { it('registers provider using class type', () => { const providers = [TestService]; registerNgModule(moduleName, [], [], providers); expect(angular.module(moduleName)['_invokeQueue'].length).toEqual(providers.length); angular.module(moduleName)['_invokeQueue'].forEach((value: any, index: number) => { // expect(value[2][0]).toEqual(serviceName); expect(value[2][1]).toEqual(TestService); }); }); }); describe('provided using useClass syntax', () => { it('registers provider using provide token', () => { const providers = [{provide: 'useClassTestService', useClass: TestService}]; registerNgModule(moduleName, [], [], providers); // const $injector = angular.injector([moduleName]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; expect(invokeQueue.length).toEqual(providers.length); invokeQueue.forEach((value: any, index: number) => { expect(value[0]).toEqual('$provide'); expect(value[1]).toEqual('service'); expect(value[2][0]).toEqual(providers[index].provide); expect(value[2][1]).toEqual(providers[index].useClass); expect(TestService).toEqual(providers[index].useClass); }); // expect($injector.get(anotherServiceName)).toEqual($injector.get(serviceName)); }); }); describe('useFactory', () => { it('registers provider using string token', () => { const providers = [{provide: 'useFactoryTestService', useFactory: (...args) => new TestService(args)}]; registerNgModule(moduleName, [], [], providers); const invokeQueue = angular.module(moduleName)['_invokeQueue']; expect(invokeQueue.length).toEqual(providers.length); invokeQueue.forEach((value: any, index: number) => { expect(value[0]).toEqual('$provide'); expect(value[1]).toEqual('factory'); expect(value[2][0]).toEqual(providers[index].provide); expect(value[2][1]).toBe(providers[index].useFactory); }); }); }); describe('useValue', () => { it('registers provider using string token', () => { const providers = [{provide: 'useValueTestService', useValue: (...args) => new TestService(args)}]; registerNgModule(moduleName, [], [], providers); const invokeQueue = angular.module(moduleName)['_invokeQueue']; expect(invokeQueue.length).toEqual(providers.length); invokeQueue.forEach((value: any, index: number) => { expect(value[0]).toEqual('$provide'); expect(value[1]).toEqual('constant'); expect(value[2][0]).toEqual(providers[index].provide); expect(value[2][1]).toEqual(providers[index].useValue); }); }); }); }); describe('@Pipe', () => { const name = 'formatDateTime'; describe('without injection', () => { @Pipe({ name }) class FormatDateTimeFilter implements PipeTransform { public transform(input: number): string { return new Date(input).toLocaleString(); } } it('registers as filter', () => { registerNgModule(moduleName, [], [ FormatDateTimeFilter ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; expect(invokeQueue.length).toEqual(1); expect(invokeQueue[0][0]).toEqual('$filterProvider'); expect(invokeQueue[0][1]).toEqual('register'); expect(invokeQueue[0][2][0]).toEqual(name); expect(invokeQueue[0][2][1].$inject).toEqual(['$injector']); }); }); describe('with injection', () => { @Pipe({ name }) class FormatDateTimeFilter implements PipeTransform { constructor($timeout: any) {} public transform(input: number): string { return new Date(input).toLocaleString(); } } FormatDateTimeFilter.$inject = ['$timeout']; it('registers as filter', () => { registerNgModule(moduleName, [], [ FormatDateTimeFilter ]); const invokeQueue = angular.module(moduleName)['_invokeQueue']; expect(invokeQueue.length).toEqual(1); expect(invokeQueue[0][0]).toEqual('$filterProvider'); expect(invokeQueue[0][1]).toEqual('register'); expect(invokeQueue[0][2][0]).toEqual(name); expect(invokeQueue[0][2][1].$inject).toEqual(['$injector', '$timeout']); }); }); }); });
the_stack
import {DraftBotReactionMessage} from "./DraftBotReactionMessage"; import {DraftBotReaction} from "./DraftBotReaction"; import {TranslationModule, Translations} from "../Translations"; import {Constants} from "../Constants"; import {User} from "discord.js"; import {DraftBotErrorEmbed} from "./DraftBotErrorEmbed"; import {DraftBotValidateReactionMessage} from "./DraftBotValidateReactionMessage"; declare function format(s: string, replacement: any): string; declare const Entities: any; /** * Reasons when the shop ends */ export enum ShopEndReason { /** * The player didn't react and the collector ends */ TIME, /** * The player reacted with cancel */ REACTION, /** * The player tried to buy something but he doesn't have enough money */ NOT_ENOUGH_MONEY, /** * The player tried to buy something but at the last moment chose to cancel */ REFUSED_CONFIRMATION, /** * The player bought an item successfully */ SUCCESS } export class DraftBotShopMessage extends DraftBotReactionMessage { private readonly _getUserMoney: (userId: string) => Promise<number>; private readonly _user: User; private readonly _removeUserMoney: (userId: string, amount: number) => Promise<void>; private readonly _shopEndCallback: (message: DraftBotShopMessage, reason: ShopEndReason) => void; private readonly _shopItems: ShopItem[]; private readonly _shopItemReactions: string[]; private readonly _language: string; private readonly _translationModule: TranslationModule; /** * Default constructor * @param shopItemCategories * @param language * @param title * @param user * @param currentMoney * @param getUserMoney * @param removeUserMoney * @param shopEndCallback */ // eslint-disable-next-line max-params constructor( shopItemCategories: ShopItemCategory[], language: string, title: string, user: User, currentMoney: number, getUserMoney: (userId: string) => Promise<number>, removeUserMoney: (userId: string, amount: number) => Promise<void>, shopEndCallback: (message: DraftBotShopMessage, reason: ShopEndReason) => void ) { const translationModule = Translations.getModule("commands.shop", language); const reactions: DraftBotReaction[] = []; const shopItems: ShopItem[] = []; const shopItemReactions: string[] = []; let content = ""; for (const shopItemCategory of shopItemCategories) { content += "**" + shopItemCategory.categoryTitle + (language === "en" ? "" : " ") + ":**\n"; for (const shopItem of shopItemCategory.items) { content += format(translationModule.get("display"), { emote: shopItem.emote, name: shopItem.name, price: shopItem.price }) + "\n"; const emoji = shopItem.emote.includes("<") ? shopItem.emote.split(":")[2].replace(">", "") : shopItem.emote; reactions.push(new DraftBotReaction(emoji)); shopItems.push(shopItem); shopItemReactions.push(shopItem.emote); } content += "\n"; } reactions.push(new DraftBotReaction(Constants.REACTIONS.REFUSE_REACTION)); content += format(translationModule.get("moneyQuantity"), { money: currentMoney }); super( reactions, [user.id], DraftBotShopMessage.shopCallback, 0, false, 0 ); this.setTitle(title); this.setDescription(content); this._getUserMoney = getUserMoney; this._user = user; this._removeUserMoney = removeUserMoney; this._shopEndCallback = shopEndCallback; this._shopItems = shopItems; this._shopItemReactions = shopItemReactions; this._language = language; this._translationModule = translationModule; } private async getUserMoney(): Promise<number> { return await this._getUserMoney(this._user.id); } private getChoseShopItem(): ShopItem { // eslint-disable-next-line max-len const emoji = this.getFirstReaction() ? this.getFirstReaction().emoji.id === null ? this.getFirstReaction().emoji.name : "<:" + this.getFirstReaction().emoji.name + ":" + this.getFirstReaction().emoji.id + ">" : null; const index: number = this._shopItemReactions.indexOf(emoji); if (index === -1) { return null; } return this._shopItems[index]; } private async removeUserMoney(amount: number): Promise<void> { return await this._removeUserMoney(this._user.id, amount); } get user(): User { return this._user; } get language(): string { return this._language; } private static async shopCallback(msg: DraftBotReactionMessage): Promise<void> { const shopMessage = msg as DraftBotShopMessage; const choseShopItem = shopMessage.getChoseShopItem(); if (choseShopItem) { const userMoney = await shopMessage.getUserMoney(); if (userMoney < choseShopItem.price) { await shopMessage.sentMessage.channel.send({ embeds: [ new DraftBotErrorEmbed( shopMessage._user, shopMessage._language, format( shopMessage._translationModule.get("error.cannotBuy"), { missingMoney: choseShopItem.price - userMoney } ) )] } ); shopMessage._shopEndCallback(shopMessage, ShopEndReason.NOT_ENOUGH_MONEY); } else if (choseShopItem.amounts.length === 1 && choseShopItem.amounts[0] === 1) { const confirmBuyMessage = await new DraftBotValidateReactionMessage( shopMessage._user, async (reactionMessage) => { const validateMessage = reactionMessage as DraftBotValidateReactionMessage; if (validateMessage.isValidated()) { shopMessage._shopEndCallback(shopMessage, ShopEndReason.SUCCESS); const removeMoney = await choseShopItem.buyCallback(shopMessage, 1); if (removeMoney) { await shopMessage.removeUserMoney(choseShopItem.price); } } else { await shopMessage.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( shopMessage.user, shopMessage.language, shopMessage._translationModule.get("error.canceledPurchase"), true )] }); shopMessage._shopEndCallback(shopMessage, ShopEndReason.REFUSED_CONFIRMATION); } } ); confirmBuyMessage.formatAuthor(shopMessage._translationModule.get("confirm"), shopMessage._user); confirmBuyMessage.setDescription(format(shopMessage._translationModule.get("display"), { emote: choseShopItem.emote, name: choseShopItem.name, price: choseShopItem.price }) + "\n\n" + Constants.REACTIONS.WARNING + " " + choseShopItem.description); confirmBuyMessage.send(shopMessage.sentMessage.channel); } else { const numberReactions: DraftBotReaction[] = []; const prices: number[] = []; for (let i = 0; i < choseShopItem.amounts.length; ++i) { const amount = choseShopItem.amounts[i]; const numberEmote: string = Constants.REACTIONS.NUMBERS[amount]; if (amount < 0 || amount > 10 || choseShopItem.amounts.indexOf(amount) < i || userMoney < amount * choseShopItem.price) { continue; } numberReactions.push(new DraftBotReaction(numberEmote, async (reactionMessage: DraftBotReactionMessage) => { shopMessage._shopEndCallback(shopMessage, ShopEndReason.SUCCESS); const removeMoney = await choseShopItem.buyCallback(shopMessage, amount); if (removeMoney) { await shopMessage.removeUserMoney(choseShopItem.price * amount); } reactionMessage.stop(); })); prices.push(amount * choseShopItem.price); } numberReactions.push(new DraftBotReaction( Constants.REACTIONS.REFUSE_REACTION, async (reactionMessage: DraftBotReactionMessage) => { reactionMessage.stop(); await shopMessage.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( shopMessage.user, shopMessage.language, shopMessage._translationModule.get("error.canceledPurchase"), true )] }); shopMessage._shopEndCallback(shopMessage, ShopEndReason.REFUSED_CONFIRMATION); } )); const confirmBuyMessage = await new DraftBotReactionMessage( numberReactions, [shopMessage.user.id], null, 0, false, 0 ); confirmBuyMessage.formatAuthor(shopMessage._translationModule.get("confirm"), shopMessage._user); let desc = format(shopMessage._translationModule.get("multipleChoice.display"), { emote: choseShopItem.emote, name: choseShopItem.name }); for (const price of prices) { desc += format(shopMessage._translationModule.get("multipleChoice.priceDisplay"), { price: price }); } desc += "\n\n" + choseShopItem.description + "\n\n" + Constants.REACTIONS.WARNING + " " + shopMessage._translationModule.get("multipleChoice.warning"); confirmBuyMessage.setDescription(desc); confirmBuyMessage.send(shopMessage.sentMessage.channel); } } else { await shopMessage.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( shopMessage.user, shopMessage.language, shopMessage._translationModule.get("error.leaveShop"), true )] }); if (msg.getFirstReaction()) { shopMessage._shopEndCallback(shopMessage, ShopEndReason.REACTION); } else { shopMessage._shopEndCallback(shopMessage, ShopEndReason.TIME); } } } } /** * Builder for a shop */ export class DraftBotShopMessageBuilder { private _shopItemCategories: ShopItemCategory[] = []; private readonly _user: User; private readonly _title: string; private readonly _language: string; private _getUserMoney: (userId: string) => Promise<number> = async (userId) => (await Entities.getOrRegister(userId))[0].Player.money; private _removeUserMoney: (userId: string, amount: number) => Promise<void> = async (userId, amount) => { const player = (await Entities.getOrRegister(userId))[0].Player; player.money -= amount; await player.save(); }; private _shopEndCallback: (message: DraftBotShopMessage, reason: ShopEndReason) => void = () => { /* do nothing */ }; private _noShoppingCart = false; /** * Default constructor * @param user The user of the shop * @param title The title of the shop * @param language The language of the shop */ constructor( user: User, title: string, language: string ) { this._user = user; this._title = title; this._language = language; } /** * Add a shop category * @param category */ addCategory(category: ShopItemCategory): DraftBotShopMessageBuilder { if (!category || category.items.length === 0 || category.items.filter(item => item !== null && item !== undefined).length === 0) { return this; } this._shopItemCategories.push(category); return this; } /** * Remove the shopping cart icon before the title of the shop */ noShoppingCart(): DraftBotShopMessageBuilder { this._noShoppingCart = true; return this; } /** * The callback called when the shp ends * @param callback */ endCallback(callback: (message: DraftBotShopMessage, reason: ShopEndReason) => void): DraftBotShopMessageBuilder { this._shopEndCallback = callback; return this; } /** * Set the function which get the money from the player * To be used in the case the money is not the base game money (ex: points) * It MUST query the player from the database or whatever each time this function is called in order to prevent problems of concurrent modifications * @param getUserMoney */ setGetUserMoney(getUserMoney: (userId: string) => Promise<number>): DraftBotShopMessageBuilder { this._getUserMoney = getUserMoney; return this; } /** * Set the function which removes money from the player * To be used in the case the money is not the base game money (ex: points) * It MUST query the player from the database or whatever each time this function is called in order to prevent problems of concurrent modifications * @param removeUserMoney */ setRemoveUserMoney(removeUserMoney: (userId: string, amount: number) => Promise<void>): DraftBotShopMessageBuilder { this._removeUserMoney = removeUserMoney; return this; } /** * Build the shop message */ async build(): Promise<DraftBotShopMessage> { return new DraftBotShopMessage( this._shopItemCategories, this._language, (this._noShoppingCart ? this._title : Constants.REACTIONS.SHOPPING_CART + " " + this._title) + (this._language === "en" ? "" : " ") + ":", this._user, await this._getUserMoney(this._user.id), this._getUserMoney, this._removeUserMoney, this._shopEndCallback ); } } /** * An item in the shop */ export class ShopItem { private readonly _emote: string; private readonly _name: string; private readonly _price: number; private readonly _buyCallback: (message: DraftBotShopMessage, amount: number) => Promise<boolean>; private readonly _description: string; private readonly _amounts: number[]; /** * Default constructor * @param emote The emote of the shop item * @param name The name of the shop item * @param price The price of the shop item (for x1) * @param description The description of the shop item * @param buyCallback The callback called when this item is try to be bought * It must return false if the purchase failed in order not to remove money from the player, and true if bought with success * @param amounts The possible amounts for this item */ constructor(emote: string, name: string, price: number, description: string, buyCallback: (message: DraftBotShopMessage, amount: number) => Promise<boolean>, amounts = [1]) { this._emote = emote; this._name = name; this._price = price; this._buyCallback = buyCallback; this._description = description; this._amounts = amounts; } get emote(): string { return this._emote; } get name(): string { return this._name; } get price(): number { return this._price; } get buyCallback(): (message: DraftBotShopMessage, amount: number) => Promise<boolean> { return this._buyCallback; } get description(): string { return this._description; } get amounts(): number[] { return this._amounts; } } /** * A category of the shop */ export class ShopItemCategory { private readonly _items: ShopItem[]; private readonly _categoryTitle: string; /** * Default constructor * @param items The items in the category * @param categoryTitle The title of the category */ constructor(items: ShopItem[], categoryTitle: string) { this._items = items; this._categoryTitle = categoryTitle; } get items(): ShopItem[] { return this._items; } get categoryTitle(): string { return this._categoryTitle; } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class WellArchitected extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: WellArchitected.Types.ClientConfiguration) config: Config & WellArchitected.Types.ClientConfiguration; /** * Associate a lens to a workload. */ associateLenses(params: WellArchitected.Types.AssociateLensesInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Associate a lens to a workload. */ associateLenses(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Create a milestone for an existing workload. */ createMilestone(params: WellArchitected.Types.CreateMilestoneInput, callback?: (err: AWSError, data: WellArchitected.Types.CreateMilestoneOutput) => void): Request<WellArchitected.Types.CreateMilestoneOutput, AWSError>; /** * Create a milestone for an existing workload. */ createMilestone(callback?: (err: AWSError, data: WellArchitected.Types.CreateMilestoneOutput) => void): Request<WellArchitected.Types.CreateMilestoneOutput, AWSError>; /** * Create a new workload. The owner of a workload can share the workload with other AWS accounts and IAM users in the same AWS Region. Only the owner of a workload can delete it. For more information, see Defining a Workload in the AWS Well-Architected Tool User Guide. */ createWorkload(params: WellArchitected.Types.CreateWorkloadInput, callback?: (err: AWSError, data: WellArchitected.Types.CreateWorkloadOutput) => void): Request<WellArchitected.Types.CreateWorkloadOutput, AWSError>; /** * Create a new workload. The owner of a workload can share the workload with other AWS accounts and IAM users in the same AWS Region. Only the owner of a workload can delete it. For more information, see Defining a Workload in the AWS Well-Architected Tool User Guide. */ createWorkload(callback?: (err: AWSError, data: WellArchitected.Types.CreateWorkloadOutput) => void): Request<WellArchitected.Types.CreateWorkloadOutput, AWSError>; /** * Create a workload share. The owner of a workload can share it with other AWS accounts and IAM users in the same AWS Region. Shared access to a workload is not removed until the workload invitation is deleted. For more information, see Sharing a Workload in the AWS Well-Architected Tool User Guide. */ createWorkloadShare(params: WellArchitected.Types.CreateWorkloadShareInput, callback?: (err: AWSError, data: WellArchitected.Types.CreateWorkloadShareOutput) => void): Request<WellArchitected.Types.CreateWorkloadShareOutput, AWSError>; /** * Create a workload share. The owner of a workload can share it with other AWS accounts and IAM users in the same AWS Region. Shared access to a workload is not removed until the workload invitation is deleted. For more information, see Sharing a Workload in the AWS Well-Architected Tool User Guide. */ createWorkloadShare(callback?: (err: AWSError, data: WellArchitected.Types.CreateWorkloadShareOutput) => void): Request<WellArchitected.Types.CreateWorkloadShareOutput, AWSError>; /** * Delete an existing workload. */ deleteWorkload(params: WellArchitected.Types.DeleteWorkloadInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Delete an existing workload. */ deleteWorkload(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Delete a workload share. */ deleteWorkloadShare(params: WellArchitected.Types.DeleteWorkloadShareInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Delete a workload share. */ deleteWorkloadShare(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Disassociate a lens from a workload. The AWS Well-Architected Framework lens (wellarchitected) cannot be removed from a workload. */ disassociateLenses(params: WellArchitected.Types.DisassociateLensesInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Disassociate a lens from a workload. The AWS Well-Architected Framework lens (wellarchitected) cannot be removed from a workload. */ disassociateLenses(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Get the answer to a specific question in a workload review. */ getAnswer(params: WellArchitected.Types.GetAnswerInput, callback?: (err: AWSError, data: WellArchitected.Types.GetAnswerOutput) => void): Request<WellArchitected.Types.GetAnswerOutput, AWSError>; /** * Get the answer to a specific question in a workload review. */ getAnswer(callback?: (err: AWSError, data: WellArchitected.Types.GetAnswerOutput) => void): Request<WellArchitected.Types.GetAnswerOutput, AWSError>; /** * Get lens review. */ getLensReview(params: WellArchitected.Types.GetLensReviewInput, callback?: (err: AWSError, data: WellArchitected.Types.GetLensReviewOutput) => void): Request<WellArchitected.Types.GetLensReviewOutput, AWSError>; /** * Get lens review. */ getLensReview(callback?: (err: AWSError, data: WellArchitected.Types.GetLensReviewOutput) => void): Request<WellArchitected.Types.GetLensReviewOutput, AWSError>; /** * Get lens review report. */ getLensReviewReport(params: WellArchitected.Types.GetLensReviewReportInput, callback?: (err: AWSError, data: WellArchitected.Types.GetLensReviewReportOutput) => void): Request<WellArchitected.Types.GetLensReviewReportOutput, AWSError>; /** * Get lens review report. */ getLensReviewReport(callback?: (err: AWSError, data: WellArchitected.Types.GetLensReviewReportOutput) => void): Request<WellArchitected.Types.GetLensReviewReportOutput, AWSError>; /** * Get lens version differences. */ getLensVersionDifference(params: WellArchitected.Types.GetLensVersionDifferenceInput, callback?: (err: AWSError, data: WellArchitected.Types.GetLensVersionDifferenceOutput) => void): Request<WellArchitected.Types.GetLensVersionDifferenceOutput, AWSError>; /** * Get lens version differences. */ getLensVersionDifference(callback?: (err: AWSError, data: WellArchitected.Types.GetLensVersionDifferenceOutput) => void): Request<WellArchitected.Types.GetLensVersionDifferenceOutput, AWSError>; /** * Get a milestone for an existing workload. */ getMilestone(params: WellArchitected.Types.GetMilestoneInput, callback?: (err: AWSError, data: WellArchitected.Types.GetMilestoneOutput) => void): Request<WellArchitected.Types.GetMilestoneOutput, AWSError>; /** * Get a milestone for an existing workload. */ getMilestone(callback?: (err: AWSError, data: WellArchitected.Types.GetMilestoneOutput) => void): Request<WellArchitected.Types.GetMilestoneOutput, AWSError>; /** * Get an existing workload. */ getWorkload(params: WellArchitected.Types.GetWorkloadInput, callback?: (err: AWSError, data: WellArchitected.Types.GetWorkloadOutput) => void): Request<WellArchitected.Types.GetWorkloadOutput, AWSError>; /** * Get an existing workload. */ getWorkload(callback?: (err: AWSError, data: WellArchitected.Types.GetWorkloadOutput) => void): Request<WellArchitected.Types.GetWorkloadOutput, AWSError>; /** * List of answers. */ listAnswers(params: WellArchitected.Types.ListAnswersInput, callback?: (err: AWSError, data: WellArchitected.Types.ListAnswersOutput) => void): Request<WellArchitected.Types.ListAnswersOutput, AWSError>; /** * List of answers. */ listAnswers(callback?: (err: AWSError, data: WellArchitected.Types.ListAnswersOutput) => void): Request<WellArchitected.Types.ListAnswersOutput, AWSError>; /** * List lens review improvements. */ listLensReviewImprovements(params: WellArchitected.Types.ListLensReviewImprovementsInput, callback?: (err: AWSError, data: WellArchitected.Types.ListLensReviewImprovementsOutput) => void): Request<WellArchitected.Types.ListLensReviewImprovementsOutput, AWSError>; /** * List lens review improvements. */ listLensReviewImprovements(callback?: (err: AWSError, data: WellArchitected.Types.ListLensReviewImprovementsOutput) => void): Request<WellArchitected.Types.ListLensReviewImprovementsOutput, AWSError>; /** * List lens reviews. */ listLensReviews(params: WellArchitected.Types.ListLensReviewsInput, callback?: (err: AWSError, data: WellArchitected.Types.ListLensReviewsOutput) => void): Request<WellArchitected.Types.ListLensReviewsOutput, AWSError>; /** * List lens reviews. */ listLensReviews(callback?: (err: AWSError, data: WellArchitected.Types.ListLensReviewsOutput) => void): Request<WellArchitected.Types.ListLensReviewsOutput, AWSError>; /** * List the available lenses. */ listLenses(params: WellArchitected.Types.ListLensesInput, callback?: (err: AWSError, data: WellArchitected.Types.ListLensesOutput) => void): Request<WellArchitected.Types.ListLensesOutput, AWSError>; /** * List the available lenses. */ listLenses(callback?: (err: AWSError, data: WellArchitected.Types.ListLensesOutput) => void): Request<WellArchitected.Types.ListLensesOutput, AWSError>; /** * List all milestones for an existing workload. */ listMilestones(params: WellArchitected.Types.ListMilestonesInput, callback?: (err: AWSError, data: WellArchitected.Types.ListMilestonesOutput) => void): Request<WellArchitected.Types.ListMilestonesOutput, AWSError>; /** * List all milestones for an existing workload. */ listMilestones(callback?: (err: AWSError, data: WellArchitected.Types.ListMilestonesOutput) => void): Request<WellArchitected.Types.ListMilestonesOutput, AWSError>; /** * List lens notifications. */ listNotifications(params: WellArchitected.Types.ListNotificationsInput, callback?: (err: AWSError, data: WellArchitected.Types.ListNotificationsOutput) => void): Request<WellArchitected.Types.ListNotificationsOutput, AWSError>; /** * List lens notifications. */ listNotifications(callback?: (err: AWSError, data: WellArchitected.Types.ListNotificationsOutput) => void): Request<WellArchitected.Types.ListNotificationsOutput, AWSError>; /** * List the workload invitations. */ listShareInvitations(params: WellArchitected.Types.ListShareInvitationsInput, callback?: (err: AWSError, data: WellArchitected.Types.ListShareInvitationsOutput) => void): Request<WellArchitected.Types.ListShareInvitationsOutput, AWSError>; /** * List the workload invitations. */ listShareInvitations(callback?: (err: AWSError, data: WellArchitected.Types.ListShareInvitationsOutput) => void): Request<WellArchitected.Types.ListShareInvitationsOutput, AWSError>; /** * List the tags for a resource. */ listTagsForResource(params: WellArchitected.Types.ListTagsForResourceInput, callback?: (err: AWSError, data: WellArchitected.Types.ListTagsForResourceOutput) => void): Request<WellArchitected.Types.ListTagsForResourceOutput, AWSError>; /** * List the tags for a resource. */ listTagsForResource(callback?: (err: AWSError, data: WellArchitected.Types.ListTagsForResourceOutput) => void): Request<WellArchitected.Types.ListTagsForResourceOutput, AWSError>; /** * List the workload shares associated with the workload. */ listWorkloadShares(params: WellArchitected.Types.ListWorkloadSharesInput, callback?: (err: AWSError, data: WellArchitected.Types.ListWorkloadSharesOutput) => void): Request<WellArchitected.Types.ListWorkloadSharesOutput, AWSError>; /** * List the workload shares associated with the workload. */ listWorkloadShares(callback?: (err: AWSError, data: WellArchitected.Types.ListWorkloadSharesOutput) => void): Request<WellArchitected.Types.ListWorkloadSharesOutput, AWSError>; /** * List workloads. Paginated. */ listWorkloads(params: WellArchitected.Types.ListWorkloadsInput, callback?: (err: AWSError, data: WellArchitected.Types.ListWorkloadsOutput) => void): Request<WellArchitected.Types.ListWorkloadsOutput, AWSError>; /** * List workloads. Paginated. */ listWorkloads(callback?: (err: AWSError, data: WellArchitected.Types.ListWorkloadsOutput) => void): Request<WellArchitected.Types.ListWorkloadsOutput, AWSError>; /** * Adds one or more tags to the specified resource. */ tagResource(params: WellArchitected.Types.TagResourceInput, callback?: (err: AWSError, data: WellArchitected.Types.TagResourceOutput) => void): Request<WellArchitected.Types.TagResourceOutput, AWSError>; /** * Adds one or more tags to the specified resource. */ tagResource(callback?: (err: AWSError, data: WellArchitected.Types.TagResourceOutput) => void): Request<WellArchitected.Types.TagResourceOutput, AWSError>; /** * Deletes specified tags from a resource. To specify multiple tags, use separate tagKeys parameters, for example: DELETE /tags/WorkloadArn?tagKeys=key1&amp;tagKeys=key2 */ untagResource(params: WellArchitected.Types.UntagResourceInput, callback?: (err: AWSError, data: WellArchitected.Types.UntagResourceOutput) => void): Request<WellArchitected.Types.UntagResourceOutput, AWSError>; /** * Deletes specified tags from a resource. To specify multiple tags, use separate tagKeys parameters, for example: DELETE /tags/WorkloadArn?tagKeys=key1&amp;tagKeys=key2 */ untagResource(callback?: (err: AWSError, data: WellArchitected.Types.UntagResourceOutput) => void): Request<WellArchitected.Types.UntagResourceOutput, AWSError>; /** * Update the answer to a specific question in a workload review. */ updateAnswer(params: WellArchitected.Types.UpdateAnswerInput, callback?: (err: AWSError, data: WellArchitected.Types.UpdateAnswerOutput) => void): Request<WellArchitected.Types.UpdateAnswerOutput, AWSError>; /** * Update the answer to a specific question in a workload review. */ updateAnswer(callback?: (err: AWSError, data: WellArchitected.Types.UpdateAnswerOutput) => void): Request<WellArchitected.Types.UpdateAnswerOutput, AWSError>; /** * Update lens review. */ updateLensReview(params: WellArchitected.Types.UpdateLensReviewInput, callback?: (err: AWSError, data: WellArchitected.Types.UpdateLensReviewOutput) => void): Request<WellArchitected.Types.UpdateLensReviewOutput, AWSError>; /** * Update lens review. */ updateLensReview(callback?: (err: AWSError, data: WellArchitected.Types.UpdateLensReviewOutput) => void): Request<WellArchitected.Types.UpdateLensReviewOutput, AWSError>; /** * Update a workload invitation. */ updateShareInvitation(params: WellArchitected.Types.UpdateShareInvitationInput, callback?: (err: AWSError, data: WellArchitected.Types.UpdateShareInvitationOutput) => void): Request<WellArchitected.Types.UpdateShareInvitationOutput, AWSError>; /** * Update a workload invitation. */ updateShareInvitation(callback?: (err: AWSError, data: WellArchitected.Types.UpdateShareInvitationOutput) => void): Request<WellArchitected.Types.UpdateShareInvitationOutput, AWSError>; /** * Update an existing workload. */ updateWorkload(params: WellArchitected.Types.UpdateWorkloadInput, callback?: (err: AWSError, data: WellArchitected.Types.UpdateWorkloadOutput) => void): Request<WellArchitected.Types.UpdateWorkloadOutput, AWSError>; /** * Update an existing workload. */ updateWorkload(callback?: (err: AWSError, data: WellArchitected.Types.UpdateWorkloadOutput) => void): Request<WellArchitected.Types.UpdateWorkloadOutput, AWSError>; /** * Update a workload share. */ updateWorkloadShare(params: WellArchitected.Types.UpdateWorkloadShareInput, callback?: (err: AWSError, data: WellArchitected.Types.UpdateWorkloadShareOutput) => void): Request<WellArchitected.Types.UpdateWorkloadShareOutput, AWSError>; /** * Update a workload share. */ updateWorkloadShare(callback?: (err: AWSError, data: WellArchitected.Types.UpdateWorkloadShareOutput) => void): Request<WellArchitected.Types.UpdateWorkloadShareOutput, AWSError>; /** * Upgrade lens review. */ upgradeLensReview(params: WellArchitected.Types.UpgradeLensReviewInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Upgrade lens review. */ upgradeLensReview(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; } declare namespace WellArchitected { export interface Answer { QuestionId?: QuestionId; PillarId?: PillarId; QuestionTitle?: QuestionTitle; QuestionDescription?: QuestionDescription; ImprovementPlanUrl?: ImprovementPlanUrl; HelpfulResourceUrl?: HelpfulResourceUrl; Choices?: Choices; SelectedChoices?: SelectedChoices; /** * A list of selected choices to a question in your workload. */ ChoiceAnswers?: ChoiceAnswers; IsApplicable?: IsApplicable; Risk?: Risk; Notes?: Notes; /** * The reason why the question is not applicable to your workload. */ Reason?: AnswerReason; } export type AnswerReason = "OUT_OF_SCOPE"|"BUSINESS_PRIORITIES"|"ARCHITECTURE_CONSTRAINTS"|"OTHER"|"NONE"|string; export type AnswerSummaries = AnswerSummary[]; export interface AnswerSummary { QuestionId?: QuestionId; PillarId?: PillarId; QuestionTitle?: QuestionTitle; Choices?: Choices; SelectedChoices?: SelectedChoices; /** * A list of selected choices to a question in your workload. */ ChoiceAnswerSummaries?: ChoiceAnswerSummaries; IsApplicable?: IsApplicable; Risk?: Risk; /** * The reason why a choice is non-applicable to a question in your workload. */ Reason?: AnswerReason; } export interface AssociateLensesInput { WorkloadId: WorkloadId; LensAliases: LensAliases; } export type AwsAccountId = string; export type AwsRegion = string; export type Base64String = string; export interface Choice { ChoiceId?: ChoiceId; Title?: ChoiceTitle; Description?: ChoiceDescription; } export interface ChoiceAnswer { ChoiceId?: ChoiceId; /** * The status of a choice. */ Status?: ChoiceStatus; /** * The reason why a choice is non-applicable to a question in your workload. */ Reason?: ChoiceReason; /** * The notes associated with a choice. */ Notes?: ChoiceNotes; } export type ChoiceAnswerSummaries = ChoiceAnswerSummary[]; export interface ChoiceAnswerSummary { ChoiceId?: ChoiceId; /** * The status of a choice. */ Status?: ChoiceStatus; /** * The reason why a choice is non-applicable to a question in your workload. */ Reason?: ChoiceReason; } export type ChoiceAnswers = ChoiceAnswer[]; export type ChoiceDescription = string; export type ChoiceId = string; export type ChoiceNotes = string; export type ChoiceReason = "OUT_OF_SCOPE"|"BUSINESS_PRIORITIES"|"ARCHITECTURE_CONSTRAINTS"|"OTHER"|"NONE"|string; export type ChoiceStatus = "SELECTED"|"NOT_APPLICABLE"|"UNSELECTED"|string; export type ChoiceTitle = string; export interface ChoiceUpdate { /** * The status of a choice. */ Status: ChoiceStatus; /** * The reason why a choice is non-applicable to a question in your workload. */ Reason?: ChoiceReason; /** * The notes associated with a choice. */ Notes?: ChoiceNotes; } export type ChoiceUpdates = {[key: string]: ChoiceUpdate}; export type Choices = Choice[]; export type ClientRequestToken = string; export type Count = number; export interface CreateMilestoneInput { WorkloadId: WorkloadId; MilestoneName: MilestoneName; ClientRequestToken: ClientRequestToken; } export interface CreateMilestoneOutput { WorkloadId?: WorkloadId; MilestoneNumber?: MilestoneNumber; } export interface CreateWorkloadInput { WorkloadName: WorkloadName; Description: WorkloadDescription; Environment: WorkloadEnvironment; AccountIds?: WorkloadAccountIds; AwsRegions?: WorkloadAwsRegions; NonAwsRegions?: WorkloadNonAwsRegions; PillarPriorities?: WorkloadPillarPriorities; ArchitecturalDesign?: WorkloadArchitecturalDesign; ReviewOwner: WorkloadReviewOwner; IndustryType?: WorkloadIndustryType; Industry?: WorkloadIndustry; Lenses: WorkloadLenses; Notes?: Notes; ClientRequestToken: ClientRequestToken; /** * The tags to be associated with the workload. */ Tags?: TagMap; } export interface CreateWorkloadOutput { WorkloadId?: WorkloadId; WorkloadArn?: WorkloadArn; } export interface CreateWorkloadShareInput { WorkloadId: WorkloadId; SharedWith: SharedWith; PermissionType: PermissionType; ClientRequestToken: ClientRequestToken; } export interface CreateWorkloadShareOutput { WorkloadId?: WorkloadId; ShareId?: ShareId; } export interface DeleteWorkloadInput { WorkloadId: WorkloadId; ClientRequestToken: ClientRequestToken; } export interface DeleteWorkloadShareInput { ShareId: ShareId; WorkloadId: WorkloadId; ClientRequestToken: ClientRequestToken; } export type DifferenceStatus = "UPDATED"|"NEW"|"DELETED"|string; export interface DisassociateLensesInput { WorkloadId: WorkloadId; LensAliases: LensAliases; } export interface GetAnswerInput { WorkloadId: WorkloadId; LensAlias: LensAlias; QuestionId: QuestionId; MilestoneNumber?: MilestoneNumber; } export interface GetAnswerOutput { WorkloadId?: WorkloadId; MilestoneNumber?: MilestoneNumber; LensAlias?: LensAlias; Answer?: Answer; } export interface GetLensReviewInput { WorkloadId: WorkloadId; LensAlias: LensAlias; MilestoneNumber?: MilestoneNumber; } export interface GetLensReviewOutput { WorkloadId?: WorkloadId; MilestoneNumber?: MilestoneNumber; LensReview?: LensReview; } export interface GetLensReviewReportInput { WorkloadId: WorkloadId; LensAlias: LensAlias; MilestoneNumber?: MilestoneNumber; } export interface GetLensReviewReportOutput { WorkloadId?: WorkloadId; MilestoneNumber?: MilestoneNumber; LensReviewReport?: LensReviewReport; } export interface GetLensVersionDifferenceInput { LensAlias: LensAlias; /** * The base version of the lens. */ BaseLensVersion: LensVersion; } export interface GetLensVersionDifferenceOutput { LensAlias?: LensAlias; /** * The base version of the lens. */ BaseLensVersion?: LensVersion; /** * The latest version of the lens. */ LatestLensVersion?: LensVersion; VersionDifferences?: VersionDifferences; } export interface GetMilestoneInput { WorkloadId: WorkloadId; MilestoneNumber: MilestoneNumber; } export interface GetMilestoneOutput { WorkloadId?: WorkloadId; Milestone?: Milestone; } export interface GetWorkloadInput { WorkloadId: WorkloadId; } export interface GetWorkloadOutput { Workload?: Workload; } export type HelpfulResourceUrl = string; export type ImprovementPlanUrl = string; export type ImprovementSummaries = ImprovementSummary[]; export interface ImprovementSummary { QuestionId?: QuestionId; PillarId?: PillarId; QuestionTitle?: QuestionTitle; Risk?: Risk; ImprovementPlanUrl?: ImprovementPlanUrl; } export type IsApplicable = boolean; export type IsReviewOwnerUpdateAcknowledged = boolean; export type LensAlias = string; export type LensAliases = LensAlias[]; export type LensDescription = string; export type LensName = string; export interface LensReview { LensAlias?: LensAlias; /** * The version of the lens. */ LensVersion?: LensVersion; LensName?: LensName; /** * The status of the lens. */ LensStatus?: LensStatus; PillarReviewSummaries?: PillarReviewSummaries; UpdatedAt?: Timestamp; Notes?: Notes; RiskCounts?: RiskCounts; NextToken?: NextToken; } export interface LensReviewReport { LensAlias?: LensAlias; Base64String?: Base64String; } export type LensReviewSummaries = LensReviewSummary[]; export interface LensReviewSummary { LensAlias?: LensAlias; /** * The version of the lens. */ LensVersion?: LensVersion; LensName?: LensName; /** * The status of the lens. */ LensStatus?: LensStatus; UpdatedAt?: Timestamp; RiskCounts?: RiskCounts; } export type LensStatus = "CURRENT"|"NOT_CURRENT"|"DEPRECATED"|string; export type LensSummaries = LensSummary[]; export interface LensSummary { LensAlias?: LensAlias; /** * The version of the lens. */ LensVersion?: LensVersion; LensName?: LensName; Description?: LensDescription; } export interface LensUpgradeSummary { WorkloadId?: WorkloadId; WorkloadName?: WorkloadName; LensAlias?: LensAlias; /** * The current version of the lens. */ CurrentLensVersion?: LensVersion; /** * The latest version of the lens. */ LatestLensVersion?: LensVersion; } export type LensVersion = string; export interface ListAnswersInput { WorkloadId: WorkloadId; LensAlias: LensAlias; PillarId?: PillarId; MilestoneNumber?: MilestoneNumber; NextToken?: NextToken; /** * The maximum number of results to return for this request. */ MaxResults?: ListAnswersMaxResults; } export type ListAnswersMaxResults = number; export interface ListAnswersOutput { WorkloadId?: WorkloadId; MilestoneNumber?: MilestoneNumber; LensAlias?: LensAlias; AnswerSummaries?: AnswerSummaries; NextToken?: NextToken; } export interface ListLensReviewImprovementsInput { WorkloadId: WorkloadId; LensAlias: LensAlias; PillarId?: PillarId; MilestoneNumber?: MilestoneNumber; NextToken?: NextToken; /** * The maximum number of results to return for this request. */ MaxResults?: ListLensReviewImprovementsMaxResults; } export type ListLensReviewImprovementsMaxResults = number; export interface ListLensReviewImprovementsOutput { WorkloadId?: WorkloadId; MilestoneNumber?: MilestoneNumber; LensAlias?: LensAlias; ImprovementSummaries?: ImprovementSummaries; NextToken?: NextToken; } export interface ListLensReviewsInput { WorkloadId: WorkloadId; MilestoneNumber?: MilestoneNumber; NextToken?: NextToken; MaxResults?: MaxResults; } export interface ListLensReviewsOutput { WorkloadId?: WorkloadId; MilestoneNumber?: MilestoneNumber; LensReviewSummaries?: LensReviewSummaries; NextToken?: NextToken; } export interface ListLensesInput { NextToken?: NextToken; MaxResults?: MaxResults; } export interface ListLensesOutput { LensSummaries?: LensSummaries; NextToken?: NextToken; } export interface ListMilestonesInput { WorkloadId: WorkloadId; NextToken?: NextToken; MaxResults?: MaxResults; } export interface ListMilestonesOutput { WorkloadId?: WorkloadId; MilestoneSummaries?: MilestoneSummaries; NextToken?: NextToken; } export interface ListNotificationsInput { WorkloadId?: WorkloadId; NextToken?: NextToken; /** * The maximum number of results to return for this request. */ MaxResults?: ListNotificationsMaxResults; } export type ListNotificationsMaxResults = number; export interface ListNotificationsOutput { /** * List of lens notification summaries in a workload. */ NotificationSummaries?: NotificationSummaries; NextToken?: NextToken; } export interface ListShareInvitationsInput { WorkloadNamePrefix?: WorkloadNamePrefix; NextToken?: NextToken; /** * The maximum number of results to return for this request. */ MaxResults?: ListShareInvitationsMaxResults; } export type ListShareInvitationsMaxResults = number; export interface ListShareInvitationsOutput { /** * List of share invitation summaries in a workload. */ ShareInvitationSummaries?: ShareInvitationSummaries; NextToken?: NextToken; } export interface ListTagsForResourceInput { WorkloadArn: WorkloadArn; } export interface ListTagsForResourceOutput { /** * The tags for the resource. */ Tags?: TagMap; } export interface ListWorkloadSharesInput { WorkloadId: WorkloadId; /** * The AWS account ID or IAM role with which the workload is shared. */ SharedWithPrefix?: SharedWithPrefix; NextToken?: NextToken; /** * The maximum number of results to return for this request. */ MaxResults?: ListWorkloadSharesMaxResults; } export type ListWorkloadSharesMaxResults = number; export interface ListWorkloadSharesOutput { WorkloadId?: WorkloadId; WorkloadShareSummaries?: WorkloadShareSummaries; NextToken?: NextToken; } export interface ListWorkloadsInput { WorkloadNamePrefix?: WorkloadNamePrefix; NextToken?: NextToken; /** * The maximum number of results to return for this request. */ MaxResults?: ListWorkloadsMaxResults; } export type ListWorkloadsMaxResults = number; export interface ListWorkloadsOutput { WorkloadSummaries?: WorkloadSummaries; NextToken?: NextToken; } export type MaxResults = number; export interface Milestone { MilestoneNumber?: MilestoneNumber; MilestoneName?: MilestoneName; RecordedAt?: Timestamp; Workload?: Workload; } export type MilestoneName = string; export type MilestoneNumber = number; export type MilestoneSummaries = MilestoneSummary[]; export interface MilestoneSummary { MilestoneNumber?: MilestoneNumber; MilestoneName?: MilestoneName; RecordedAt?: Timestamp; WorkloadSummary?: WorkloadSummary; } export type NextToken = string; export type Notes = string; export type NotificationSummaries = NotificationSummary[]; export interface NotificationSummary { /** * The type of notification. */ Type?: NotificationType; /** * Summary of lens upgrade. */ LensUpgradeSummary?: LensUpgradeSummary; } export type NotificationType = "LENS_VERSION_UPGRADED"|"LENS_VERSION_DEPRECATED"|string; export type PermissionType = "READONLY"|"CONTRIBUTOR"|string; export interface PillarDifference { PillarId?: PillarId; /** * Indicates the type of change to the pillar. */ DifferenceStatus?: DifferenceStatus; /** * List of question differences. */ QuestionDifferences?: QuestionDifferences; } export type PillarDifferences = PillarDifference[]; export type PillarId = string; export type PillarName = string; export type PillarNotes = {[key: string]: Notes}; export type PillarReviewSummaries = PillarReviewSummary[]; export interface PillarReviewSummary { PillarId?: PillarId; PillarName?: PillarName; Notes?: Notes; RiskCounts?: RiskCounts; } export type QuestionDescription = string; export interface QuestionDifference { QuestionId?: QuestionId; QuestionTitle?: QuestionTitle; /** * Indicates the type of change to the question. */ DifferenceStatus?: DifferenceStatus; } export type QuestionDifferences = QuestionDifference[]; export type QuestionId = string; export type QuestionTitle = string; export type Risk = "UNANSWERED"|"HIGH"|"MEDIUM"|"NONE"|"NOT_APPLICABLE"|string; export type RiskCounts = {[key: string]: Count}; export type SelectedChoices = ChoiceId[]; export type ShareId = string; export interface ShareInvitation { /** * The ID assigned to the share invitation. */ ShareInvitationId?: ShareInvitationId; WorkloadId?: WorkloadId; } export type ShareInvitationAction = "ACCEPT"|"REJECT"|string; export type ShareInvitationId = string; export type ShareInvitationSummaries = ShareInvitationSummary[]; export interface ShareInvitationSummary { /** * The ID assigned to the share invitation. */ ShareInvitationId?: ShareInvitationId; SharedBy?: AwsAccountId; SharedWith?: SharedWith; PermissionType?: PermissionType; WorkloadName?: WorkloadName; WorkloadId?: WorkloadId; } export type ShareStatus = "ACCEPTED"|"REJECTED"|"PENDING"|"REVOKED"|"EXPIRED"|string; export type SharedWith = string; export type SharedWithPrefix = string; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceInput { WorkloadArn: WorkloadArn; /** * The tags for the resource. */ Tags: TagMap; } export interface TagResourceOutput { } export type TagValue = string; export type Timestamp = Date; export interface UntagResourceInput { WorkloadArn: WorkloadArn; /** * A list of tag keys. Existing tags of the resource whose keys are members of this list are removed from the resource. */ TagKeys: TagKeyList; } export interface UntagResourceOutput { } export interface UpdateAnswerInput { WorkloadId: WorkloadId; LensAlias: LensAlias; QuestionId: QuestionId; SelectedChoices?: SelectedChoices; /** * A list of choices to update on a question in your workload. The String key corresponds to the choice ID to be updated. */ ChoiceUpdates?: ChoiceUpdates; Notes?: Notes; IsApplicable?: IsApplicable; /** * The reason why a question is not applicable to your workload. */ Reason?: AnswerReason; } export interface UpdateAnswerOutput { WorkloadId?: WorkloadId; LensAlias?: LensAlias; Answer?: Answer; } export interface UpdateLensReviewInput { WorkloadId: WorkloadId; LensAlias: LensAlias; LensNotes?: Notes; PillarNotes?: PillarNotes; } export interface UpdateLensReviewOutput { WorkloadId?: WorkloadId; LensReview?: LensReview; } export interface UpdateShareInvitationInput { /** * The ID assigned to the share invitation. */ ShareInvitationId: ShareInvitationId; ShareInvitationAction: ShareInvitationAction; } export interface UpdateShareInvitationOutput { /** * The updated workload share invitation. */ ShareInvitation?: ShareInvitation; } export interface UpdateWorkloadInput { WorkloadId: WorkloadId; WorkloadName?: WorkloadName; Description?: WorkloadDescription; Environment?: WorkloadEnvironment; AccountIds?: WorkloadAccountIds; AwsRegions?: WorkloadAwsRegions; NonAwsRegions?: WorkloadNonAwsRegions; PillarPriorities?: WorkloadPillarPriorities; ArchitecturalDesign?: WorkloadArchitecturalDesign; ReviewOwner?: WorkloadReviewOwner; /** * Flag indicating whether the workload owner has acknowledged that the Review owner field is required. If a Review owner is not added to the workload within 60 days of acknowledgement, access to the workload is restricted until an owner is added. */ IsReviewOwnerUpdateAcknowledged?: IsReviewOwnerUpdateAcknowledged; IndustryType?: WorkloadIndustryType; Industry?: WorkloadIndustry; Notes?: Notes; ImprovementStatus?: WorkloadImprovementStatus; } export interface UpdateWorkloadOutput { Workload?: Workload; } export interface UpdateWorkloadShareInput { ShareId: ShareId; WorkloadId: WorkloadId; PermissionType: PermissionType; } export interface UpdateWorkloadShareOutput { WorkloadId?: WorkloadId; WorkloadShare?: WorkloadShare; } export interface UpgradeLensReviewInput { WorkloadId: WorkloadId; LensAlias: LensAlias; MilestoneName: MilestoneName; ClientRequestToken?: ClientRequestToken; } export interface VersionDifferences { /** * The differences between the base and latest versions of the lens. */ PillarDifferences?: PillarDifferences; } export interface Workload { WorkloadId?: WorkloadId; WorkloadArn?: WorkloadArn; WorkloadName?: WorkloadName; Description?: WorkloadDescription; Environment?: WorkloadEnvironment; UpdatedAt?: Timestamp; AccountIds?: WorkloadAccountIds; AwsRegions?: WorkloadAwsRegions; NonAwsRegions?: WorkloadNonAwsRegions; ArchitecturalDesign?: WorkloadArchitecturalDesign; ReviewOwner?: WorkloadReviewOwner; ReviewRestrictionDate?: Timestamp; /** * Flag indicating whether the workload owner has acknowledged that the Review owner field is required. If a Review owner is not added to the workload within 60 days of acknowledgement, access to the workload is restricted until an owner is added. */ IsReviewOwnerUpdateAcknowledged?: IsReviewOwnerUpdateAcknowledged; IndustryType?: WorkloadIndustryType; Industry?: WorkloadIndustry; Notes?: Notes; ImprovementStatus?: WorkloadImprovementStatus; RiskCounts?: RiskCounts; PillarPriorities?: WorkloadPillarPriorities; Lenses?: WorkloadLenses; Owner?: AwsAccountId; /** * The ID assigned to the share invitation. */ ShareInvitationId?: ShareInvitationId; /** * The tags associated with the workload. */ Tags?: TagMap; } export type WorkloadAccountIds = AwsAccountId[]; export type WorkloadArchitecturalDesign = string; export type WorkloadArn = string; export type WorkloadAwsRegions = AwsRegion[]; export type WorkloadDescription = string; export type WorkloadEnvironment = "PRODUCTION"|"PREPRODUCTION"|string; export type WorkloadId = string; export type WorkloadImprovementStatus = "NOT_APPLICABLE"|"NOT_STARTED"|"IN_PROGRESS"|"COMPLETE"|"RISK_ACKNOWLEDGED"|string; export type WorkloadIndustry = string; export type WorkloadIndustryType = string; export type WorkloadLenses = LensAlias[]; export type WorkloadName = string; export type WorkloadNamePrefix = string; export type WorkloadNonAwsRegion = string; export type WorkloadNonAwsRegions = WorkloadNonAwsRegion[]; export type WorkloadPillarPriorities = PillarId[]; export type WorkloadReviewOwner = string; export interface WorkloadShare { ShareId?: ShareId; SharedBy?: AwsAccountId; SharedWith?: SharedWith; PermissionType?: PermissionType; Status?: ShareStatus; WorkloadName?: WorkloadName; WorkloadId?: WorkloadId; } export type WorkloadShareSummaries = WorkloadShareSummary[]; export interface WorkloadShareSummary { ShareId?: ShareId; SharedWith?: SharedWith; PermissionType?: PermissionType; Status?: ShareStatus; } export type WorkloadSummaries = WorkloadSummary[]; export interface WorkloadSummary { WorkloadId?: WorkloadId; WorkloadArn?: WorkloadArn; WorkloadName?: WorkloadName; Owner?: AwsAccountId; UpdatedAt?: Timestamp; Lenses?: WorkloadLenses; RiskCounts?: RiskCounts; ImprovementStatus?: WorkloadImprovementStatus; } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-03-31"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the WellArchitected client. */ export import Types = WellArchitected; } export = WellArchitected;
the_stack
import { assert } from '@canvas-ui/assert' import type { Canvas, Picture } from '../canvas' import type { RasterCache } from '../compositing' import { AbstractNode } from '../foundation' import { Circle, Matrix, Point, Rect, RRect } from '../math' export class PrerollContext { constructor( readonly rasterCache: RasterCache ) { } } export class PaintContext { constructor( readonly canvas: Canvas, readonly rasterCache: RasterCache, ) { } } export abstract class Layer extends AbstractNode<unknown> { override get parent(): ContainerLayer | undefined { return this._parent as (ContainerLayer | undefined) } redepthChildren() { // } /** * 后一个兄弟图层 */ nextSibling?: Layer /** * 前一个兄弟图层 */ prevSibling?: Layer removeFromParent() { return this.parent?.removeChild(this) } abstract preroll(context: PrerollContext, matrix: Matrix): void abstract paint(context: PaintContext): void paintBounds = Rect.zero get needsPainting() { return !Rect.isEmpty(this.paintBounds) } } export class ContainerLayer extends Layer { firstChild?: Layer lastChild?: Layer get hasChildren() { return this.firstChild !== undefined } override attach(owner: unknown) { super.attach(owner) let child = this.firstChild while (child) { child.attach(owner) child = child.nextSibling } } override detach() { super.detach() let child = this.firstChild while (child) { child.detach() child = child.nextSibling } } appendChild(child: Layer) { assert(child !== this) assert(child !== this.firstChild) assert(child !== this.lastChild) assert(!child.parent) assert(!child.attached) assert(!child.nextSibling) assert(!child.prevSibling) assert((() => { let node: Layer = this while (node.parent) { node = node.parent } assert(node !== child) // 不允许循环父子 return true })()) this.adoptChild(child) child.prevSibling = this.lastChild if (this.lastChild) { this.lastChild.nextSibling = child } this.lastChild = child this.firstChild ??= child assert(child.attached === this.attached) } removeChild(child: Layer) { assert(child.parent === this) assert(child.attached === this.attached) assert(this.debugUltimatePrevSiblingOf(child, this.firstChild)) assert(this.debugUltimateNextSiblingOf(child, this.lastChild)) if (!child.prevSibling) { // child 是第一个子节点 assert(this.firstChild === child) this.firstChild = child.nextSibling } else { child.prevSibling.nextSibling = child.nextSibling } if (!child.nextSibling) { // child 是最后一个子节点 assert(this.lastChild === child) this.lastChild = child.prevSibling } else { child.nextSibling.prevSibling = child.prevSibling } assert((!this.firstChild) === (!this.lastChild), '如果移除了最后一个子节点,则 firstChild 和 lastChild 都为 undefined,否则 firstChild 和 lastChild 都不能为 undefined') assert(!this.firstChild || this.firstChild.attached === this.attached) assert(!this.lastChild || this.lastChild.attached === this.attached) assert(!this.firstChild || this.debugUltimateNextSiblingOf(this.firstChild, this.lastChild), 'firstChild 和 lastChild 不能是循环兄弟节点') assert(!this.lastChild || this.debugUltimatePrevSiblingOf(this.lastChild, this.firstChild), 'lastChild 和 firstChild 不能是循环兄弟节点') child.prevSibling = undefined child.nextSibling = undefined this.dropChild(child) assert(!child.attached) } removeAllChildren() { let child = this.firstChild while (child) { const next = child.nextSibling child.prevSibling = undefined child.nextSibling = undefined assert(child.attached === this.attached) this.dropChild(child) child = next } this.firstChild = undefined this.lastChild = undefined } debugDFSChildren(): Layer[] { if (!this.firstChild) { return [] } const children: Layer[] = [] let child: Layer | undefined = this.firstChild while (child) { children.push(child) if (child instanceof ContainerLayer) { children.push(...child.debugDFSChildren()) } child = child.nextSibling } return children } private debugUltimatePrevSiblingOf(child: Layer, equals: Layer | undefined) { assert(child.attached === this.attached) while (child.prevSibling) { assert(child.prevSibling !== child) child = child.prevSibling assert(child.attached === this.attached) } return child === equals } private debugUltimateNextSiblingOf(child: Layer, equals: Layer | undefined) { assert(child.attached === this.attached) while (child.nextSibling) { assert(child.nextSibling !== child) child = child.nextSibling! assert(child.attached === this.attached) } return child === equals } preroll(context: PrerollContext, matrix: Matrix): void { this.paintBounds = this.prerollChildren(context, matrix) } prerollChildren(context: PrerollContext, childMatrix: Matrix): Rect { let childPaintBounds = Rect.zero let layer = this.firstChild while (layer) { layer.preroll(context, childMatrix) if (Rect.isEmpty(childPaintBounds)) { childPaintBounds = layer.paintBounds } else { childPaintBounds = Rect.expandToInclude(childPaintBounds, layer.paintBounds) } layer = layer.nextSibling } return childPaintBounds } paintChildren(context: PaintContext): void { assert(this.needsPainting) let layer = this.firstChild while (layer) { if (layer.needsPainting) { layer.paint(context) } layer = layer.nextSibling } } paint(context: PaintContext): void { this.paintChildren(context) } } export class PictureLayer extends Layer { constructor( private readonly offset = Point.zero, // private readonly complex = false, public willChange = false, ) { super() } picture?: Picture private matrix?: Matrix preroll(context: PrerollContext, matrix: Matrix): void { assert(this.picture) assert(Point.isZero(this.offset), '暂不支持 PictureLayer.offset') if (Point.isZero(this.offset)) { this.paintBounds = this.picture.cullRect } else { this.paintBounds = Rect.shift(this.picture.cullRect, this.offset) } context.rasterCache.prepare( this.picture, matrix, this.willChange, ) this.matrix = matrix } paint(context: PaintContext): void { assert(this.picture) assert(this.needsPainting) assert(this.matrix) context.canvas.save() assert(Point.isZero(this.offset), '暂不支持 PictureLayer.offset') // 优先绘制缓存了的图像 if (!context.rasterCache.drawPicture(this.picture, context.canvas, this.matrix)) { context.canvas.drawPicture(this.picture) } context.canvas.restore() } } export class TransformLayer extends ContainerLayer { constructor( public transform = Matrix.identity, ) { super() } override preroll(context: PrerollContext, matrix: Matrix) { const childMatrix = Matrix.mul(matrix, this.transform) const childPaintBounds = this.prerollChildren(context, childMatrix) // todo(haocong): !!! 还不支持缩放和斜切 !!! this.paintBounds = Rect.shift(childPaintBounds, Matrix.getTranslate(this.transform)) } override paint(context: PaintContext) { context.canvas.save() context.canvas.transform(this.transform) this.paintChildren(context) context.canvas.restore() } } export class OffsetLayer extends TransformLayer { constructor( offset = Point.zero, ) { super(Matrix.fromTranslate(offset.x, offset.y)) } set offset(value: Point) { this.transform = Matrix.fromTranslate(value.x, value.y) } get offset() { return Matrix.getTranslate(this.transform) } } export class ClipRectLayer extends ContainerLayer { constructor( public clipRect: Rect ) { super() } override preroll(context: PrerollContext, matrix: Matrix) { const childPaintBounds = this.prerollChildren(context, matrix) if (Rect.overlaps(this.clipRect, childPaintBounds)) { this.paintBounds = Rect.intersect(this.clipRect, childPaintBounds) } } override paint(context: PaintContext) { context.canvas.save() context.canvas.clipRect( this.clipRect.left, this.clipRect.top, this.clipRect.width, this.clipRect.height, ) this.paintChildren(context) context.canvas.restore() } } export class ClipRRectLayer extends ContainerLayer { constructor( public clipRRect: RRect ) { super() } override preroll(context: PrerollContext, matrix: Matrix) { const childPaintBounds = this.prerollChildren(context, matrix) if (Rect.overlaps(this.clipRRect, childPaintBounds)) { this.paintBounds = Rect.intersect(this.clipRRect, childPaintBounds) } } override paint(context: PaintContext) { context.canvas.save() context.canvas.clipRRect( this.clipRRect.left, this.clipRRect.top, this.clipRRect.width, this.clipRRect.height, this.clipRRect.radiusX, this.clipRRect.radiusY, ) this.paintChildren(context) context.canvas.restore() } } export class ClipCircleLayer extends ContainerLayer { constructor( clipCircle: Circle ) { super() this.clipCircle = clipCircle } get clipCircle(): Circle { return this._clipCircle } set clipCircle(value: Circle) { this._clipCircle = value this.clipBounds = Circle.getBounds(this._clipCircle) } private _clipCircle!: Circle private clipBounds!: Rect override preroll(context: PrerollContext, matrix: Matrix) { const childPaintBounds = this.prerollChildren(context, matrix) if (Rect.overlaps(this.clipBounds, childPaintBounds)) { this.paintBounds = Rect.intersect(this.clipBounds, childPaintBounds) } } override paint(context: PaintContext) { context.canvas.save() context.canvas.clipCircle( this.clipCircle.x, this.clipCircle.y, this.clipCircle.radius, ) this.paintChildren(context) context.canvas.restore() } }
the_stack
import expect from "expect"; import sample from "lodash/sample"; import sampleSize from "lodash/sampleSize"; import invariant from "invariant"; import { BigNumber } from "bignumber.js"; import type { CosmosDelegation, CosmosRedelegation, CosmosResources, CosmosUnbonding, Transaction, } from "../../families/cosmos/types"; import { getCurrentCosmosPreloadData } from "../../families/cosmos/preloadedData"; import { getCryptoCurrencyById } from "../../currencies"; import { pickSiblings } from "../../bot/specs"; import type { AppSpec } from "../../bot/types"; import { toOperationRaw } from "../../account"; import { COSMOS_MIN_SAFE, canClaimRewards, canDelegate, canUndelegate, canRedelegate, getMaxDelegationAvailable, } from "./logic"; import { DeviceModelId } from "@ledgerhq/devices"; const cosmos: AppSpec<Transaction> = { name: "Cosmos", currency: getCryptoCurrencyById("cosmos"), appQuery: { model: DeviceModelId.nanoS, firmware: "<2", appName: "Cosmos", }, transactionCheck: ({ maxSpendable }) => { invariant(maxSpendable.gt(COSMOS_MIN_SAFE), "balance is too low"); }, test: ({ operation, optimisticOperation }) => { const opExpected: Record<string, any> = toOperationRaw({ ...optimisticOperation, }); delete opExpected.value; delete opExpected.fee; delete opExpected.date; delete opExpected.blockHash; delete opExpected.blockHeight; expect(toOperationRaw(operation)).toMatchObject(opExpected); // TODO check it is between operation.value-fees (excluded) and operation.value /* // balance move expect(account.balance.toString()).toBe( accountBeforeTransaction.balance.minus(operation.value).toString() ); */ }, mutations: [ { name: "send some", maxRun: 2, transaction: ({ account, siblings, bridge, maxSpendable }) => { return { transaction: bridge.createTransaction(account), updates: [ { recipient: pickSiblings(siblings, 7).freshAddress, }, { amount: maxSpendable .times(0.3 + 0.4 * Math.random()) .integerValue(), }, Math.random() < 0.5 ? { memo: "LedgerLiveBot", } : null, ], }; }, }, { name: "send max", maxRun: 1, transaction: ({ account, siblings, bridge }) => { return { transaction: bridge.createTransaction(account), updates: [ { recipient: pickSiblings(siblings, 7).freshAddress, }, { useAllAmount: true, }, ], }; }, test: ({ account }) => { expect(account.spendableBalance.toString()).toBe("0"); }, }, { name: "delegate new validators", maxRun: 2, transaction: ({ account, bridge }) => { invariant( account.index % 10 > 0, "one out of 10 accounts is not going to delegate" ); invariant(canDelegate(account), "can delegate"); const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); invariant( (cosmosResources as CosmosResources).delegations.length < 10, "already enough delegations" ); const data = getCurrentCosmosPreloadData(); const count = 1 + Math.floor(5 * Math.random()); let remaining = getMaxDelegationAvailable(account, count).times( Math.random() ); const all = data.validators.filter( (v) => !(cosmosResources as CosmosResources).delegations.some( // new delegations only (d) => d.validatorAddress === v.validatorAddress ) ); const validators = sampleSize(all, count) .map((delegation) => { // take a bit of remaining each time (less is preferred with the random() square) const amount = remaining .times(Math.random() * Math.random()) .integerValue(); remaining = remaining.minus(amount); return { address: delegation.validatorAddress, amount, }; }) .filter((v) => v.amount.gt(0)); invariant(validators.length > 0, "no possible delegation found"); return { transaction: bridge.createTransaction(account), updates: [ { memo: "LedgerLiveBot", mode: "delegate", }, ...validators.map((_, i) => ({ validators: validators.slice(0, i + 1), })), ], }; }, test: ({ account, transaction }) => { const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); transaction.validators.forEach((v) => { const d = (cosmosResources as CosmosResources).delegations.find( (d) => d.validatorAddress === v.address ); invariant(d, "delegated %s must be found in account", v.address); expect({ address: v.address, // we round last digit amount: "~" + v.amount.div(10).integerValue().times(10).toString(), }).toMatchObject({ address: (d as CosmosDelegation).validatorAddress, amount: "~" + (d as CosmosDelegation).amount .div(10) .integerValue() .times(10) .toString(), }); }); }, }, { name: "undelegate", maxRun: 3, transaction: ({ account, bridge }) => { invariant(canUndelegate(account), "can undelegate"); const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); invariant( (cosmosResources as CosmosResources).delegations.length > 0, "already enough delegations" ); const undelegateCandidate = sample( (cosmosResources as CosmosResources).delegations.filter( (d) => !(cosmosResources as CosmosResources).redelegations.some( (r) => r.validatorSrcAddress === d.validatorAddress || r.validatorDstAddress === d.validatorAddress ) && !(cosmosResources as CosmosResources).unbondings.some( (r) => r.validatorAddress === d.validatorAddress ) ) ); invariant(undelegateCandidate, "already pending"); return { transaction: bridge.createTransaction(account), updates: [ { mode: "undelegate", memo: "LedgerLiveBot", }, { validators: [ { address: (undelegateCandidate as CosmosDelegation) .validatorAddress, amount: (undelegateCandidate as CosmosDelegation).amount // most of the time, undelegate all .times(Math.random() > 0.3 ? 1 : Math.random()) .integerValue(), }, ], }, ], }; }, test: ({ account, transaction }) => { const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); transaction.validators.forEach((v) => { const d = (cosmosResources as CosmosResources).unbondings.find( (d) => d.validatorAddress === v.address ); invariant(d, "undelegated %s must be found in account", v.address); expect({ address: v.address, // we round last digit amount: "~" + v.amount.div(10).integerValue().times(10).toString(), }).toMatchObject({ address: (d as CosmosUnbonding).validatorAddress, amount: "~" + (d as CosmosUnbonding).amount .div(10) .integerValue() .times(10) .toString(), }); }); }, }, { name: "redelegate", maxRun: 1, transaction: ({ account, bridge }) => { const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); const sourceDelegation = sample( (cosmosResources as CosmosResources).delegations.filter((d) => canRedelegate(account, d) ) ); invariant(sourceDelegation, "none can redelegate"); const delegation = sample( (cosmosResources as CosmosResources).delegations.filter( (d) => d.validatorAddress !== (sourceDelegation as CosmosDelegation).validatorAddress ) ); return { transaction: bridge.createTransaction(account), updates: [ { mode: "redelegate", memo: "LedgerLiveBot", cosmosSourceValidator: (sourceDelegation as CosmosDelegation) .validatorAddress, validators: [ { address: (delegation as CosmosDelegation).validatorAddress, amount: (sourceDelegation as CosmosDelegation).amount .times( // most of the time redelegate all Math.random() > 0.3 ? 1 : Math.random() ) .integerValue(), }, ], }, ], }; }, test: ({ account, transaction }) => { const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); transaction.validators.forEach((v) => { const d = (cosmosResources as CosmosResources).redelegations .slice(0) // recent first .sort( // FIXME: valueOf for date arithmetic operations in typescript (a, b) => b.completionDate.valueOf() - a.completionDate.valueOf() ) // find the related redelegation .find( (d) => d.validatorDstAddress === v.address && d.validatorSrcAddress === transaction.cosmosSourceValidator ); invariant(d, "redelegated %s must be found in account", v.address); expect({ address: v.address, // we round last digit amount: "~" + v.amount.div(10).integerValue().times(10).toString(), }).toMatchObject({ address: (d as CosmosRedelegation).validatorDstAddress, amount: "~" + (d as CosmosRedelegation).amount .div(10) .integerValue() .times(10) .toString(), }); }); }, }, { name: "claim rewards", maxRun: 1, transaction: ({ account, bridge }) => { const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); const delegation = sample( (cosmosResources as CosmosResources).delegations.filter( // FIXME // (d) => canClaimRewards(account, d) && d.pendingRewards.gt(2000) (d) => d.pendingRewards.gt(2000) ) ); invariant(delegation, "no delegation to claim"); return { transaction: bridge.createTransaction(account), updates: [ { mode: "claimReward", memo: "LedgerLiveBot", validators: [ { address: (delegation as CosmosDelegation).validatorAddress, // TODO: the test should be // amount: delegation.pendingRewards, // but it won't work until COIN-665 is fixed until then, // amount is set to 0 in // src/families/cosmos/libcore-buildOperation in the REWARD case amount: new BigNumber(0), }, ], }, ], }; }, test: ({ account, transaction }) => { const { cosmosResources } = account; invariant(cosmosResources, "cosmos"); transaction.validators.forEach((v) => { const d = (cosmosResources as CosmosResources).delegations.find( (d) => d.validatorAddress === v.address ); invariant(d, "delegation %s must be found in account", v.address); invariant( !canClaimRewards(account, d as CosmosDelegation), "reward no longer be claimable" ); }); }, }, ], }; export default { cosmos, };
the_stack
import * as _ from 'lodash'; import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import * as fs from 'fs-extra'; import { PipelineRunData, TriggerTemplateKindParam, TriggerTemplateKind, EventListenerKind, Workspace, VCT, TknTaskRun } from '../tekton'; import { TektonItem } from './tektonitem'; import { AddTriggerFormValues, Pipeline, TriggerBindingKind, Resources, Param, Workspaces } from './triggertype'; import { K8sKind, PipelineRunKind, RouteKind } from './k8s-type'; import * as yaml from 'js-yaml'; import { Platform } from '../util/platform'; import { exposeRoute, RouteModel } from './expose'; import { Progress } from '../util/progress'; import { TknVersion, version } from '../util/tknversion'; import { NewPvc } from './create-resources'; import { getExposeURl } from '../util/exposeurl'; import { telemetryLog, telemetryLogError } from '../telemetry'; import { getStderrString } from '../util/stderrstring'; import { Command } from '../cli-command'; import semver = require('semver'); import { ClusterTaskModel, EventListenerModel, PipelineRunModel, TaskModel, TriggerTemplateModel } from '../util/resource-kind'; import { showPipelineRunPreview } from '../pipeline/pipeline-preview'; import { PipelineRun } from './pipelinerun'; import { tkn } from '../tkn'; export enum WorkspaceResource { Secret = 'secret', ConfigMap = 'configMap', PersistentVolumeClaim = 'persistentVolumeClaim', EmptyDirectory = 'emptyDir' } export const PIPELINE_SERVICE_ACCOUNT = 'pipeline'; export function addTriggerToPipeline(inputAddTrigger: AddTriggerFormValues): Promise<string> { return Progress.execFunctionWithProgress('Adding Trigger.', () => addTrigger(inputAddTrigger) .then(() => TektonItem.explorer.refresh()) .catch((error) => Promise.reject(`Failed to Add Trigger '${error}'`)) ); } export async function addTrigger(inputAddTrigger: AddTriggerFormValues): Promise<void> { if (inputAddTrigger.resources && inputAddTrigger.resources.length !== 0) { restoreResource(inputAddTrigger.resources); } if (inputAddTrigger.params && inputAddTrigger.params.length !== 0) { newParam(inputAddTrigger.params); } const triggerBinding = inputAddTrigger.trigger; const pipelineRun: PipelineRunData = await getPipelineRunFrom(inputAddTrigger, { generateName: true }, {}); // const triggerTemplateParams: TriggerTemplateKindParam[] = triggerBinding.resource.spec.params.map( ({ name }) => ({ name } as TriggerTemplateKindParam), ); const triggerTemplate: TriggerTemplateKind = createTriggerTemplate( pipelineRun, triggerTemplateParams, inputAddTrigger.name ); const createTt = await k8sCreate(triggerTemplate, inputAddTrigger.commandId); if (!createTt) return null; const eventListener: EventListenerKind = await createEventListener( [triggerBinding.resource], triggerTemplate, ); const createEt = await k8sCreate(eventListener, inputAddTrigger.commandId); if (!createEt) return null; await exposeRoute(eventListener.metadata.name, inputAddTrigger.commandId); } export async function k8sCreate(trigger: TriggerTemplateKind | EventListenerKind | RouteKind | NewPvc | PipelineRunKind | TknTaskRun, commandId?: string, kind?: string): Promise<boolean> { const quote = Platform.OS === 'win32' ? '"' : '\''; const triggerYaml = yaml.safeDump(trigger, {skipInvalid: true}); const tempPath = os.tmpdir(); if (!tempPath) { return false; } const fsPath = path.join(tempPath, `${trigger.metadata.name || trigger.metadata.generateName}.yaml`); await fs.writeFile(fsPath, triggerYaml, 'utf8'); const result = await tkn.execute(Command.create(`${quote}${fsPath}${quote}`)); if (result.error) { telemetryLogError(commandId, result.error.toString().replace(fsPath, 'user path')); vscode.window.showErrorMessage(`Fail to deploy Resources: ${getStderrString(result.error)}`); return false; } if (trigger.kind === RouteModel.kind && !result.error) { const url = await getExposeURl(trigger.metadata.name); telemetryLog(commandId, 'Trigger successfully created'); vscode.window.showInformationMessage(`Trigger successfully created. Expose URL: ${url}`); } if (kind === PipelineRunModel.kind && !result.error) { const message = 'Pipeline successfully started'; telemetryLog(commandId, message); if (TektonItem.ShowPipelineRun()) { const pipelineRunNameRegex = new RegExp(`${trigger.metadata.generateName}\\w*`); const pipelineRunName = result.stdout.match(pipelineRunNameRegex)[0]; if (pipelineRunName) { await showPipelineRunPreview(pipelineRunName); if (vscode.workspace.getConfiguration('vs-tekton').get('showLogsOnPipelineStart')) PipelineRun.pipelineRunFollowLogs(pipelineRunName); } } vscode.window.showInformationMessage(message); } if ((kind === TaskModel.kind || kind === ClusterTaskModel.kind) && !result.error) { const message = `${kind} successfully started`; telemetryLog(commandId, message); vscode.window.showInformationMessage(message); } await fs.unlink(fsPath); return true; } function newParam(params: Param[]): void { params.map(val => { val.value = val.default delete val.default }) } function restoreResource(resource: Resources[]): void { resource.map(val => { const referenceName: string = (typeof val.resourceRef === 'string') ? val.resourceRef : undefined; val.resourceRef = { name: referenceName } }) } export async function getPipelineRunFrom(inputAddTrigger: AddTriggerFormValues, options?: { generateName: boolean }, labels?: { [key: string]: string },): Promise<PipelineRunData> { const pipelineRunData: PipelineRunData = { metadata: { labels, }, spec: { pipelineRef: { name: inputAddTrigger.name, }, params: inputAddTrigger.params, resources: inputAddTrigger.resources, workspaces: getPipelineRunWorkspaces(inputAddTrigger.workspaces, inputAddTrigger.volumeClaimTemplate), serviceAccountName: inputAddTrigger.serviceAccount, }, }; return await getPipelineRunData(pipelineRunData, options); } export function getPipelineRunWorkspaces(workspaces: Workspaces[], volumeClaimTemplate?: VCT[]): Workspace[] { const newWorkspace = []; if (workspaces && workspaces.length === 0) return newWorkspace; workspaces.map((workspaceData: Workspaces) => { const newWorkspaceObject = {}; const workspaceResourceObject = {}; newWorkspaceObject['name'] = workspaceData.name; if (WorkspaceResource[workspaceData.workspaceType] === WorkspaceResource.Secret) { workspaceResourceObject['secretName'] = workspaceData.workspaceName; } else if (WorkspaceResource[workspaceData.workspaceType] === WorkspaceResource.ConfigMap) { workspaceResourceObject['name'] = workspaceData.workspaceName; } else if (WorkspaceResource[workspaceData.workspaceType] === WorkspaceResource.PersistentVolumeClaim) { workspaceResourceObject['claimName'] = workspaceData.workspaceName; } else if (WorkspaceResource[workspaceData.workspaceType] === WorkspaceResource.EmptyDirectory) { workspaceResourceObject['emptyDir'] } if (workspaceData.item && workspaceData.item.length !== 0) { workspaceResourceObject['items'] = workspaceData.item; } newWorkspaceObject[WorkspaceResource[workspaceData.workspaceType]] = workspaceResourceObject; newWorkspace.push(newWorkspaceObject); }); if (volumeClaimTemplate && volumeClaimTemplate.length !== 0) { volumeClaimTemplate.map(value => { const workspaceObject = {}; workspaceObject['name'] = value.metadata.name, workspaceObject[value.kind] = { spec: value.spec } newWorkspace.push(workspaceObject); }) } return newWorkspace; } function getRandomChars(len = 6): string { return Math.random() .toString(36) .replace(/[^a-z0-9]+/g, '') .substr(1, len); } async function getPipelineRunData(latestRun: PipelineRunData, options?: { generateName: boolean }): Promise<PipelineRunData> { const pipelineData = await TektonItem.tkn.execute(Command.getPipeline(latestRun.spec.pipelineRef.name), process.cwd(), false); const pipeline: Pipeline = JSON.parse(pipelineData.stdout); const resources = latestRun?.spec.resources; const pipelineName = pipeline ? pipeline.metadata.name : latestRun.spec.pipelineRef.name; const workspaces = latestRun?.spec.workspaces; const latestRunParams = latestRun?.spec.params; const params = latestRunParams; const newPipelineRun = { apiVersion: pipeline ? pipeline.apiVersion : latestRun.apiVersion, kind: PipelineRunModel.kind, metadata: { ...(options?.generateName ? { generateName: `${pipelineName}-`, } : { name: `${pipelineName}-${getRandomChars()}`, }), // namespace: pipeline ? pipeline.metadata.namespace : latestRun.metadata.namespace, labels: _.merge({}, pipeline?.metadata?.labels, latestRun?.metadata?.labels, { 'tekton.dev/pipeline': pipelineName, }), }, spec: { ...(latestRun?.spec || {}), pipelineRef: { name: pipelineName, }, resources, ...(params && { params }), workspaces, status: null, }, }; return migratePipelineRun(newPipelineRun); } function migratePipelineRun(pipelineRun: PipelineRunData): PipelineRunData { let newPipelineRun = pipelineRun; const serviceAccountPath = 'spec.serviceAccount'; if (_.has(newPipelineRun, serviceAccountPath)) { // .spec.serviceAccount was removed for .spec.serviceAccountName in 0.9.x // Note: apiVersion was not updated for this change and thus we cannot gate this change behind a version number const serviceAccountName = _.get(newPipelineRun, serviceAccountPath); newPipelineRun = _.omit(newPipelineRun, [serviceAccountPath]); newPipelineRun = _.merge(newPipelineRun, { spec: { serviceAccountName, }, }); } return newPipelineRun; } export function createTriggerTemplate(pipelineRun: PipelineRunData, params: TriggerTemplateKindParam[], pipelineName?: string): TriggerTemplateKind { return { apiVersion: apiVersionForModel(TriggerTemplateModel), kind: TriggerTemplateModel.kind, metadata: { name: `trigger-template-${pipelineName}-${getRandomChars()}`, }, spec: { params, resourcetemplates: [pipelineRun], }, }; } export function apiVersionForModel(model: K8sKind): string { return _.isEmpty(model.apiGroup) ? model.apiVersion : `${model.apiGroup}/${model.apiVersion}`; } export async function createEventListener(triggerBindings: TriggerBindingKind[], triggerTemplate: TriggerTemplateKind): Promise<EventListenerKind> { const getNewELSupport: TknVersion = await version(); const compareVersion = semver.satisfies('0.5.0', `>=${getNewELSupport.trigger}`); return { apiVersion: apiVersionForModel(EventListenerModel), kind: EventListenerModel.kind, metadata: { name: `event-listener-${getRandomChars()}`, }, spec: { serviceAccountName: PIPELINE_SERVICE_ACCOUNT, triggers: [ { bindings: triggerBindings.map(({ kind, metadata: { name } }) => { if (compareVersion) { return ({ kind, name }); } else { const Ref = name; return ({ kind, Ref }); } }), template: compareVersion ? { name: triggerTemplate.metadata.name } : { ref: triggerTemplate.metadata.name }, }, ], }, }; }
the_stack
import { TestBed } from '@angular/core/testing'; import { Component, ViewChild } from '@angular/core'; import * as Infragistics from '../../public-api'; declare const $: any; describe('Infragistics Angular HierarchicalGrid', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [Infragistics.IgHierarchicalGridComponent, TestComponent] }); }); it('should initialize correctly', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgHierarchicalGridComponent) .toBe(true); done(); }); }); it('should reflect changes when a record in the data changes', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [options]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.data[0].Name = ''; fixture.detectChanges(); fixture.componentInstance.data[0].Name = 'Test'; fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tr:first td[aria-describedby=\'grid1_Name\']').text()) .toBe('Test'); done(); }); }); it('should reflect changes when a record is removed from the data', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); // remove item fixture.componentInstance.data.removeAt(0); setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tr').length) .toBe(2); expect($(fixture.debugElement.nativeElement).find('#grid1 tr:first td[aria-describedby=\'grid1_Name\']').text()) .toBe('Beverages'); done(); }, 10); }); }); it('should reflect changes when a record is added from the data', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); // add item fixture.componentInstance.data.push({ ID: 200, Name: 'John Snow' }); setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tr').length) .toBe(4); expect($(fixture.debugElement.nativeElement).find('#grid1 tr:last td[aria-describedby=\'grid1_Name\']').text()) .toBe('John Snow'); done(); }, 10); }); }); it('should reflect changes when records in the grid are updated', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); // update row $('#grid1').igGridUpdating('updateRow', 0, { Name: 'Maria' }); setTimeout(() => { fixture.detectChanges(); const fName = fixture.componentInstance.data[0].Name; expect(fName).toBe('Maria'); done(); }, 10); }); }); it('should reflect changes when records in the grid are deleted', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); // delete row $('#grid1').igGridUpdating('deleteRow', 0); setTimeout(() => { fixture.detectChanges(); expect(fixture.componentInstance.data.length).toBe(2); expect(fixture.componentInstance.data[0].ID).toBe(1); done(); }, 10); }); }); it('should reflect changes when records in the grid are added', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); $('#grid1').igGridUpdating('addRow', { ID: 200, Name: 'Snow' }); setTimeout(() => { fixture.detectChanges(); expect(fixture.componentInstance.data.length).toBe(4); expect(fixture.componentInstance.data[3].ID).toBe(200); done(); }, 10); }); }); it('should reflect changes when child records are changed', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); // expand first record const row = $('#grid1').igGrid('rowAt', 0); $('#grid1').igHierarchicalGrid('expand', row, () => { // change data child data fixture.componentInstance.data[0].Products.removeAt(0); setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1') .igHierarchicalGrid('option', 'dataSource')[0].Products.length).toBe(0); done(); }, 10); }); }); }); it('should reflect changes when a value in the child grid changes', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data" #hgrid></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); // expand first record const row = $('#grid1').igGrid('rowAt', 0); $('#grid1').igHierarchicalGrid('expand', row, () => { // change data child data fixture.componentInstance.data[0].Products[0].Name = 'Custom Name'; fixture.componentInstance.viewChild.markForCheck(); setTimeout(() => { fixture.detectChanges(); expect($($(fixture.debugElement.nativeElement).find('#grid1_0_Products_child').igGrid('cellAt', 1, 0)).text()) .toBe('Custom Name'); done(); }, 10); }); }); }); it('should initialize correctly when datasource is remote', (done) => { $['mockjax']({ url: 'myURL/Categories', contentType: 'application/json', dataType: 'json', responseText: '[{"ID": 0, "Name": "Food", "Products":[{"ID":0,"Name":"Bread","Description":"Whole grain bread","ReleaseDate":"1992-01-01T00:00:00","DiscontinuedDate":null,"Rating":4,"Price":2.5}]}]' }); const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID2" [(options)]="opts2"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); setTimeout(() => { expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgHierarchicalGridComponent) .toBe(true); done(); }, 500); }); }); it('should detect changes when original data source is changed but the data source length is the same.', (done) => { const template = '<ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="optsNew" [dataSource]="singleRecData"></ig-hierarchical-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.componentInstance.singleRecData.length = 0; Array.prototype.push.apply(fixture.componentInstance.singleRecData, fixture.componentInstance.singleRecData2); fixture.detectChanges(); const $grid = $('#grid1'); expect($grid.data('igGrid').allRows().length === 1).toBeTruthy('There should be one record in grid.'); expect($($grid.data('igGrid').cellById(1, 'Name')).text() === 'Test').toBeTruthy('Change in text should be reflected in grid.'); done(); }); }); it('should fill the featuresList and allow accessing their methods', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.viewChild.featuresList.updating.deleteRow(1); setTimeout(() => { fixture.detectChanges(); expect(fixture.componentInstance.data.length).toBe(2); done(); }, 10); }); }); it('should allow setting empty array for data source', (done) => { const template = '<div><ig-hierarchical-grid [(widgetId)]="gridID" [(options)]="opts" [(dataSource)]="data"></ig-hierarchical-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.data = []; fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1_container tbody tr').length) .toBe(0); done(); }); }); }); @Component({ selector: 'test-cmp', template: '<div></div>' // "Component 'TestComponent' must have either 'template' or 'templateUrl' set." }) class TestComponent { private opts: any; private opts2: any; private optsNew: any; private gridID: string; private gridID2: string; public data: any; protected cdi = 0; public singleRecData: Array<any>; public singleRecData2: Array<any>; @ViewChild(Infragistics.IgHierarchicalGridComponent, { static: true }) public viewChild: Infragistics.IgHierarchicalGridComponent; constructor() { this.data = [ { ID: 0, Name: 'Food', Products: [ { ID: 0, Name: 'Bread', Price: '2.5' } ] }, { ID: 1, Name: 'Beverages', Products: [ { ID: 1, Name: 'Milk', Price: '3.5' }, { ID: 2, Name: 'Vint soda', Price: '20.9' } ] }, { ID: 2, Name: 'Electronics', Products: [ { ID: 7, Name: 'DVD Player', Price: '35.88' }, { ID: 8, Name: 'LCD HDTV', Price: '1088.8' } ] } ]; this.singleRecData = [{ ID: 0, Name: 'Food', Products: [ { ID: 0, Name: 'Bread', Price: '2.5' } ] }]; this.singleRecData2 = [{ ID: 1, Name: 'Test', Products: [ { ID: 1, Name: 'Milk', Price: '3.5' }, { ID: 2, Name: 'Vint soda', Price: '20.9' } ] }]; this.gridID = 'grid1'; this.gridID2 = 'hgrid'; this.opts = { autoCommit: true, localSchemaTransform: false, // dataSource: this.data, primaryKey: 'ID', width: '100%', height: '400px', autoGenerateColumns: false, autoGenerateColumnLayouts: false, columns: [ { headerText: 'ID', key: 'ID', width: '50px', dataType: 'number' }, { headerText: 'Name', key: 'Name', width: '130px', dataType: 'string' } ], features: [ { name: 'Updating' } ], columnLayouts: [ { key: 'Products', responseDataKey: '', childrenDataProperty: 'Products', autoGenerateColumns: false, primaryKey: 'ID', columns: [ { key: 'ID', headerText: 'ID', width: '25px' }, { key: 'Name', headerText: 'Product Name', width: '90px' }, { key: 'Price', headerText: 'Price', dataType: 'number', width: '55px' } ] } ] }; this.optsNew = { autoCommit: true, // dataSource: this.singleRecData, primaryKey: 'ID', width: '100%', height: '400px', autoGenerateColumns: false, autoGenerateColumnLayouts: false, columns: [ { headerText: 'ID', key: 'ID', width: '50px', dataType: 'number' }, { headerText: 'Name', key: 'Name', width: '130px', dataType: 'string' } ], columnLayouts: [ { key: 'Products', responseDataKey: '', childrenDataProperty: 'Products', autoGenerateColumns: false, primaryKey: 'ID', columns: [ { key: 'ID', headerText: 'ID', width: '25px' }, { key: 'Name', headerText: 'Product Name', width: '90px' }, { key: 'Price', headerText: 'Price', dataType: 'number', width: '55px' } ] } ] }; this.opts2 = { dataSource: 'myURL/Categories' }; } }
the_stack
import type { TextDocument } from 'vscode-languageserver-textdocument'; import type { Connection, TextDocuments } from 'vscode-languageserver'; import type winston from 'winston'; import type { LanguageServerContext, LanguageServerOptions } from '../../src/server/types'; import type { CommandManager, NotificationManager } from '../../src/utils/lsp'; import type { StylelintRunner } from '../../src/utils/stylelint'; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type JestFn = jest.Mock<any, any>; export type MockConnection = { __typed: () => Connection; client: { connection: MockConnection; register: JestFn; }; console: { connection: MockConnection; error: JestFn; info: JestFn; log: JestFn; warn: JestFn; }; dispose: JestFn; languages: { connection: MockConnection; attachPartialResultProgress: JestFn; attachWorkDoneProgress: JestFn; callHierarchy: { onIncomingCalls: JestFn; onOutgoingCalls: JestFn; onPrepare: JestFn; }; moniker: { on: JestFn; }; onLinkedEditingRange: JestFn; semanticTokens: { on: JestFn; onDelta: JestFn; onRange: JestFn; }; }; listen: JestFn; onCodeAction: JestFn; onCodeActionResolve: JestFn; onCodeLens: JestFn; onCodeLensResolve: JestFn; onColorPresentation: JestFn; onCompletion: JestFn; onCompletionResolve: JestFn; onDeclaration: JestFn; onDefinition: JestFn; onDidChangeConfiguration: JestFn; onDidChangeTextDocument: JestFn; onDidChangeWatchedFiles: JestFn; onDidCloseTextDocument: JestFn; onDidOpenTextDocument: JestFn; onDidSaveTextDocument: JestFn; onDocumentColor: JestFn; onDocumentFormatting: JestFn; onDocumentHighlight: JestFn; onDocumentLinkResolve: JestFn; onDocumentLinks: JestFn; onDocumentOnTypeFormatting: JestFn; onDocumentRangeFormatting: JestFn; onDocumentSymbol: JestFn; onExecuteCommand: JestFn; onExit: JestFn; onFoldingRanges: JestFn; onHover: JestFn; onImplementation: JestFn; onInitialize: JestFn; onInitialized: JestFn; onNotification: JestFn; onPrepareRename: JestFn; onProgress: JestFn; onReferences: JestFn; onRenameRequest: JestFn; onRequest: JestFn; onSignatureHelp: JestFn; onSelectionRanges: JestFn; onShutdown: JestFn; onTypeDefinition: JestFn; onWillSaveTextDocument: JestFn; onWillSaveTextDocumentWaitUntil: JestFn; onWorkspaceSymbol: JestFn; sendDiagnostics: JestFn; sendNotification: JestFn; sendProgress: JestFn; sendRequest: JestFn; telemetry: { connection: MockConnection; logEvent: JestFn; }; tracer: { connection: MockConnection; log: JestFn; }; window: { connection: MockConnection; attachWorkDoneProgress: JestFn; createWorkDoneProgress: JestFn; showDocument: JestFn; showErrorMessage: JestFn; showInformationMessage: JestFn; showWarningMessage: JestFn; }; workspace: { connection: MockConnection; applyEdit: JestFn; getConfiguration: JestFn; getWorkspaceFolders: JestFn; onDidChangeWorkspaceFolders: JestFn; onDidCreateFiles: JestFn; onDidDeleteFiles: JestFn; onDidRenameFiles: JestFn; onWillCreateFiles: JestFn; onWillDeleteFiles: JestFn; onWillRenameFiles: JestFn; }; }; /** * Returns a mock language server connection. */ export function getConnection(): MockConnection { const connection: MockConnection = { __typed: () => connection as Connection, client: { get connection() { return connection; }, register: jest.fn(), }, console: { get connection() { return connection; }, error: jest.fn(), info: jest.fn(), log: jest.fn(), warn: jest.fn(), }, dispose: jest.fn(), languages: { get connection() { return connection; }, attachPartialResultProgress: jest.fn(), attachWorkDoneProgress: jest.fn(), callHierarchy: { onIncomingCalls: jest.fn(), onOutgoingCalls: jest.fn(), onPrepare: jest.fn(), }, moniker: { on: jest.fn(), }, onLinkedEditingRange: jest.fn(), semanticTokens: { on: jest.fn(), onDelta: jest.fn(), onRange: jest.fn(), }, }, listen: jest.fn(), onCodeAction: jest.fn(), onCodeActionResolve: jest.fn(), onCodeLens: jest.fn(), onCodeLensResolve: jest.fn(), onColorPresentation: jest.fn(), onCompletion: jest.fn(), onCompletionResolve: jest.fn(), onDeclaration: jest.fn(), onDefinition: jest.fn(), onDidChangeConfiguration: jest.fn(), onDidChangeTextDocument: jest.fn(), onDidChangeWatchedFiles: jest.fn(), onDidCloseTextDocument: jest.fn(), onDidOpenTextDocument: jest.fn(), onDidSaveTextDocument: jest.fn(), onDocumentColor: jest.fn(), onDocumentFormatting: jest.fn(), onDocumentHighlight: jest.fn(), onDocumentLinkResolve: jest.fn(), onDocumentLinks: jest.fn(), onDocumentOnTypeFormatting: jest.fn(), onDocumentRangeFormatting: jest.fn(), onDocumentSymbol: jest.fn(), onExecuteCommand: jest.fn(), onExit: jest.fn(), onFoldingRanges: jest.fn(), onHover: jest.fn(), onImplementation: jest.fn(), onInitialize: jest.fn(), onInitialized: jest.fn(), onNotification: jest.fn(), onPrepareRename: jest.fn(), onProgress: jest.fn(), onReferences: jest.fn(), onRenameRequest: jest.fn(), onRequest: jest.fn(), onSignatureHelp: jest.fn(), onSelectionRanges: jest.fn(), onShutdown: jest.fn(), onTypeDefinition: jest.fn(), onWillSaveTextDocument: jest.fn(), onWillSaveTextDocumentWaitUntil: jest.fn(), onWorkspaceSymbol: jest.fn(), sendDiagnostics: jest.fn(), sendNotification: jest.fn(), sendProgress: jest.fn(), sendRequest: jest.fn(), telemetry: { get connection() { return connection; }, logEvent: jest.fn(), }, tracer: { get connection() { return connection; }, log: jest.fn(), }, window: { get connection() { return connection; }, attachWorkDoneProgress: jest.fn(), createWorkDoneProgress: jest.fn(), showDocument: jest.fn(), showErrorMessage: jest.fn(), showInformationMessage: jest.fn(), showWarningMessage: jest.fn(), }, workspace: { get connection() { return connection; }, applyEdit: jest.fn(), getConfiguration: jest.fn(), getWorkspaceFolders: jest.fn(), onDidChangeWorkspaceFolders: jest.fn(), onDidCreateFiles: jest.fn(), onDidDeleteFiles: jest.fn(), onDidRenameFiles: jest.fn(), onWillCreateFiles: jest.fn(), onWillDeleteFiles: jest.fn(), onWillRenameFiles: jest.fn(), }, }; return connection; } /** * Returns a mock logger. */ export function getLogger(): jest.Mocked<winston.Logger> { const logger: jest.Mocked<winston.Logger> = Object.assign(jest.fn(), { [Symbol.asyncIterator]: jest.fn(), _destroy: jest.fn(), _final: jest.fn(), _flush: jest.fn(), _read: jest.fn(), _transform: jest.fn(), _write: jest.fn(), add: jest.fn(), addListener: jest.fn(), alert: jest.fn(), allowHalfOpen: false, child: jest.fn().mockImplementation(() => logger), close: jest.fn(), clear: jest.fn(), configure: jest.fn(), cork: jest.fn(), crit: jest.fn(), data: jest.fn(), debug: jest.fn(), destroy: jest.fn(), destroyed: false, emerg: jest.fn(), emit: jest.fn(), end: jest.fn(), error: jest.fn(), eventNames: jest.fn(), exceptions: Object.assign(jest.fn(), { catcher: false, getAllInfo: jest.fn(), getOsInfo: jest.fn(), getProcessInfo: jest.fn(), getTrace: jest.fn(), handle: jest.fn(), handlers: new Map(), logger: undefined as unknown as winston.Logger, unhandle: jest.fn(), }), exitOnError: false, format: { transform: jest.fn(), options: {}, }, getMaxListeners: jest.fn(), help: jest.fn(), http: jest.fn(), info: jest.fn(), input: jest.fn(), isDebugEnabled: jest.fn().mockReturnValue(true), isErrorEnabled: jest.fn().mockReturnValue(true), isInfoEnabled: jest.fn().mockReturnValue(true), isLevelEnabled: jest .fn() .mockImplementation( (level: string) => level === 'info' || level === 'error' || level === 'debug' || level === 'warn', ), isPaused: jest.fn().mockReturnValue(false), isWarnEnabled: jest.fn().mockReturnValue(true), isSillyEnabled: jest.fn().mockReturnValue(false), isVerboseEnabled: jest.fn().mockReturnValue(false), level: 'debug', levels: { silly: 0, debug: 1, verbose: 2, info: 3, warn: 4, error: 5, silent: 6, }, listenerCount: jest.fn(), listeners: jest.fn(), log: jest.fn(), notice: jest.fn(), off: jest.fn(), on: jest.fn(), once: jest.fn(), pause: jest.fn(), pipe: jest.fn(), prependListener: jest.fn(), prependOnceListener: jest.fn(), profile: jest.fn(), profilers: {}, prompt: jest.fn(), push: jest.fn(), query: jest.fn(), rawListeners: jest.fn(), read: jest.fn(), readable: true, readableAborted: false, readableDidRead: true, readableEncoding: 'utf8' as BufferEncoding, readableEnded: false, readableFlowing: true, readableHighWaterMark: 16, readableLength: 0, readableObjectMode: false, remove: jest.fn(), removeAllListeners: jest.fn(), removeListener: jest.fn(), resume: jest.fn(), setDefaultEncoding: jest.fn(), setEncoding: jest.fn(), setMaxListeners: jest.fn(), silent: false, silly: jest.fn(), startTimer: jest.fn(), stream: jest.fn(), transports: [], uncork: jest.fn(), unpipe: jest.fn(), unshift: jest.fn(), verbose: jest.fn(), warn: jest.fn(), warning: jest.fn(), wrap: jest.fn(), write: jest.fn(), writable: true, writableCorked: 0, writableEnded: false, writableFinished: false, writableHighWaterMark: 16, writableLength: 0, writableObjectMode: false, }); Object.defineProperty(logger.exceptions, 'logger', { get: () => logger, }); return logger; } export type MockTextDocuments = { __typed: () => TextDocuments<TextDocument>; all: JestFn; get: JestFn; keys: JestFn; listen: JestFn; onDidChangeContent: JestFn; onDidClose: JestFn; onDidOpen: JestFn; onDidSave: JestFn; onWillSave: JestFn; onWillSaveWaitUntil: JestFn; }; /** * Returns a mock text document manager. */ export function getTextDocuments(): MockTextDocuments { const documents: MockTextDocuments = { __typed: () => documents as unknown as TextDocuments<TextDocument>, all: jest.fn(), get: jest.fn(), keys: jest.fn(), listen: jest.fn(), onDidChangeContent: jest.fn(), onDidClose: jest.fn(), onDidOpen: jest.fn(), onDidSave: jest.fn(), onWillSave: jest.fn(), onWillSaveWaitUntil: jest.fn(), }; return documents; } export type MockCommandManager = { __typed: () => CommandManager; on: JestFn; register: JestFn; }; /** * Returns a mock command manager. */ export function getCommandManager(): MockCommandManager { const manager: MockCommandManager = { __typed: () => manager as unknown as CommandManager, on: jest.fn(), register: jest.fn(), }; return manager; } export type MockNotificationManager = { __typed: () => NotificationManager; on: JestFn; }; /** * Returns a mock notification manager. */ export function getNotificationManager(): MockNotificationManager { const manager: MockNotificationManager = { __typed: () => manager as unknown as NotificationManager, on: jest.fn(), }; return manager; } export type MockStylelintRunner = { __typed: () => StylelintRunner; lintDocument: JestFn; }; /** * Returns a mock Stylelint runner. */ export function getStylelintRunner(): MockStylelintRunner { const runner: MockStylelintRunner = { __typed: () => runner as unknown as StylelintRunner, lintDocument: jest.fn(), }; return runner; } /** * Returns mock language server options. */ export function getOptions(): LanguageServerOptions { return { codeAction: { disableRuleComment: { location: 'separateLine', }, }, config: null, configFile: '', configBasedir: '', customSyntax: '', ignoreDisables: false, packageManager: 'npm', reportInvalidScopeDisables: false, reportNeedlessDisables: false, snippet: ['css', 'postcss'], stylelintPath: '', validate: ['css', 'postcss'], }; } export type MockLanguageServerContext = { __typed: () => LanguageServerContext; __options: LanguageServerOptions; connection: MockConnection; documents: MockTextDocuments; commands: MockCommandManager; notifications: MockNotificationManager; runner: MockStylelintRunner; displayError: JestFn; getOptions: jest.MockedFunction<() => Promise<LanguageServerOptions>>; getFixes: JestFn; getModule: JestFn; lintDocument: JestFn; resolveStylelint: JestFn; }; /** * Returns a mock language server context. */ export function getContext(): MockLanguageServerContext { const context: MockLanguageServerContext = { __typed: () => context as unknown as LanguageServerContext, __options: getOptions(), connection: getConnection(), documents: getTextDocuments(), commands: getCommandManager(), notifications: getNotificationManager(), runner: getStylelintRunner(), displayError: jest.fn(), getOptions: jest.fn().mockImplementation(async () => context.__options), getFixes: jest.fn(), getModule: jest.fn(), lintDocument: jest.fn(), resolveStylelint: jest.fn(), }; return context; }
the_stack
import {System} from "./generic"; import {snakeCase} from "change-case"; import uuid from "uuid"; class CountermeasureResources { copper?: number; titanium?: number; carbon?: number; plastic?: number; plasma?: number; [key: string]: number; constructor({copper = 0, titanium = 0, carbon = 0, plastic = 0, plasma = 0}) { this.copper = copper; this.titanium = titanium; this.carbon = carbon; this.plastic = plastic; this.plasma = plasma; } } class CountermeasureModule { id?: string; name: string; description: string; powerRequirement?: number; resourceRequirements: CountermeasureResources; configurationOptions?: {type: string; label: string}[]; config?: any; buildProgress?: number; activated?: boolean; constructor({ id, name, description, resourceRequirements, powerRequirement = 0, configurationOptions = [], config = {}, buildProgress = 0, activated = false, }: Partial<CountermeasureModule>) { this.id = id || snakeCase(name); this.name = name; this.description = description; this.powerRequirement = powerRequirement; this.resourceRequirements = new CountermeasureResources( resourceRequirements, ); this.configurationOptions = configurationOptions; this.config = config; this.buildProgress = buildProgress; this.activated = activated; } activate() { this.activated = true; } } export const moduleTypes = [ new CountermeasureModule({ name: "Heat Coil", description: "Generates heat. Can be configured to pulse or produce a constant heat signature. This can mimic the heat signature of a ship.", resourceRequirements: {copper: 3, carbon: 2}, powerRequirement: 1, configurationOptions: [ {type: "Pulse:Constant", label: "Mode"}, {type: "Trigger", label: "Trigger"}, ], }), new CountermeasureModule({ name: "Explosive Payload", description: "When activated, it explodes. Do not activate immediately upon launch. When activated, it will destroy the countermeasure.", resourceRequirements: {copper: 2, plasma: 3}, configurationOptions: [{type: "Trigger", label: "Trigger"}], }), new CountermeasureModule({ name: "Communications Array", description: "Broadcasts a repeating signal at a pre-defined frequency. The message in the signal can be pre-configured.", resourceRequirements: {copper: 2, titanium: 1, plastic: 1}, powerRequirement: 0.25, configurationOptions: [ {type: "Number", label: "Frequency"}, {type: "TextArea", label: "Message"}, {type: "Trigger", label: "Trigger"}, ], }), new CountermeasureModule({ name: "Battery Cell", description: "Provides power to other modules. More battery cells provide longer use of modules.", resourceRequirements: {carbon: 1, titanium: 2, plasma: 3}, configurationOptions: [{type: "Trigger", label: "Trigger"}], }), new CountermeasureModule({ name: "Sensor Scrambler", description: "Scrambles signals on the sensor grid. Can also be used to disrupt communication signals.", resourceRequirements: {copper: 1, plasma: 2, plastic: 1}, powerRequirement: 0.5, configurationOptions: [{type: "Trigger", label: "Trigger"}], }), new CountermeasureModule({ name: "Transport Inhibitor", description: "Blocks or limits the ability of nearby ships to use transporter systems.", resourceRequirements: {copper: 1, plasma: 2, titanium: 3}, powerRequirement: 0.75, configurationOptions: [{type: "Trigger", label: "Trigger"}], }), new CountermeasureModule({ name: "Ionizer", description: "Creates a cloud of particles which simulates the trail left by a small starship.", resourceRequirements: {plasma: 1, carbon: 1, titanium: 1}, powerRequirement: 0.25, configurationOptions: [{type: "Trigger", label: "Trigger"}], }), new CountermeasureModule({ name: "Chaff Deploy", description: "Releases a large amount of debris around the countermeasure. This can be used to block incoming explosive projectiles.", resourceRequirements: {carbon: 3, titanium: 1}, powerRequirement: 0.25, configurationOptions: [{type: "Trigger", label: "Trigger"}], }), new CountermeasureModule({ name: "Proximity Trigger", description: "Detects when ships approach. Other modules can use this to trigger their activation.", resourceRequirements: {copper: 1, titanium: 1, plastic: 3}, powerRequirement: 0.25, }), new CountermeasureModule({ name: "Scan Trigger", description: "Detects when the module is scanned. Other modules can use this to trigger their activation.", resourceRequirements: {copper: 1, titanium: 1, plastic: 3}, powerRequirement: 0.25, }), new CountermeasureModule({ name: "Beacon", description: "Sends out a pulse which can be used by navigation to locate the module.", resourceRequirements: {plasma: 1, carbon: 1, copper: 2}, powerRequirement: 0.5, configurationOptions: [{type: "Trigger", label: "Trigger"}], }), new CountermeasureModule({ name: "Notifier", description: "Uses encrypted, entangled quantum particles to securely send a message back to your station.", resourceRequirements: {plasma: 1, carbon: 1, titanium: 1, copper: 1}, configurationOptions: [ {type: "Trigger", label: "Trigger"}, {type: "TextArea", label: "Message"}, ], }), ]; class CountermeasureSlots { slot1: Countermeasure | null; slot2: Countermeasure | null; slot3: Countermeasure | null; slot4: Countermeasure | null; slot5: Countermeasure | null; slot6: Countermeasure | null; slot7: Countermeasure | null; slot8: Countermeasure | null; [key: string]: Countermeasure | null; constructor(params: CountermeasureSlots) { this.slot1 = params?.slot1 ? new Countermeasure(params.slot1) : null; this.slot2 = params?.slot2 ? new Countermeasure(params.slot2) : null; this.slot3 = params?.slot3 ? new Countermeasure(params.slot3) : null; this.slot4 = params?.slot4 ? new Countermeasure(params.slot4) : null; this.slot5 = params?.slot5 ? new Countermeasure(params.slot5) : null; this.slot6 = params?.slot6 ? new Countermeasure(params.slot6) : null; this.slot7 = params?.slot7 ? new Countermeasure(params.slot7) : null; this.slot8 = params?.slot8 ? new Countermeasure(params.slot8) : null; } } export class Countermeasures extends System { type = "Countermeasures"; class = "Countermeasures"; storedMaterials: CountermeasureResources; slots: CountermeasureSlots; launched: Countermeasure[]; constructor(params: Partial<Countermeasures> = {}) { super({displayName: "Countermeasures", name: "Countermeasures", ...params}); this.class = "Countermeasures"; this.type = "Countermeasures"; this.wing = params.wing || "left"; this.storedMaterials = new CountermeasureResources( params.storedMaterials || { copper: 99, titanium: 99, carbon: 99, plastic: 99, plasma: 99, }, ); this.slots = new CountermeasureSlots(params.slots); this.launched = []; params.launched?.forEach(l => this.launched.push(new Countermeasure(l))); } get materials() { const usedMaterials = Object.entries(this.slots).reduce( (prev, [, slot]) => { slot?.modules.forEach(mod => { prev.copper += (mod.resourceRequirements.copper || 0) * mod.buildProgress; prev.carbon += (mod.resourceRequirements.carbon || 0) * mod.buildProgress; prev.plasma += (mod.resourceRequirements.plasma || 0) * mod.buildProgress; prev.plastic += (mod.resourceRequirements.plastic || 0) * mod.buildProgress; prev.titanium += (mod.resourceRequirements.titanium || 0) * mod.buildProgress; }); return prev; }, {copper: 0, carbon: 0, plasma: 0, plastic: 0, titanium: 0}, ); return { copper: this.storedMaterials.copper - usedMaterials.copper, carbon: this.storedMaterials.carbon - usedMaterials.carbon, plasma: this.storedMaterials.plasma - usedMaterials.plasma, plastic: this.storedMaterials.plastic - usedMaterials.plastic, titanium: this.storedMaterials.titanium - usedMaterials.titanium, }; } setResource(resource, value) { this.storedMaterials[resource] = value; } createCountermeasure(slot: string, name: string) { const countermeasure = new Countermeasure({id: uuid.v4(), name}); this.slots[slot] = countermeasure; } removeCountermeasure(slot) { if (this.slots[slot]) { const countermeasure: Countermeasure = this.slots[slot]; this.slots[slot] = null; // Remove all of the unused materials from the countermeasure modules countermeasure.modules.forEach(m => { // Half the build progress so at least some materials are recycled. const usedMaterialValue = m.buildProgress * 0.5; Object.entries(m.resourceRequirements).forEach(([key, value]) => { this.storedMaterials[key] = Math.round( this.storedMaterials[key] - usedMaterialValue * value, ); }); }); } } launchCountermeasure(slot) { if (this.slots[slot]?.readyToLaunch) { // For now, activate all of the modules when launched. // TODO: When the Universal Sandbox is completed, // make them know when and how to activate properly. this.slots[slot].modules.forEach(m => m.activate()); this.launched.push(this.slots[slot]); // Properly remove the materials that were used. const countermeasure: Countermeasure = this.slots[slot]; this.slots[slot] = null; countermeasure.modules.forEach(m => { const usedMaterialValue = m.buildProgress; Object.entries(m.resourceRequirements).forEach(([key, value]) => { this.storedMaterials[key] = Math.round( this.storedMaterials[key] - usedMaterialValue * value, ); }); }); } } buildCountermeasure(slot) { this.slots[slot]?.build(); } addCountermeasureModule(slot, moduleType) { const countermeasure = this.slots[slot]; countermeasure?.addModule(moduleType); return countermeasure; } removeCountermeasureModule(slot, id) { this.slots[slot]?.removeModule(id); } configureCountermeasureModule(slot, id, config) { this.slots[slot]?.configureModule(id, config); } setSlotActivation(slot, active) { this.slots[slot]?.setActive(active); } setFDNote(id, note) { const cm = this.launched.find(l => l.id === id) || Object.values(this.slots).find(s => s?.id === id); cm?.setNote(note); } } class Countermeasure { id: string; name: string; modules: CountermeasureModule[]; locked: boolean; active: boolean; building: boolean; totalPowerUsed: number; note: string; constructor(params: Partial<Countermeasure>) { this.id = params.id || uuid.v4(); this.name = params.name || "Countermeasure"; this.modules = []; params.modules?.forEach(m => this.modules.push(new CountermeasureModule(m)), ); this.locked = params.locked || false; this.active = params.active || false; this.building = params.building || false; this.totalPowerUsed = params.totalPowerUsed || 0; this.note = params.note || ""; } get readyToLaunch() { // If we have a module and all of the modules are built, then the countermeasure is ready to launch. return ( this.modules.length > 0 && this.modules.reduce((acc, next) => { if (!acc) return false; if (next.buildProgress < 1) return false; return true; }, true) ); } get powerUsage() { return this.modules.reduce((acc, mod) => { return acc + (mod.powerRequirement || 0); }, 0); } get availablePower() { // Each battery provides 1 unit of power for one unit of power usage. // Countermeasures come with half a unit worth of power by default. return this.modules.filter(f => f.name === "Battery Cell").length + 0.5; } get buildPercentage() { if (this.modules.length === 0) return 0; return ( this.modules.reduce( (acc, m) => (m.buildProgress ? m.buildProgress + acc : acc), 0, ) / this.modules.length ); } usePower(amount) { if (!this.active) return; if (this.totalPowerUsed >= this.availablePower) { this.active = false; return; } // Multiply the amount by the power usage this.totalPowerUsed += amount * this.powerUsage; } build() { this.building = true; } setActive(tf) { this.active = tf; } addModule(moduleType) { if (!this.building) { const mod = moduleTypes.find( m => m.name === moduleType || m.id === moduleType, ); if (!mod) return; this.modules.push(new CountermeasureModule({...mod, id: uuid.v4()})); } } removeModule(id) { if (!this.building) { this.modules = this.modules.filter(m => m.id !== id); } } configureModule(id, config) { if (!this.building) { const mod = this.modules.find(m => m.id === id); if (mod) { mod.config = config; } } } activateModule(id) { this.modules.find(m => m.id === id)?.activate(); } setNote(note) { this.note = note; } }
the_stack
'use strict'; import { WickedInitOptions, Callback, WickedGlobals, WickedGetOptions, WickedGetCollectionOptions, WickedAwaitOptions, WickedUserInfo, ErrorCallback, WickedSubscriptionInfo } from "./interfaces"; import { WickedError } from "./wicked-error"; import * as async from 'async'; import * as semver from 'semver'; /** @hidden */ const os = require('os'); /** @hidden */ const request = require('request'); /** @hidden */ const containerized = require('containerized'); /** @hidden */ const debug = require('debug')('wicked-sdk'); /** @hidden */ const qs = require('querystring'); /** @hidden */ const isLinux = (os.platform() === 'linux'); /** @hidden */ const isContainerized = isLinux && containerized(); const WICKED_TIMEOUT = 10000; // request timeout for wicked API operations const TRYGET_TIMEOUT = 5000; // request timeout for single calls in awaitUrl // ====== VARIABLES ====== /** @hidden */ const EMPTY_STORAGE = { initialized: false, kongAdapterInitialized: false, machineUserId: null, apiUrl: null, globals: null, configHash: null, userAgent: null, pendingExit: false, apiReachable: false, isPollingApi: false, // This field will not necessarily be filled. apiVersion: null, isV012OrHigher: false, isV100OrHigher: false, portalApiScope: null, apiMaxTries: 10, apiRetryDelay: 500 }; /** * Use this for local caching of things. Usually just the globals. * The apiUrl will - after initialization - contain the URL which * was used to access the portal API with. * @hidden */ let wickedStorage = _clone(EMPTY_STORAGE); /** * This is used for passing the correlation ID from the correlation handler. * @hidden */ export const requestRuntime = { correlationId: null }; // ==================== // INTERNAL TYPES // ==================== /** @hidden */ interface RequestBody { method: string, url: string, headers?: { [headerName: string]: string } timeout?: number, json?: boolean, body?: any } // ======= IMPLEMENTATION ====== /** @hidden */ export function _initialize(options: WickedInitOptions, callback?: Callback<WickedGlobals>) { debug('initialize()'); if (!callback && (typeof (options) === 'function')) { callback = options; options = null; } const func = _initialize; if (!callback) { return new Promise(function (resolve, reject) { func(options, function (err, g) { err ? reject(err) : resolve(g); }); }); } // Reset the storage when (re-)initializing wickedStorage = _clone(EMPTY_STORAGE); if (options) { debug('options:'); debug(options); if (options.apiMaxTries) { wickedStorage.apiMaxTries = options.apiMaxTries; wickedStorage.apiRetryDelay = options.apiRetryDelay; } } const validationError = validateOptions(options); if (validationError) { return callback(validationError); } // I know, this would look a lot nicer with async or Promises, // but I did not want to pull in additional dependencies. const apiUrl = resolveApiUrl(); debug('Awaiting portal API at ' + apiUrl); _awaitUrl(apiUrl + 'ping', options, function (err, pingResult) { if (err) { debug('awaitUrl returned an error:'); debug(err); return callback(err); } debug('Ping result:'); debug(pingResult); const pingJson = getJson(pingResult); if (pingJson.version) { // The version field is not filled until wicked 0.12.0 wickedStorage.apiVersion = pingJson.version; wickedStorage.isV012OrHigher = true; if (pingJson.version >= '1.0.0') { wickedStorage.isV100OrHigher = true; } } wickedStorage.apiUrl = apiUrl; if (options.userAgentName && options.userAgentVersion) wickedStorage.userAgent = options.userAgentName + '/' + options.userAgentVersion; request.get({ url: apiUrl + 'confighash', timeout: WICKED_TIMEOUT }, function (err, res, body) { if (err) { debug('GET /confighash failed.'); debug(err); return callback(err); } if (200 != res.statusCode) { debug('GET /confighash returned status code: ' + res.statusCode); debug('Body: ' + body); return callback(new Error('GET /confighash returned unexpected status code: ' + res.statusCode + ' (Body: ' + body + ')')); } wickedStorage.configHash = '' + body; request.get({ url: apiUrl + 'globals', headers: { 'User-Agent': wickedStorage.userAgent, 'X-Config-Hash': wickedStorage.configHash }, timeout: WICKED_TIMEOUT }, function (err, res, body) { if (err) { debug('GET /globals failed'); debug(err); return callback(err); } if (res.statusCode !== 200) { debug('GET /globals returned status code ' + res.statusCode); return callback(new Error('GET /globals return unexpected error code: ' + res.statusCode)); } let globals = null; try { globals = getJson(body); wickedStorage.globals = globals; wickedStorage.initialized = true; wickedStorage.apiReachable = true; } catch (ex) { return callback(new Error('Parsing globals failed: ' + ex.message)); } // Success, set up config hash checker loop (if not switched off) if (!options.doNotPollConfigHash) { wickedStorage.isPollingApi = true; setInterval(checkConfigHash, 10000); } return callback(null, globals); }); }); }); } /** @hidden */ function _clone(o) { return JSON.parse(JSON.stringify(o)); } /** @hidden */ export function validateOptions(options) { if ((options.userAgentName && !options.userAgentVersion) || (!options.userAgentName && options.userAgentVersion)) return new Error('You need to specify both userAgentName and userAgentVersion'); if (options.userAgentName && !/^[a-zA-Z\ \-\_\.0-9]+$/.test(options.userAgentName)) return new Error('The userAgentName must only contain characters a-z, A-Z, 0-9, -, _ and space.'); if (options.userAgentVersion && semver.valid(options.userAgentVersion) == null) return new Error(`The userAgentVersion ${options.userAgentVersion} is not a valid semver (see http://semver.org)`); return null; } /** @hidden */ export function validateGetOptions(options: WickedGetOptions): WickedGetOptions { const o = {} as WickedGetOptions; if (options) { if (options.offset) o.offset = options.offset; if (options.limit) o.limit = options.limit; } return o; } /** @hidden */ export function validateGetCollectionOptions(options: WickedGetCollectionOptions): WickedGetCollectionOptions { const o = {} as WickedGetCollectionOptions; if (options) { if (options.filter) o.filter = options.filter; if (options.offset) o.offset = options.offset; if (options.limit) o.limit = options.limit; if (options.order_by) o.order_by = options.order_by; if (options.no_cache) o.no_cache = options.no_cache; } return o; } /** @hidden */ export function checkConfigHash() { debug('checkConfigHash()'); request.get({ url: wickedStorage.apiUrl + 'confighash', timeout: WICKED_TIMEOUT }, function (err, res, body) { wickedStorage.apiReachable = false; if (err) { console.error('checkConfigHash(): An error occurred.'); console.error(err); console.error(err.stack); return; } if (200 !== res.statusCode) { console.error('checkConfigHash(): Returned unexpected status code: ' + res.statusCode); return; } wickedStorage.apiReachable = true; const configHash = '' + body; if (configHash !== wickedStorage.configHash) { console.log('checkConfigHash() - Detected new configuration version, scheduling shutdown in 2 seconds.'); wickedStorage.pendingExit = true; setTimeout(forceExit, 2000); } }); } /** @hidden */ export function forceExit() { console.log('Exiting component due to outdated configuration (confighash mismatch).'); process.exit(0); } /** @hidden */ export function _isApiReachable() { checkInitialized('isApiReachable'); if (!wickedStorage.isPollingApi) throw new Error('isApiReachable() can only be used if wicked-sdk is polling the API continuously (option "doNotPollConfigHash").') return wickedStorage.apiReachable; } /** @hidden */ export function _isDevelopmentMode() { checkInitialized('isDevelopmentMode'); if (wickedStorage.globals && wickedStorage.globals.network && wickedStorage.globals.network.schema && wickedStorage.globals.network.schema === 'https') return false; return true; } const DEFAULT_AWAIT_OPTIONS = { statusCode: 200, maxTries: 100, retryDelay: 1000 }; /** @hidden */ export function _awaitUrl(url: string, options: WickedAwaitOptions, callback?: Callback<any>): void | Promise<any> { debug('awaitUrl(): ' + url); if (!callback && (typeof (options) === 'function')) { callback = options; options = null; } const func = _awaitUrl; if (!callback) { return new Promise(function (resolve, reject) { func(url, options, function (err, result) { err ? reject(err) : resolve(result); }); }); } // Copy the settings from the defaults; otherwise we'd change them haphazardly const awaitOptions: WickedAwaitOptions = { statusCode: DEFAULT_AWAIT_OPTIONS.statusCode, maxTries: DEFAULT_AWAIT_OPTIONS.maxTries, retryDelay: DEFAULT_AWAIT_OPTIONS.retryDelay }; if (options) { if (options.statusCode) awaitOptions.statusCode = options.statusCode; if (options.maxTries) awaitOptions.maxTries = options.maxTries; if (options.retryDelay) awaitOptions.retryDelay = options.retryDelay; } debug('Invoking tryGet()'); tryGet(url, awaitOptions.statusCode, awaitOptions.maxTries, 0, awaitOptions.retryDelay, function (err, body) { debug('tryGet() returned.'); if (err) { debug('but tryGet() errored.'); debug(err); return callback(err); } callback(null, body); }); } /** @hidden */ export function _awaitKongAdapter(awaitOptions, callback?): void | Promise<any> { debug('awaitKongAdapter()'); checkInitialized('awaitKongAdapter'); if (!callback && (typeof (awaitOptions) === 'function')) { callback = awaitOptions; awaitOptions = null; } const func = _awaitKongAdapter; if (!callback) { return new Promise(function (resolve, reject) { func(awaitOptions, function (err, result) { err ? reject(err) : resolve(result); }); }); } if (awaitOptions) { debug('awaitOptions:'); debug(awaitOptions); } const adapterPingUrl = _getInternalKongAdapterUrl() + 'ping'; _awaitUrl(adapterPingUrl, awaitOptions, function (err, body) { if (err) return callback(err); wickedStorage.kongAdapterInitialized = true; return callback(null, body); }); } /** @hidden */ export function _initMachineUser(serviceId: string, callback?: ErrorCallback): void | Promise<any> { debug('initMachineUser()'); checkInitialized('initMachineUser'); const func = _initMachineUser; if (!callback) { return new Promise(function (resolve, reject) { func(serviceId, function (err) { err ? reject(err) : resolve(); }); }); } retrieveOrCreateMachineUser(serviceId, (err, _) => { if (err) return callback(err); // wickedStorage.machineUserId has been filled now; // now we want to retrieve the API scopes of portal-api. return initPortalApiScopes(callback); }); } /** @hidden */ export function retrieveOrCreateMachineUser(serviceId: string, callback: Callback<WickedUserInfo>) { debug('retrieveOrCreateMachineUser()'); if (!/^[a-zA-Z\-_0-9]+$/.test(serviceId)) return callback(new Error('Invalid Service ID, must only contain a-z, A-Z, 0-9, - and _.')); const customId = makeMachineUserCustomId(serviceId); _apiGet('users?customId=' + qs.escape(customId), null, 'read_users', function (err, userInfo) { if (err && err.statusCode == 404) { // Not found return createMachineUser(serviceId, callback); } else if (err) { return callback(err); } if (!Array.isArray(userInfo)) return callback(new Error('GET of user with customId ' + customId + ' did not return expected array.')); if (userInfo.length !== 1) return callback(new Error('GET of user with customId ' + customId + ' did not return array of length 1 (length == ' + userInfo.length + ').')); userInfo = userInfo[0]; // Pick the user from the list. storeMachineUser(userInfo); return callback(null, userInfo); }); } /** @hidden */ export function storeMachineUser(userInfo) { debug('Machine user info:'); debug(userInfo); debug('Setting machine user id: ' + userInfo.id); wickedStorage.machineUserId = userInfo.id; } /** @hidden */ function makeMachineUserCustomId(serviceId) { const customId = 'internal:' + serviceId; return customId; } /** @hidden */ export function createMachineUser(serviceId, callback) { const customId = makeMachineUserCustomId(serviceId); const userInfo = { customId: customId, firstName: 'Machine-User', lastName: serviceId, email: serviceId + '@wicked.haufe.io', validated: true, groups: ['admin'] }; _apiPost('users/machine', userInfo, null, function (err, userInfo) { if (err) return callback(err); storeMachineUser(userInfo); return callback(null, userInfo); }); } /** @hidden */ function initPortalApiScopes(callback) { debug('initPortalApiScopes()'); if (!wickedStorage.machineUserId) return callback(new Error('initPortalApiScopes: Machine user id not initialized.')); _apiGet('apis/portal-api', null, 'read_apis', (err, apiInfo) => { if (err) return callback(err); debug(apiInfo); if (!apiInfo.settings) return callback(new Error('initPortalApiScope: Property settings not found.')); if (!apiInfo.settings.scopes) return callback(new Error('initPortalApiScope: Property settings.scopes not found.')); const scopeList = []; for (let scope in apiInfo.settings.scopes) { scopeList.push(scope); } wickedStorage.portalApiScope = scopeList.join(' '); debug(`initPortalApiScopes: Full API Scope: "${wickedStorage.portalApiScope}"`); return callback(null); }); } /** @hidden */ export function _getGlobals() { debug('getGlobals()'); checkInitialized('getGlobals'); return wickedStorage.globals; } /** @hidden */ export function _getConfigHash() { debug('getConfigHash()'); checkInitialized('getConfigHash'); return wickedStorage.configHash; } /** @hidden */ export function _getExternalPortalHost() { debug('getExternalPortalHost()'); checkInitialized('getExternalPortalHost'); return checkNoSlash(getPortalHost()); } /** @hidden */ export function _getExternalPortalUrl() { debug('getExternalPortalUrl()'); checkInitialized('getExternalPortalUrl'); return checkSlash(_getSchema() + '://' + getPortalHost()); } /** @hidden */ export function _getExternalGatewayHost() { debug('getExternalGatewayHost()'); checkInitialized('getExternalGatewayHost()'); return checkNoSlash(getApiHost()); } /** @hidden */ export function _getExternalGatewayUrl() { debug('getExternalGatewayUrl()'); checkInitialized('getExternalGatewayUrl'); return checkSlash(_getSchema() + '://' + getApiHost()); } /** @hidden */ export function _getInternalApiUrl() { debug('getInternalApiUrl()'); checkInitialized('getInternalApiUrl'); return checkSlash(wickedStorage.apiUrl); } /** @hidden */ export function _getPortalApiScope() { debug('getPortalApiScope()'); checkInitialized('getPortalApiScope'); if (wickedStorage.isV100OrHigher && wickedStorage.portalApiScope) return wickedStorage.portalApiScope; debug('WARNING: portalApiScope is not defined, or wicked API is <1.0.0'); return ''; } /** @hidden */ export function _getInternalPortalUrl() { debug('getInternalPortalUrl()'); checkInitialized('getInternalPortalUrl'); return _getInternalUrl('portalUrl', 'portal', 3000); } /** @hidden */ export function _getInternalKongAdminUrl() { debug('getInternalKongAdminUrl()'); checkInitialized('getInternalKongAdminUrl'); return _getInternalUrl('kongAdminUrl', 'kong', 8001); } /** @hidden */ export function _getInternalKongProxyUrl() { debug('getInternalKongProxyUrl()'); checkInitialized('getInternalKongProxyUrl'); // Check if it's there, but only if the property is present if (wickedStorage.globals.network && wickedStorage.globals.network.kongProxyUrl) { try { const proxyUrl = _getInternalUrl('kongProxyUrl', 'kong', 8000); if (proxyUrl && proxyUrl !== '' && proxyUrl !== '/') return proxyUrl; } catch (ex) { debug(ex); } } debug(`globals.json: network.kongProxyUrl is not defined, falling back to admin URL.`) // Fallback: Deduce from Kong Admin URL const adminUrl = _getInternalKongAdminUrl(); return adminUrl.replace(/8001/, '8000'); } /** @hidden */ export function _getInternalMailerUrl() { debug('getInternalMailerUrl'); checkInitialized('getInternalMailerUrl'); return _getInternalUrl('mailerUrl', 'portal-mailer', 3003); } /** @hidden */ export function _getInternalChatbotUrl() { debug('getInternalChatbotUrl()'); checkInitialized('getInternalChatbotUrl'); return _getInternalUrl('chatbotUrl', 'portal-chatbot', 3004); } /** @hidden */ export function _getInternalKongAdapterUrl() { debug('getInternalKongAdapterUrl()'); checkInitialized('getInternalKongAdapterUrl'); return _getInternalUrl('kongAdapterUrl', 'portal-kong-adapter', 3002); } /** @hidden */ export function _getInternalKongOAuth2Url() { debug('getInternalKongOAuth2Url()'); checkInitialized('getInternalKongOAuth2Url'); return _getInternalUrl('kongOAuth2Url', 'portal-kong-oauth2', 3006); } /** @hidden */ export function _getInternalUrl(globalSettingsProperty: string, defaultHost: string, defaultPort: number) { debug('getInternalUrl("' + globalSettingsProperty + '")'); checkInitialized('getInternalUrl'); if (wickedStorage.globals.network && wickedStorage.globals.network.hasOwnProperty(globalSettingsProperty)) { return checkSlash(wickedStorage.globals.network[globalSettingsProperty]); } if (defaultHost && defaultPort) return checkSlash(guessServiceUrl(defaultHost, defaultPort)); throw new Error('Configuration property "' + globalSettingsProperty + '" not defined in globals.json: network.'); } /** @hidden */ export function _getKongAdapterIgnoreList(): string[] { debug('getKongAdapterIgnoreList()'); checkInitialized('getKongAdapterIgnoreList'); const glob = wickedStorage.globals as WickedGlobals; if (glob.kongAdapter && glob.kongAdapter.useKongAdapter && glob.kongAdapter.ignoreList) { return glob.kongAdapter.ignoreList; } return []; } /** @hidden */ export function _getApiKeyHeader(): string { debug('getApiKeyHeader()'); checkInitialized('getApiKeyHeader'); const glob = wickedStorage.globals as WickedGlobals; if (glob.api && glob.api.headerName) return glob.api.headerName; return 'X-ApiKey'; } /** @hidden */ export function _getPasswordStrategy(): string { debug('getPasswordStrategy()'); checkInitialized('getPasswordStrategy()'); const glob = wickedStorage.globals as WickedGlobals; if (glob.passwordStrategy) return glob.passwordStrategy; return 'PW_6_24'; } // ======= UTILITY FUNCTIONS ====== /** @hidden */ function checkSlash(someUrl) { if (someUrl.endsWith('/')) return someUrl; return someUrl + '/'; } /** @hidden */ function checkNoSlash(someUrl) { if (someUrl.endsWith('/')) return someUrl.substring(0, someUrl.length - 1); return someUrl; } /** @hidden */ export function _getSchema() { checkInitialized('getSchema'); if (wickedStorage.globals.network && wickedStorage.globals.network.schema) return wickedStorage.globals.network.schema; console.error('In globals.json, network.schema is not defined. Defaulting to https.'); return 'https'; } /** @hidden */ export function getPortalHost() { if (wickedStorage.globals.network && wickedStorage.globals.network.portalHost) return wickedStorage.globals.network.portalHost; throw new Error('In globals.json, portalHost is not defined. Cannot return any default.'); } /** @hidden */ export function getApiHost() { if (wickedStorage.globals.network && wickedStorage.globals.network.apiHost) return wickedStorage.globals.network.apiHost; throw new Error('In globals.json, apiHost is not defined. Cannot return any default.'); } /** @hidden */ export function checkInitialized(callingFunction) { if (!wickedStorage.initialized) throw new Error('Before calling ' + callingFunction + '(), initialize() must have been called and has to have returned successfully.'); } /** @hidden */ export function checkKongAdapterInitialized(callingFunction) { if (!wickedStorage.kongAdapterInitialized) throw new Error('Before calling ' + callingFunction + '(), awaitKongAdapter() must have been called and has to have returned successfully.'); } /** @hidden */ function guessServiceUrl(defaultHost, defaultPort) { debug('guessServiceUrl() - defaultHost: ' + defaultHost + ', defaultPort: ' + defaultPort); let url = 'http://' + defaultHost + ':' + defaultPort + '/'; // Are we not running containerized? Then guess we're in local development mode. if (!isContainerized) { const defaultLocalIP = getDefaultLocalIP(); url = 'http://' + defaultLocalIP + ':' + defaultPort + '/'; } debug(url); return url; } /** @hidden */ function resolveApiUrl() { let apiUrl = process.env.PORTAL_API_URL; if (!apiUrl) { apiUrl = guessServiceUrl('portal-api', '3001'); console.error('Environment variable PORTAL_API_URL is not set, defaulting to ' + apiUrl + '. If this is not correct, please set before starting this process.'); } if (!apiUrl.endsWith('/')) // Add trailing slash apiUrl += '/'; return apiUrl; } /** @hidden */ function getDefaultLocalIP() { const localIPs = getLocalIPs(); if (localIPs.length > 0) return localIPs[0]; return "localhost"; } /** @hidden */ function getLocalIPs() { debug('getLocalIPs()'); const interfaces = os.networkInterfaces(); const addresses = []; for (let k in interfaces) { for (let k2 in interfaces[k]) { const address = interfaces[k][k2]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } debug(addresses); return addresses; } /** @hidden */ function tryGet(url, statusCode, maxTries, tryCounter, timeout, callback) { debug('Try #' + tryCounter + ' to GET ' + url); request.get({ url: url, timeout: TRYGET_TIMEOUT }, function (err, res, body) { if (err || res.statusCode !== statusCode) { if (tryCounter < maxTries || maxTries < 0) return setTimeout(tryGet, timeout, url, statusCode, maxTries, tryCounter + 1, timeout, callback); debug('Giving up.'); if (!err) err = new Error('Too many unsuccessful retries to GET ' + url + '. Gave up after ' + maxTries + ' tries.'); return callback(err); } callback(null, body); }); } /** @hidden */ function getJson(ob) { if (typeof ob === "string") return JSON.parse(ob); return ob; } /** @hidden */ function getText(ob) { if (ob instanceof String || typeof ob === "string") return ob; return JSON.stringify(ob, null, 2); } /** @hidden */ export function _apiGet(urlPath, userId, scope, callback) { debug('apiGet(): ' + urlPath); checkInitialized('apiGet'); if (arguments.length !== 4 && arguments.length !== 3) throw new Error('apiGet was called with wrong number of arguments'); return apiAction('GET', urlPath, null, userId, scope, callback); } /** @hidden */ export function _apiPost(urlPath, postBody, userId, callback) { debug('apiPost(): ' + urlPath); checkInitialized('apiPost'); if (arguments.length !== 4 && arguments.length !== 3) throw new Error('apiPost was called with wrong number of arguments'); return apiAction('POST', urlPath, postBody, userId, null, callback); } /** @hidden */ export function _apiPut(urlPath, putBody, userId, callback) { debug('apiPut(): ' + urlPath); checkInitialized('apiPut'); if (arguments.length !== 4 && arguments.length !== 3) throw new Error('apiPut was called with wrong number of arguments'); return apiAction('PUT', urlPath, putBody, userId, null, callback); } /** @hidden */ export function _apiPatch(urlPath, patchBody, userId, callback) { debug('apiPatch(): ' + urlPath); checkInitialized('apiPatch'); if (arguments.length !== 4 && arguments.length !== 3) throw new Error('apiPatch was called with wrong number of arguments'); return apiAction('PATCH', urlPath, patchBody, userId, null, callback); } /** @hidden */ export function _apiDelete(urlPath, userId, callback) { debug('apiDelete(): ' + urlPath); checkInitialized('apiDelete'); if (arguments.length !== 3 && arguments.length !== 2) throw new Error('apiDelete was called with wrong number of arguments'); return apiAction('DELETE', urlPath, null, userId, null, callback); } /** @hidden */ function apiAction(method, urlPath, actionBody, userId, scope, callback) { const func = apiAction; if (!callback) { debug(`apiAction(): Promisifying ${method} ${urlPath}`); return new Promise(function (resolve, reject) { func(method, urlPath, actionBody, userId, scope, function (err, result) { err ? reject(err) : resolve(result) }); }); } debug('apiAction(' + method + '): ' + urlPath); if (arguments.length !== 6) throw new Error('apiAction called with wrong number of arguments'); if (typeof (callback) !== 'function') throw new Error('apiAction: callback is not a function'); if (!wickedStorage.apiReachable) return callback(new Error('The wicked API is currently not reachable. Try again later.')); // This is not needed anymore: The API accepts the current and the previous config hash now. // if (wickedStorage.pendingExit) // return callback(new Error('A shutdown due to changed configuration is pending.')); if (!scope) { if (wickedStorage.portalApiScope) scope = wickedStorage.portalApiScope; else scope = ''; } debug(`apiAction: Using scope ${scope}`); if (actionBody) debug(actionBody); if (!userId && wickedStorage.machineUserId) { debug('Picking up machine user id: ' + wickedStorage.machineUserId); userId = wickedStorage.machineUserId; } if (urlPath.startsWith('/')) urlPath = urlPath.substring(1); // strip slash in beginning; it's in the API url const url = _getInternalApiUrl() + urlPath; debug(method + ' ' + url); const reqInfo: RequestBody = { method: method, url: url, timeout: WICKED_TIMEOUT }; if (method != 'DELETE' && method != 'GET') { // DELETE and GET ain't got no body. reqInfo.body = actionBody; reqInfo.json = true; } // This is the config hash we saw at init; send it to make sure we don't // run on an outdated configuration. reqInfo.headers = { 'X-Config-Hash': wickedStorage.configHash }; if (userId) { if (wickedStorage.isV100OrHigher) { reqInfo.headers['X-Authenticated-UserId'] = `sub=${userId}`; } else if (wickedStorage.isV012OrHigher) { reqInfo.headers['X-Authenticated-UserId'] = userId; } else { reqInfo.headers['X-UserId'] = userId; } } if (wickedStorage.isV100OrHigher) { reqInfo.headers['X-Authenticated-Scope'] = scope; } if (requestRuntime.correlationId) { debug('Using correlation id: ' + requestRuntime.correlationId); reqInfo.headers['Correlation-Id'] = requestRuntime.correlationId; } if (wickedStorage.userAgent) { debug('Using User-Agent: ' + wickedStorage.userAgent); reqInfo.headers['User-Agent'] = wickedStorage.userAgent; } async.retry({ tries: wickedStorage.apiMaxTries, interval: wickedStorage.apiRetryDelay, errorFilter: function (err) { // Errors which are not "hard" but have an error code are permanent if they have a non-5xx error code. if (err.statusCode) { // In that case, abort the retry flow if (err.statusCode < 500) return false; // Retry on 5xx return true; } // In case of hard errors (such es E_CONN_xxx), continue retrying return true; } }, function (callback) { debug(`Attempting to ${reqInfo.method} ${reqInfo.url}`); request(reqInfo, function (err, res, body) { if (err) return callback(err); if (res.statusCode > 299) { // Looks bad const err = new WickedError(`api${nice(method)}() ${urlPath} returned non-OK status code: ${res.statusCode}, check err.statusCode and err.body for details`, res.statusCode, body); return callback(err); } if (res.statusCode !== 204) { const contentType = res.headers['content-type']; let returnValue = null; try { if (contentType.startsWith('text')) returnValue = getText(body); else returnValue = getJson(body); } catch (ex) { return callback(new WickedError(`api${nice(method)}() ${urlPath} returned non-parseable JSON: ${ex.message}`, 500, body)); } return callback(null, returnValue); } else { // Empty response return callback(null); } }); }, callback); } /** @hidden */ function nice(methodName) { return methodName.substring(0, 1) + methodName.substring(1).toLowerCase(); } /** @hidden */ export function buildUrl(base, queryParams) { let url = base; let first = true; for (let p in queryParams) { if (first) { url += '?'; first = false; } else { url += '&'; } const v = queryParams[p]; if (typeof v === 'number') url += v; else if (typeof v === 'string') url += qs.escape(v); else if (typeof v === 'boolean') url += v ? 'true' : 'false'; else // Object or array or whatever url += qs.escape(JSON.stringify(v)); } return url; } /** @hidden */ export function _getSubscriptionByClientId(clientId: string, apiId: string, asUserId: string, callback?: Callback<WickedSubscriptionInfo>): void | Promise<WickedSubscriptionInfo> { debug('getSubscriptionByClientId()'); checkInitialized('getSubscriptionByClientId'); const func = _getSubscriptionByClientId; if (!callback) { return new Promise(function (resolve, reject) { func(clientId, apiId, asUserId, function (err, result) { err ? reject(err) : resolve(result) }); }); } // Validate format of clientId if (!/^[a-zA-Z0-9\-]+$/.test(clientId)) { return callback(new Error('Invalid client_id format.')); } // Check whether we know this client ID, otherwise we won't bother. _apiGet('subscriptions/' + qs.escape(clientId), asUserId, 'read_subscriptions', function (err, subsInfo) { if (err) { debug('GET of susbcription for client_id ' + clientId + ' failed.'); debug(err); return callback(new Error('Could not identify application with given client_id.')); } debug('subscription info:'); debug(subsInfo); if (!subsInfo.subscription) return callback(new Error('Could not successfully retrieve subscription information.')); if (subsInfo.subscription.api != apiId) { debug('subsInfo.api != apiId: ' + subsInfo.subscription.api + ' != ' + apiId); return callback(new Error('Bad request. The client_id does not match the API.')); } debug('Successfully identified application: ' + subsInfo.subscription.application); return callback(null, subsInfo); }); }
the_stack
import { reaction, action, observable } from 'mobx' import { task } from '../index' import { memoize } from 'lodash' import autobind from 'autobind-decorator' import { throws } from 'smid' import { defer } from './defer' // tslint:disable:await-promise no-floating-promises test('goes from pending -> resolved', async () => { const d = defer() const base = jest.fn((_a: number, _b: number, _c: number) => d.promise) const fn = task(base) expect(fn.state === 'pending').toBe(true) expect(fn.pending === true).toBe(true) const p = fn(1, 2, 3) expect(fn.state === 'pending').toBe(true) expect(fn.pending === true).toBe(true) d.resolve(1337) const result = await p expect(result).toBe(1337) expect(fn.pending).toBe(false) expect(fn.rejected).toBe(false) expect(fn.resolved).toBe(true) expect(fn.result).toBe(1337) expect(fn.state).toBe('resolved') }) test('goes from pending -> rejected on error', async () => { const d = defer() const base = jest.fn((_a: number, _b: number, _c: number) => d.promise) const fn = task(base) expect(fn.state === 'pending').toBe(true) expect(fn.pending === true).toBe(true) const p = fn(1, 2, 3) expect(fn.state === 'pending').toBe(true) expect(fn.pending === true).toBe(true) const err = new Error('hah') d.reject(err) const result = await throws(p) expect(result).toBe(err) expect(fn.pending).toBe(false) expect(fn.rejected).toBe(true) expect(fn.resolved).toBe(false) expect(fn.result).toBe(undefined) expect(fn.error).toBe(err) expect(fn.state).toBe('rejected') }) test('goes from resolved -> pending -> resolved when state is set', async () => { const d = defer() const fn = task(() => d.promise, { state: 'resolved' }) expect(fn.resolved).toBe(true) const p = fn() expect(fn.pending).toBe(true) d.resolve(1337) await p expect(fn.resolved).toBe(true) }) test('state is reactive', () => { const fn = task(() => 1337) const isPending = jest.fn() const isResolved = jest.fn() const isRejected = jest.fn() reaction(() => fn.pending, isPending) reaction(() => fn.resolved, isResolved) reaction(() => fn.rejected, isRejected) fn.setState({ state: 'resolved' }) fn.setState({ state: 'rejected' }) fn.setState({ state: 'pending' }) // these goes from false to true, and from true to false expect(isPending).toHaveBeenCalledTimes(2) expect(isResolved).toHaveBeenCalledTimes(2) expect(isRejected).toHaveBeenCalledTimes(2) }) test('setState lets me modify the internal state', () => { const fn = task(() => 1337) expect(fn.pending).toBe(true) fn.setState({ state: 'resolved', result: 123 }) expect(fn.result).toBe(123) expect(fn.resolved).toBe(true) }) test('there are shortcuts to check the state.', () => { const fn = task(() => 1337) expect(fn.state).toBe('pending') expect(fn.pending).toBe(true) expect(fn.resolved).toBe(false) expect(fn.rejected).toBe(false) fn.setState({ state: 'resolved', result: 123 }) expect(fn.state).toBe('resolved') expect(fn.pending).toBe(false) expect(fn.resolved).toBe(true) expect(fn.rejected).toBe(false) fn.setState({ state: 'rejected' }) expect(fn.state).toBe('rejected') expect(fn.pending).toBe(false) expect(fn.resolved).toBe(false) expect(fn.rejected).toBe(true) }) test('task.resolved shorthand sets state: resolved', () => { const fn = task.resolved(() => 1337) expect(fn.resolved).toBe(true) }) test('swallow: true does not throw exceptions', async () => { const err = new Error('haha shiit') const fn = task((_a: number) => Promise.reject(err), { swallow: true }) const result = await fn(123) expect(result).toBe(undefined) expect(fn.result).toBe(undefined) expect(fn.error).toBe(err) }) test('regular decorator', async () => { const d = defer() class Test { @task fn(arg: any) { return d.promise.then(() => arg) } } const test = new Test() expect((test.fn as any).pending).toBe(true) const p = test.fn(123) expect((test.fn as any).pending).toBe(true) d.resolve(1337) const result = await p expect(result).toBe(123) expect((test.fn as any).resolved).toBe(true) expect((test.fn as any).result).toBe(123) }) test('decorator factory', () => { class Test { @task({ state: 'resolved', result: 1337 }) fn(_arg: any) { /**/ } } const test = new Test() expect((test.fn as any).resolved).toBe(true) expect((test.fn as any).result).toBe(1337) }) test('preconfigured decorator', () => { const error = new Error('hah') class Test { @task.resolved fnResolved() { /**/ } @task.rejected({ error }) fnRejected() { /**/ } } const test = new Test() expect((test.fnResolved as any).resolved).toBe(true) expect((test.fnRejected as any).rejected).toBe(true) expect((test.fnRejected as any).error).toBe(error) }) test('bind returns a task function', async () => { const fn = task(function(this: any, arg1: number) { return [this, arg1] }) const that = {} const bound = fn.bind(that, 1) const boundResult = await (bound as any)(1337) expect(boundResult[0]).toBe(that) expect(boundResult[1]).toBe(1) }) test('wrap returns a task function', async () => { const fn = task(() => 42).wrap(f => { const inner = () => { inner.callCount += 1 return f() } inner.callCount = 0 return inner }) expect(await fn()).toBe(42) expect((fn as any).callCount).toBe(1) expect(fn.resolved).toBe(true) }) test('can be memoized', async () => { let i = 1 const fn = task(() => i++).wrap(memoize) expect(await fn()).toBe(1) expect(await fn()).toBe(1) expect(fn.resolved).toBe(true) }) test('can decorate an already decorated method', async () => { /** * For this to work the task decorator has * to be the last decorator to run (declared first) */ class Test { @task @action.bound method() { return this } } const test = new Test() expect((test.method as any).pending).toBe(true) const method = test.method expect(await method()).toBe(test) // twice to test caching expect(await method()).toBe(test) }) test('can be tacked onto an observable', async () => { const store = observable({ todos: [], fetchTodos: task(async () => { return [{ text: 'install mobx-task' }] }) }) expect(store.fetchTodos.pending).toBe(true) await store.fetchTodos() expect(store.fetchTodos.resolved).toBe(true) }) test('match returns the case for the current state', () => { const fn = task((): number | undefined => undefined) const run = () => fn.match({ pending: () => 1, resolved: value => value, rejected: (err: any) => err.message }) expect(run()).toBe(1) fn.setState({ state: 'resolved', result: 42 }) expect(run()).toBe(42) fn.setState({ state: 'rejected', error: new Error('hah') }) expect(run()).toBe('hah') }) test('match returns undefined if there is no case', () => { const fn = task((): number | undefined => undefined) const run = () => fn.match({ resolved: value => value, rejected: (err: any) => err.message }) expect(run()).toBe(undefined) fn.setState({ state: 'resolved', result: 42 }) expect(run()).toBe(42) fn.setState({ state: 'rejected', error: new Error('hah') }) expect(run()).toBe('hah') }) test('match passes arguments to pending', () => { const fn = task((_a: number, _b: number) => undefined) let calledWith = null fn(1, 2) fn.match({ pending: (arg1, arg2) => { calledWith = [arg1, arg2] } }) expect(calledWith).toEqual([1, 2]) }) test('calling the function multiple times will only trigger setState:resolved once', async () => { const fn = task(d => d.promise) const d1 = defer() const d2 = defer() const p1 = fn(d1) const p2 = fn(d2) await new Promise(resolve => setTimeout(resolve, 20)) d1.resolve(1) const r1 = await p1 expect(fn.pending).toBe(true) d2.resolve(2) const r2 = await p2 expect(fn.resolved).toBe(true) expect(r1).toBe(1) expect(r2).toBe(2) }) test('calling the function multiple times will not trigger setState:rejected if not the last call', async () => { const fn = task(d => d.promise) const d1 = defer() const d2 = defer() const p1 = fn(d1) const p2 = fn(d2) await new Promise(resolve => setTimeout(resolve, 20)) d1.reject(new Error('Oh shit')) const r1 = await throws(() => p1) expect(fn.pending).toBe(true) d2.resolve(2) const r2 = await p2 expect(fn.resolved).toBe(true) expect(r1.message).toBe('Oh shit') expect(r2).toBe(2) }) test('catches sync errors', async () => { const fn = task(() => { throw new Error('hah') }) await throws(() => fn()) expect(fn.rejected).toBe(true) expect((fn.error as any).message).toBe('hah') }) test('reset() resets the state to resolved with result', async () => { const fn = task( () => { return 1337 }, { state: 'resolved', result: 42 } ) expect(fn.result).toBe(42) const result = await fn() expect(result).toBe(1337) expect(fn.state).toBe('resolved') const fromReset = fn.reset() expect(fromReset).toBe(fn) expect(fn.result).toBe(42) }) test('reset() resets the state to pending', async () => { const fn = task(() => { return 1337 }) expect(fn.result).toBe(undefined) const result = await fn() expect(result).toBe(1337) expect(fn.state).toBe('resolved') fn.reset() expect(fn.result).toBe(undefined) expect(fn.state).toBe('pending') }) test('autobind works', async () => { @autobind class Test { value: number constructor() { this.value = 42 } @task @autobind func() { return this.value } } const sub = new Test() const fn = sub.func const result = await fn() expect(result).toBe(42) expect((fn as any).state).toBe('resolved') expect((sub.func as any).state).toBe('resolved') }) test('can reassign decorated method', async () => { class Test { @task method() { /**/ } } const sub = new Test() sub.method = 123 as any expect(sub.method).toBe(123) }) test('decorator value is cached', async () => { class Test { @task method() { return 42 } } const sub = new Test() expect(await sub.method()).toBe(42) expect(await sub.method()).toBe(42) }) test('decorator supports fields with functions', async () => { class Test { @task method = function() { return 42 } } const sub = new Test() expect(await sub.method()).toBe(42) }) test('decorator supports fields with arrow functions', async () => { class Test { getValue() { return 42 } @task method = () => this.getValue() } const sub = new Test() expect(await sub.method()).toBe(42) })
the_stack
import Button from '@material-ui/core/Button'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import { action, computed, makeObservable, observable, toJS } from 'mobx'; import { observer } from 'mobx-react'; import { posix as Path } from 'path'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { MessageBus } from '../api'; import { ConfigurationChangeMessage, EnableLanguageIdMessage, SelectFileMessage, SelectFolderMessage, SelectTabMessage, } from '../api/message'; import { Config, ConfigFile, Configs, ConfigTarget, FileConfig, Settings, TextDocument, WorkspaceFolder } from '../api/settings'; import { extractConfig } from '../api/settings/settingsHelper'; import { VsCodeWebviewApi } from '../api/vscode/VsCodeWebviewApi'; import { sampleSettings, sampleSettingsSingleFolder, sampleSettingsExcluded, sampleSettingsExcludedNotInWorkspace, sampleSettingsGitignore, sampleSettingsBlocked, } from '../test/samples/sampleSettings'; import { ErrorBoundary } from './components/ErrorBoundary'; class AppState { currentSample: number = 0; sampleSettings: Settings[] = [ sampleSettings, sampleSettingsSingleFolder, sampleSettingsExcluded, sampleSettingsExcludedNotInWorkspace, sampleSettingsGitignore, sampleSettingsBlocked, ]; _settings: Settings = this.sampleSettings[this.currentSample]; _activeTab: string = 'About'; constructor() { makeObservable(this, { _activeTab: observable, _settings: observable, currentSample: observable, sampleSettings: observable, nextSample: action, updateActiveFileUri: action, updateActiveFolderUri: action, updateActiveTab: action, updateConfigs: action, updateConfigsFile: action, updateSettings: action, }); } @computed get settings(): Settings { return this._settings; } @computed get activeTab() { return this._activeTab; } updateActiveTab(tab: string) { this._activeTab = tab; return this._activeTab; } @computed get activeFolder(): WorkspaceFolder | undefined { const folders = this.workspaceFolders; const uri = this.activeFolderUri; return folders.filter((f) => f.uri === uri)[0]; } @computed get workspaceFolders(): WorkspaceFolder[] { const workspace = this.settings.workspace; return (workspace && workspace.workspaceFolders) || []; } @computed get activeFolderUri(): string | undefined { return this.settings.activeFolderUri; } updateActiveFolderUri(fileUri: string | undefined) { this._settings.activeFolderUri = fileUri; } @computed get activeFileUri(): string | undefined { return this.settings.activeFileUri; } updateActiveFileUri(fileUri: string | undefined) { this._settings.activeFileUri = fileUri; } @computed get activeDocument(): TextDocument | undefined { const uri = this.activeFileUri; return this.workspaceDocuments.filter((d) => d.uri === uri)[0]; } @computed get workspaceDocuments(): TextDocument[] { const workspace = this.settings.workspace; return (workspace && workspace.textDocuments) || []; } @computed get enabledLanguageIds(): string[] { const cfg = extractConfig(this.settings.configs, 'languageIdsEnabled'); return cfg.config || []; } updateSettings(settings: Settings) { this._settings = settings; } nextSample() { this.sampleSettings[this.currentSample] = toJS(this.settings); this.currentSample = (this.currentSample + 1) % this.sampleSettings.length; this._settings = this.sampleSettings[this.currentSample]; } updateConfigs<K extends keyof Configs>(key: K, value: Configs[K]): void { this._settings.configs[key] = value; } updateConfigsFile(file: FileConfig | undefined) { this.updateConfigs('file', file); } findMatchingSampleConfig(docUri: string): Configs | undefined { for (const sample of this.sampleSettings) { if (sample.activeFileUri === docUri) { return sample.configs; } } return undefined; } } const localeDisplay: [ConfigTarget, string][] = [ ['user', 'Global'], ['workspace', 'Workspace'], ['folder', 'Folder'], ]; @observer class VsCodeTestWrapperView extends React.Component<{ appState: AppState }> { render() { const appState = this.props.appState; const settings = appState.settings; const getLocales = (target: ConfigTarget) => { const config = settings.configs[target]; if (!config) return '-'; return (config.locales || ['-']).join(', '); }; return ( <ErrorBoundary> <h2>Locales</h2> <Table> <TableHead key="title"> <TableRow> <TableCell>Scope</TableCell> <TableCell>Value</TableCell> </TableRow> </TableHead> <TableBody> {localeDisplay.map(([field, name]) => ( <TableRow key={field}> <TableCell>{name}</TableCell> <TableCell>{getLocales(field)}</TableCell> </TableRow> ))} </TableBody> </Table> <div> <h2>Info</h2> <div>Panel: {appState.activeTab}</div> <div> Active Folder: <pre>{JSON.stringify(toJS(appState.activeFolder), null, 2)}</pre> </div> <div> Active Document: <pre>{JSON.stringify(toJS(appState.activeDocument), null, 2)}</pre> </div> <div> File Config <pre>{JSON.stringify(toJS(appState.settings.configs.file), null, 2)}</pre> </div> </div> <div> <Button variant="contained" color="primary" onClick={this.onUpdateConfig}> Toggle Single / Multi Folder Workspace </Button> </div> <div> <pre>{JSON.stringify(toJS(appState.settings), null, 2)}</pre> </div> </ErrorBoundary> ); } onUpdateConfig = () => { console.log('onUpdateConfig'); this.props.appState.nextSample(); postSettings(); }; } const appState = new AppState(); /* reaction( () => toJS(appState.settings), value => ( console.log('post ConfigurationChangeMessage'), vsCodeApi.postMessage({ command: 'ConfigurationChangeMessage', value: { settings: toJS(appState.settings) } }); ) ); */ ReactDOM.render(<VsCodeTestWrapperView appState={appState} />, document.getElementById('root')); const messageBus = new MessageBus(new VsCodeWebviewApi()); messageBus.listenFor('RequestConfigurationMessage', postSettings); function postSettings() { messageBus.postMessage({ command: 'ConfigurationChangeMessage', value: { activeTab: toJS(appState.activeTab), settings: toJS(appState.settings), }, }); } function calcFileConfig() { const uri = appState.activeFileUri; const doc = appState.workspaceDocuments.filter((doc) => doc.uri === uri)[0]; if (!doc) { return; } const languageId = doc.languageId; const dictionaries = appState.settings.dictionaries; const languageEnabled = appState.enabledLanguageIds.includes(languageId); const folderPath = Path.dirname(Path.dirname(doc.uri)); const workspacePath = Path.dirname(folderPath); const config = appState.findMatchingSampleConfig(doc.uri); const useConfig: FileConfig = config?.file ?? { ...doc, fileEnabled: true, fileIsIncluded: true, fileIsExcluded: false, fileIsInWorkspace: true, excludedBy: undefined, languageEnabled, dictionaries: dictionaries.filter((dic) => dic.languageIds.includes(languageId)), configFiles: [cfgFile(folderPath, 'cspell.json'), cfgFile(workspacePath, 'cspell.config.json')], gitignoreInfo: config?.file?.gitignoreInfo, blockedReason: config?.file?.blockedReason, }; appState.updateConfigsFile(useConfig); } function cfgFile(path: string, file: string): ConfigFile { return { uri: Path.join(path, file), name: [Path.basename(path), file].join('/'), }; } messageBus.listenFor('ConfigurationChangeMessage', (msg: ConfigurationChangeMessage) => { console.log('ConfigurationChangeMessage'); appState.updateSettings(msg.value.settings); }); messageBus.listenFor('SelectTabMessage', (msg: SelectTabMessage) => { console.log('SelectTabMessage'); appState.updateActiveTab(msg.value); }); messageBus.listenFor('SelectFolderMessage', (msg: SelectFolderMessage) => { console.log('SelectFolderMessage'); appState.updateActiveFolderUri(msg.value); }); messageBus.listenFor('SelectFileMessage', (msg: SelectFileMessage) => { console.log('SelectFileMessage'); appState.updateActiveFileUri(msg.value); calcFileConfig(); postSettings(); }); messageBus.listenFor('EnableLanguageIdMessage', (msg: EnableLanguageIdMessage) => { console.log('EnableLanguageIdMessage'); console.log(JSON.stringify(msg, null, 2)); const foundConfig = extractConfig(appState.settings.configs, 'languageIdsEnabled'); const { target = foundConfig.target, languageId, enable: enabled } = msg.value; const config: Config = appState.settings.configs[target]; const ids = new Set(config.languageIdsEnabled || []); if (enabled) { ids.add(languageId); } else { ids.delete(languageId); } const languageIdsEnabled = [...ids].sort(); appState.updateConfigs(target, { ...config, languageIdsEnabled }); calcFileConfig(); postSettings(); });
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /** * An inlined enum containing useful character codes (to be used with String.charCodeAt). * Please leave the const keyword such that it gets inlined when compiled to JavaScript! */ export const enum CharCode { Null = 0, /** * The `\b` character. */ Backspace = 8, /** * The `\t` character. */ Tab = 9, /** * The `\n` character. */ LineFeed = 10, /** * The `\r` character. */ CarriageReturn = 13, Space = 32, /** * The `!` character. */ ExclamationMark = 33, /** * The `"` character. */ DoubleQuote = 34, /** * The `#` character. */ Hash = 35, /** * The `$` character. */ DollarSign = 36, /** * The `%` character. */ PercentSign = 37, /** * The `&` character. */ Ampersand = 38, /** * The `'` character. */ SingleQuote = 39, /** * The `(` character. */ OpenParen = 40, /** * The `)` character. */ CloseParen = 41, /** * The `*` character. */ Asterisk = 42, /** * The `+` character. */ Plus = 43, /** * The `,` character. */ Comma = 44, /** * The `-` character. */ Dash = 45, /** * The `.` character. */ Period = 46, /** * The `/` character. */ Slash = 47, Digit0 = 48, Digit1 = 49, Digit2 = 50, Digit3 = 51, Digit4 = 52, Digit5 = 53, Digit6 = 54, Digit7 = 55, Digit8 = 56, Digit9 = 57, /** * The `:` character. */ Colon = 58, /** * The `;` character. */ Semicolon = 59, /** * The `<` character. */ LessThan = 60, /** * The `=` character. */ Equals = 61, /** * The `>` character. */ GreaterThan = 62, /** * The `?` character. */ QuestionMark = 63, /** * The `@` character. */ AtSign = 64, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, /** * The `[` character. */ OpenSquareBracket = 91, /** * The `\` character. */ Backslash = 92, /** * The `]` character. */ CloseSquareBracket = 93, /** * The `^` character. */ Caret = 94, /** * The `_` character. */ Underline = 95, /** * The ``(`)`` character. */ BackTick = 96, a = 97, b = 98, c = 99, d = 100, e = 101, f = 102, g = 103, h = 104, i = 105, j = 106, k = 107, l = 108, m = 109, n = 110, o = 111, p = 112, q = 113, r = 114, s = 115, t = 116, u = 117, v = 118, w = 119, x = 120, y = 121, z = 122, /** * The `{` character. */ OpenCurlyBrace = 123, /** * The `|` character. */ Pipe = 124, /** * The `}` character. */ CloseCurlyBrace = 125, /** * The `~` character. */ Tilde = 126, U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde U_Combining_Macron = 0x0304, // U+0304 Combining Macron U_Combining_Overline = 0x0305, // U+0305 Combining Overline U_Combining_Breve = 0x0306, // U+0306 Combining Breve U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above U_Combining_Ring_Above = 0x030a, // U+030A Combining Ring Above U_Combining_Double_Acute_Accent = 0x030b, // U+030B Combining Double Acute Accent U_Combining_Caron = 0x030c, // U+030C Combining Caron U_Combining_Vertical_Line_Above = 0x030d, // U+030D Combining Vertical Line Above U_Combining_Double_Vertical_Line_Above = 0x030e, // U+030E Combining Double Vertical Line Above U_Combining_Double_Grave_Accent = 0x030f, // U+030F Combining Double Grave Accent U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below U_Combining_Left_Angle_Above = 0x031a, // U+031A Combining Left Angle Above U_Combining_Horn = 0x031b, // U+031B Combining Horn U_Combining_Left_Half_Ring_Below = 0x031c, // U+031C Combining Left Half Ring Below U_Combining_Up_Tack_Below = 0x031d, // U+031D Combining Up Tack Below U_Combining_Down_Tack_Below = 0x031e, // U+031E Combining Down Tack Below U_Combining_Plus_Sign_Below = 0x031f, // U+031F Combining Plus Sign Below U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below U_Combining_Bridge_Below = 0x032a, // U+032A Combining Bridge Below U_Combining_Inverted_Double_Arch_Below = 0x032b, // U+032B Combining Inverted Double Arch Below U_Combining_Caron_Below = 0x032c, // U+032C Combining Caron Below U_Combining_Circumflex_Accent_Below = 0x032d, // U+032D Combining Circumflex Accent Below U_Combining_Breve_Below = 0x032e, // U+032E Combining Breve Below U_Combining_Inverted_Breve_Below = 0x032f, // U+032F Combining Inverted Breve Below U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below U_Combining_Inverted_Bridge_Below = 0x033a, // U+033A Combining Inverted Bridge Below U_Combining_Square_Below = 0x033b, // U+033B Combining Square Below U_Combining_Seagull_Below = 0x033c, // U+033C Combining Seagull Below U_Combining_X_Above = 0x033d, // U+033D Combining X Above U_Combining_Vertical_Tilde = 0x033e, // U+033E Combining Vertical Tilde U_Combining_Double_Overline = 0x033f, // U+033F Combining Double Overline U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below U_Combining_Not_Tilde_Above = 0x034a, // U+034A Combining Not Tilde Above U_Combining_Homothetic_Above = 0x034b, // U+034B Combining Homothetic Above U_Combining_Almost_Equal_To_Above = 0x034c, // U+034C Combining Almost Equal To Above U_Combining_Left_Right_Arrow_Below = 0x034d, // U+034D Combining Left Right Arrow Below U_Combining_Upwards_Arrow_Below = 0x034e, // U+034E Combining Upwards Arrow Below U_Combining_Grapheme_Joiner = 0x034f, // U+034F Combining Grapheme Joiner U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata U_Combining_X_Below = 0x0353, // U+0353 Combining X Below U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below U_Combining_Double_Ring_Below = 0x035a, // U+035A Combining Double Ring Below U_Combining_Zigzag_Above = 0x035b, // U+035B Combining Zigzag Above U_Combining_Double_Breve_Below = 0x035c, // U+035C Combining Double Breve Below U_Combining_Double_Breve = 0x035d, // U+035D Combining Double Breve U_Combining_Double_Macron = 0x035e, // U+035E Combining Double Macron U_Combining_Double_Macron_Below = 0x035f, // U+035F Combining Double Macron Below U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D U_Combining_Latin_Small_Letter_H = 0x036a, // U+036A Combining Latin Small Letter H U_Combining_Latin_Small_Letter_M = 0x036b, // U+036B Combining Latin Small Letter M U_Combining_Latin_Small_Letter_R = 0x036c, // U+036C Combining Latin Small Letter R U_Combining_Latin_Small_Letter_T = 0x036d, // U+036D Combining Latin Small Letter T U_Combining_Latin_Small_Letter_V = 0x036e, // U+036E Combining Latin Small Letter V U_Combining_Latin_Small_Letter_X = 0x036f, // U+036F Combining Latin Small Letter X /** * Unicode Character 'LINE SEPARATOR' (U+2028) * http://www.fileformat.info/info/unicode/char/2028/index.htm */ LINE_SEPARATOR = 0x2028, /** * Unicode Character 'PARAGRAPH SEPARATOR' (U+2029) * http://www.fileformat.info/info/unicode/char/2029/index.htm */ PARAGRAPH_SEPARATOR = 0x2029, /** * Unicode Character 'NEXT LINE' (U+0085) * http://www.fileformat.info/info/unicode/char/0085/index.htm */ NEXT_LINE = 0x0085, // http://www.fileformat.info/info/unicode/category/Sk/list.htm U_CIRCUMFLEX = 0x005e, // U+005E CIRCUMFLEX U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT U_DIAERESIS = 0x00a8, // U+00A8 DIAERESIS U_MACRON = 0x00af, // U+00AF MACRON U_ACUTE_ACCENT = 0x00b4, // U+00B4 ACUTE ACCENT U_CEDILLA = 0x00b8, // U+00B8 CEDILLA U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02c2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02c3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02c4, // U+02C4 MODIFIER LETTER UP ARROWHEAD U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02c5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02d2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02d3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING U_MODIFIER_LETTER_UP_TACK = 0x02d4, // U+02D4 MODIFIER LETTER UP TACK U_MODIFIER_LETTER_DOWN_TACK = 0x02d5, // U+02D5 MODIFIER LETTER DOWN TACK U_MODIFIER_LETTER_PLUS_SIGN = 0x02d6, // U+02D6 MODIFIER LETTER PLUS SIGN U_MODIFIER_LETTER_MINUS_SIGN = 0x02d7, // U+02D7 MODIFIER LETTER MINUS SIGN U_BREVE = 0x02d8, // U+02D8 BREVE U_DOT_ABOVE = 0x02d9, // U+02D9 DOT ABOVE U_RING_ABOVE = 0x02da, // U+02DA RING ABOVE U_OGONEK = 0x02db, // U+02DB OGONEK U_SMALL_TILDE = 0x02dc, // U+02DC SMALL TILDE U_DOUBLE_ACUTE_ACCENT = 0x02dd, // U+02DD DOUBLE ACUTE ACCENT U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02de, // U+02DE MODIFIER LETTER RHOTIC HOOK U_MODIFIER_LETTER_CROSS_ACCENT = 0x02df, // U+02DF MODIFIER LETTER CROSS ACCENT U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02e5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02e6, // U+02E6 MODIFIER LETTER HIGH TONE BAR U_MODIFIER_LETTER_MID_TONE_BAR = 0x02e7, // U+02E7 MODIFIER LETTER MID TONE BAR U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02e8, // U+02E8 MODIFIER LETTER LOW TONE BAR U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02e9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02ea, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02eb, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK U_MODIFIER_LETTER_UNASPIRATED = 0x02ed, // U+02ED MODIFIER LETTER UNASPIRATED U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02ef, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02f0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02f1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02f2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD U_MODIFIER_LETTER_LOW_RING = 0x02f3, // U+02F3 MODIFIER LETTER LOW RING U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02f4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02f5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02f6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT U_MODIFIER_LETTER_LOW_TILDE = 0x02f7, // U+02F7 MODIFIER LETTER LOW TILDE U_MODIFIER_LETTER_RAISED_COLON = 0x02f8, // U+02F8 MODIFIER LETTER RAISED COLON U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02f9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE U_MODIFIER_LETTER_END_HIGH_TONE = 0x02fa, // U+02FA MODIFIER LETTER END HIGH TONE U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02fb, // U+02FB MODIFIER LETTER BEGIN LOW TONE U_MODIFIER_LETTER_END_LOW_TONE = 0x02fc, // U+02FC MODIFIER LETTER END LOW TONE U_MODIFIER_LETTER_SHELF = 0x02fd, // U+02FD MODIFIER LETTER SHELF U_MODIFIER_LETTER_OPEN_SHELF = 0x02fe, // U+02FE MODIFIER LETTER OPEN SHELF U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02ff, // U+02FF MODIFIER LETTER LOW LEFT ARROW U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS U_GREEK_KORONIS = 0x1fbd, // U+1FBD GREEK KORONIS U_GREEK_PSILI = 0x1fbf, // U+1FBF GREEK PSILI U_GREEK_PERISPOMENI = 0x1fc0, // U+1FC0 GREEK PERISPOMENI U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1fc1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI U_GREEK_PSILI_AND_VARIA = 0x1fcd, // U+1FCD GREEK PSILI AND VARIA U_GREEK_PSILI_AND_OXIA = 0x1fce, // U+1FCE GREEK PSILI AND OXIA U_GREEK_PSILI_AND_PERISPOMENI = 0x1fcf, // U+1FCF GREEK PSILI AND PERISPOMENI U_GREEK_DASIA_AND_VARIA = 0x1fdd, // U+1FDD GREEK DASIA AND VARIA U_GREEK_DASIA_AND_OXIA = 0x1fde, // U+1FDE GREEK DASIA AND OXIA U_GREEK_DASIA_AND_PERISPOMENI = 0x1fdf, // U+1FDF GREEK DASIA AND PERISPOMENI U_GREEK_DIALYTIKA_AND_VARIA = 0x1fed, // U+1FED GREEK DIALYTIKA AND VARIA U_GREEK_DIALYTIKA_AND_OXIA = 0x1fee, // U+1FEE GREEK DIALYTIKA AND OXIA U_GREEK_VARIA = 0x1fef, // U+1FEF GREEK VARIA U_GREEK_OXIA = 0x1ffd, // U+1FFD GREEK OXIA U_GREEK_DASIA = 0x1ffe, // U+1FFE GREEK DASIA U_IDEOGRAPHIC_FULL_STOP = 0x3002, // U+3002 IDEOGRAPHIC FULL STOP U_LEFT_CORNER_BRACKET = 0x300c, // U+300C LEFT CORNER BRACKET U_RIGHT_CORNER_BRACKET = 0x300d, // U+300D RIGHT CORNER BRACKET U_LEFT_BLACK_LENTICULAR_BRACKET = 0x3010, // U+3010 LEFT BLACK LENTICULAR BRACKET U_RIGHT_BLACK_LENTICULAR_BRACKET = 0x3011, // U+3011 RIGHT BLACK LENTICULAR BRACKET U_OVERLINE = 0x203e, // Unicode Character 'OVERLINE' /** * UTF-8 BOM * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) * http://www.fileformat.info/info/unicode/char/feff/index.htm */ UTF8_BOM = 65279, U_FULLWIDTH_SEMICOLON = 0xff1b, // U+FF1B FULLWIDTH SEMICOLON U_FULLWIDTH_COMMA = 0xff0c, // U+FF0C FULLWIDTH COMMA } function roundFloat(number: number, decimalPoints: number): number { const decimal = Math.pow(10, decimalPoints); return Math.round(number * decimal) / decimal; } export class RGBA { _rgbaBrand: void = undefined; /** * Red: integer in [0-255] */ readonly r: number; /** * Green: integer in [0-255] */ readonly g: number; /** * Blue: integer in [0-255] */ readonly b: number; /** * Alpha: float in [0-1] */ readonly a: number; constructor(r: number, g: number, b: number, a: number = 1) { this.r = Math.min(255, Math.max(0, r)) | 0; this.g = Math.min(255, Math.max(0, g)) | 0; this.b = Math.min(255, Math.max(0, b)) | 0; this.a = roundFloat(Math.max(Math.min(1, a), 0), 3); } static equals(a: RGBA, b: RGBA): boolean { return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; } } export class HSLA { _hslaBrand: void = undefined; /** * Hue: integer in [0, 360] */ readonly h: number; /** * Saturation: float in [0, 1] */ readonly s: number; /** * Luminosity: float in [0, 1] */ readonly l: number; /** * Alpha: float in [0, 1] */ readonly a: number; constructor(h: number, s: number, l: number, a: number) { this.h = Math.max(Math.min(360, h), 0) | 0; this.s = roundFloat(Math.max(Math.min(1, s), 0), 3); this.l = roundFloat(Math.max(Math.min(1, l), 0), 3); this.a = roundFloat(Math.max(Math.min(1, a), 0), 3); } static equals(a: HSLA, b: HSLA): boolean { return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a; } /** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h in the set [0, 360], s, and l in the set [0, 1]. */ static fromRGBA(rgba: RGBA): HSLA { const r = rgba.r / 255; const g = rgba.g / 255; const b = rgba.b / 255; const a = rgba.a; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h = 0; let s = 0; const l = (min + max) / 2; const chroma = max - min; if (chroma > 0) { s = Math.min(l <= 0.5 ? chroma / (2 * l) : chroma / (2 - 2 * l), 1); switch (max) { case r: h = (g - b) / chroma + (g < b ? 6 : 0); break; case g: h = (b - r) / chroma + 2; break; case b: h = (r - g) / chroma + 4; break; } h *= 60; h = Math.round(h); } return new HSLA(h, s, l, a); } private static _hue2rgb(p: number, q: number, t: number): number { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1 / 6) { return p + (q - p) * 6 * t; } if (t < 1 / 2) { return q; } if (t < 2 / 3) { return p + (q - p) * (2 / 3 - t) * 6; } return p; } /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. */ static toRGBA(hsla: HSLA): RGBA { const h = hsla.h / 360; const { s, l, a } = hsla; let r: number, g: number, b: number; if (s === 0) { r = g = b = l; // achromatic } else { const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = HSLA._hue2rgb(p, q, h + 1 / 3); g = HSLA._hue2rgb(p, q, h); b = HSLA._hue2rgb(p, q, h - 1 / 3); } return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a); } } export class HSVA { _hsvaBrand: void = undefined; /** * Hue: integer in [0, 360] */ readonly h: number; /** * Saturation: float in [0, 1] */ readonly s: number; /** * Value: float in [0, 1] */ readonly v: number; /** * Alpha: float in [0, 1] */ readonly a: number; constructor(h: number, s: number, v: number, a: number) { this.h = Math.max(Math.min(360, h), 0) | 0; this.s = roundFloat(Math.max(Math.min(1, s), 0), 3); this.v = roundFloat(Math.max(Math.min(1, v), 0), 3); this.a = roundFloat(Math.max(Math.min(1, a), 0), 3); } static equals(a: HSVA, b: HSVA): boolean { return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a; } // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm static fromRGBA(rgba: RGBA): HSVA { const r = rgba.r / 255; const g = rgba.g / 255; const b = rgba.b / 255; const cmax = Math.max(r, g, b); const cmin = Math.min(r, g, b); const delta = cmax - cmin; const s = cmax === 0 ? 0 : delta / cmax; let m: number; if (delta === 0) { m = 0; } else if (cmax === r) { m = ((((g - b) / delta) % 6) + 6) % 6; } else if (cmax === g) { m = (b - r) / delta + 2; } else { m = (r - g) / delta + 4; } return new HSVA(Math.round(m * 60), s, cmax, rgba.a); } // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm static toRGBA(hsva: HSVA): RGBA { const { h, s, v, a } = hsva; const c = v * s; const x = c * (1 - Math.abs(((h / 60) % 2) - 1)); const m = v - c; let [r, g, b] = [0, 0, 0]; if (h < 60) { r = c; g = x; } else if (h < 120) { r = x; g = c; } else if (h < 180) { g = c; b = x; } else if (h < 240) { g = x; b = c; } else if (h < 300) { r = x; b = c; } else if (h <= 360) { r = c; b = x; } r = Math.round((r + m) * 255); g = Math.round((g + m) * 255); b = Math.round((b + m) * 255); return new RGBA(r, g, b, a); } } export class Color { static fromHex(hex: string): Color { return Color.Format.CSS.parseHex(hex) || Color.red; } readonly rgba: RGBA; private _hsla?: HSLA; get hsla(): HSLA { if (this._hsla) { return this._hsla; } else { return HSLA.fromRGBA(this.rgba); } } private _hsva?: HSVA; get hsva(): HSVA { if (this._hsva) { return this._hsva; } return HSVA.fromRGBA(this.rgba); } constructor(arg: RGBA | HSLA | HSVA) { if (!arg) { throw new Error('Color needs a value'); } else if (arg instanceof RGBA) { this.rgba = arg; } else if (arg instanceof HSLA) { this._hsla = arg; this.rgba = HSLA.toRGBA(arg); } else if (arg instanceof HSVA) { this._hsva = arg; this.rgba = HSVA.toRGBA(arg); } else { throw new Error('Invalid color ctor argument'); } } equals(other: Color | null): boolean { return ( !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.equals(this.hsva, other.hsva) ); } /** * http://www.w3.org/TR/WCAG20/#relativeluminancedef * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white. */ getRelativeLuminance(): number { const R = Color._relativeLuminanceForComponent(this.rgba.r); const G = Color._relativeLuminanceForComponent(this.rgba.g); const B = Color._relativeLuminanceForComponent(this.rgba.b); const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B; return roundFloat(luminance, 4); } private static _relativeLuminanceForComponent(color: number): number { const c = color / 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); } /** * http://www.w3.org/TR/WCAG20/#contrast-ratiodef * Returns the contrast ration number in the set [1, 21]. */ getContrastRatio(another: Color): number { const lum1 = this.getRelativeLuminance(); const lum2 = another.getRelativeLuminance(); return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05); } /** * http://24ways.org/2010/calculating-color-contrast * Return 'true' if darker color otherwise 'false' */ isDarker(): boolean { const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000; return yiq < 128; } /** * http://24ways.org/2010/calculating-color-contrast * Return 'true' if lighter color otherwise 'false' */ isLighter(): boolean { const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000; return yiq >= 128; } isLighterThan(another: Color): boolean { const lum1 = this.getRelativeLuminance(); const lum2 = another.getRelativeLuminance(); return lum1 > lum2; } isDarkerThan(another: Color): boolean { const lum1 = this.getRelativeLuminance(); const lum2 = another.getRelativeLuminance(); return lum1 < lum2; } lighten(factor: number): Color { return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a)); } darken(factor: number): Color { return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a)); } transparent(factor: number): Color { const { r, g, b, a } = this.rgba; return new Color(new RGBA(r, g, b, a * factor)); } isTransparent(): boolean { return this.rgba.a === 0; } isOpaque(): boolean { return this.rgba.a === 1; } opposite(): Color { return new Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a)); } blend(c: Color): Color { const rgba = c.rgba; // Convert to 0..1 opacity const thisA = this.rgba.a; const colorA = rgba.a; const a = thisA + colorA * (1 - thisA); if (a < 1e-6) { return Color.transparent; } const r = (this.rgba.r * thisA) / a + (rgba.r * colorA * (1 - thisA)) / a; const g = (this.rgba.g * thisA) / a + (rgba.g * colorA * (1 - thisA)) / a; const b = (this.rgba.b * thisA) / a + (rgba.b * colorA * (1 - thisA)) / a; return new Color(new RGBA(r, g, b, a)); } makeOpaque(opaqueBackground: Color): Color { if (this.isOpaque() || opaqueBackground.rgba.a !== 1) { // only allow to blend onto a non-opaque color onto a opaque color return this; } const { r, g, b, a } = this.rgba; // https://stackoverflow.com/questions/12228548/finding-equivalent-color-with-opacity return new Color( new RGBA( opaqueBackground.rgba.r - a * (opaqueBackground.rgba.r - r), opaqueBackground.rgba.g - a * (opaqueBackground.rgba.g - g), opaqueBackground.rgba.b - a * (opaqueBackground.rgba.b - b), 1, ), ); } flatten(...backgrounds: Color[]): Color { const background = backgrounds.reduceRight((accumulator, color) => { return Color._flatten(color, accumulator); }); return Color._flatten(this, background); } private static _flatten(foreground: Color, background: Color) { const backgroundAlpha = 1 - foreground.rgba.a; return new Color( new RGBA( backgroundAlpha * background.rgba.r + foreground.rgba.a * foreground.rgba.r, backgroundAlpha * background.rgba.g + foreground.rgba.a * foreground.rgba.g, backgroundAlpha * background.rgba.b + foreground.rgba.a * foreground.rgba.b, ), ); } private _toString?: string; toString(): string { if (!this._toString) { this._toString = Color.Format.CSS.format(this); } return this._toString; } static getLighterColor(of: Color, relative: Color, factor?: number): Color { if (of.isLighterThan(relative)) { return of; } factor = factor ? factor : 0.5; const lum1 = of.getRelativeLuminance(); const lum2 = relative.getRelativeLuminance(); factor = (factor * (lum2 - lum1)) / lum2; return of.lighten(factor); } static getDarkerColor(of: Color, relative: Color, factor?: number): Color { if (of.isDarkerThan(relative)) { return of; } factor = factor ? factor : 0.5; const lum1 = of.getRelativeLuminance(); const lum2 = relative.getRelativeLuminance(); factor = (factor * (lum1 - lum2)) / lum1; return of.darken(factor); } static readonly white = new Color(new RGBA(255, 255, 255, 1)); static readonly black = new Color(new RGBA(0, 0, 0, 1)); static readonly red = new Color(new RGBA(255, 0, 0, 1)); static readonly blue = new Color(new RGBA(0, 0, 255, 1)); static readonly green = new Color(new RGBA(0, 255, 0, 1)); static readonly cyan = new Color(new RGBA(0, 255, 255, 1)); static readonly lightgrey = new Color(new RGBA(211, 211, 211, 1)); static readonly transparent = new Color(new RGBA(0, 0, 0, 0)); } export namespace Color { export namespace Format { export namespace CSS { export function formatRGB(color: Color): string { if (color.rgba.a === 1) { return `rgb(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b})`; } return Color.Format.CSS.formatRGBA(color); } export function formatRGBA(color: Color): string { return `rgba(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b}, ${+color.rgba.a.toFixed(2)})`; } export function formatHSL(color: Color): string { if (color.hsla.a === 1) { return `hsl(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%)`; } return Color.Format.CSS.formatHSLA(color); } export function formatHSLA(color: Color): string { return `hsla(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed( 2, )}%, ${color.hsla.a.toFixed(2)})`; } function _toTwoDigitHex(n: number): string { const r = n.toString(16); return r.length !== 2 ? '0' + r : r; } /** * Formats the color as #RRGGBB */ export function formatHex(color: Color): string { return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}`; } /** * Formats the color as #RRGGBBAA * If 'compact' is set, colors without transparancy will be printed as #RRGGBB */ export function formatHexA(color: Color, compact = false): string { if (compact && color.rgba.a === 1) { return Color.Format.CSS.formatHex(color); } return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex( color.rgba.b, )}${_toTwoDigitHex(Math.round(color.rgba.a * 255))}`; } /** * The default format will use HEX if opaque and RGBA otherwise. */ export function format(color: Color): string { if (color.isOpaque()) { return Color.Format.CSS.formatHex(color); } return Color.Format.CSS.formatRGBA(color); } /** * Converts an Hex color value to a Color. * returns r, g, and b are contained in the set [0, 255] * @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA). */ export function parseHex(hex: string): Color | null { const length = hex.length; if (length === 0) { // Invalid color return null; } if (hex.charCodeAt(0) !== CharCode.Hash) { // Does not begin with a # return null; } if (length === 7) { // #RRGGBB format const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2)); const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4)); const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6)); return new Color(new RGBA(r, g, b, 1)); } if (length === 9) { // #RRGGBBAA format const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2)); const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4)); const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6)); const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8)); return new Color(new RGBA(r, g, b, a / 255)); } if (length === 4) { // #RGB format const r = _parseHexDigit(hex.charCodeAt(1)); const g = _parseHexDigit(hex.charCodeAt(2)); const b = _parseHexDigit(hex.charCodeAt(3)); return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b)); } if (length === 5) { // #RGBA format const r = _parseHexDigit(hex.charCodeAt(1)); const g = _parseHexDigit(hex.charCodeAt(2)); const b = _parseHexDigit(hex.charCodeAt(3)); const a = _parseHexDigit(hex.charCodeAt(4)); return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255)); } // Invalid color return null; } function _parseHexDigit(charCode: CharCode): number { switch (charCode) { case CharCode.Digit0: return 0; case CharCode.Digit1: return 1; case CharCode.Digit2: return 2; case CharCode.Digit3: return 3; case CharCode.Digit4: return 4; case CharCode.Digit5: return 5; case CharCode.Digit6: return 6; case CharCode.Digit7: return 7; case CharCode.Digit8: return 8; case CharCode.Digit9: return 9; case CharCode.a: return 10; case CharCode.A: return 10; case CharCode.b: return 11; case CharCode.B: return 11; case CharCode.c: return 12; case CharCode.C: return 12; case CharCode.d: return 13; case CharCode.D: return 13; case CharCode.e: return 14; case CharCode.E: return 14; case CharCode.f: return 15; case CharCode.F: return 15; } return 0; } } } }
the_stack
import * as fs from 'fs-extra'; import * as schema from './api-schema'; import { TextBuilder, asArray, filter, ApiDefinitions, ExtendedApi, readJsonDefs, createDoc, getEventTypeName, isMap, capitalizeFirstChar, Properties, hasChangeEvent, isInterfaceReference, isUnion, isTuple, isIndexedMap, isCallback, plainType } from './common'; const NEWLESS = ` This constructor can be called as a factory, without "new". Doing so allows \ passing an attributes object which may include (in addition to the properties) \ children, event listeners and layout shorthands. `.trim(); const FACTORY_DOC = ` /** * Creates an instance of this type. * * The given attributes object may include properties, * event listener and children, if supported. * * The second parameter should be given if this is the * return value of a functional component. In this case the * component itself (factory function) must be given to make it * a valid selector for the widget selector API such as * "$()" or the composite "find()" method. */ `; const HEADER = ` // Type definitions for Tabris.js \${VERSION} /// <reference path="globals.d.ts" /> // General helper types export interface Constructor<T> {new(...args: any[]): T; } type Omit<T, K extends string | symbol | number> = Pick<T, Exclude<keyof T, K>>; type ReadOnlyWidgetKeys<T> = T extends {readonly bounds: any} ? Extract<keyof T, 'bounds' | 'absoluteBounds' | 'cid' | 'jsxAttributes'> : never; type MethodKeysOf<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; // Tabris.js Helper Types type JSXDefaultChildren = Flatten<string|{cid?: never} & object>; export type Properties< T extends {set?: any}, U = Omit<T, 'set'> // prevent self-reference issues > = Partial<Omit<U, MethodKeysOf<U> | ReadOnlyWidgetKeys<U>>> & {cid?: never, data?: any}; // prevent empty object type as possible result, would allow any object type ListenersKeysOf<T> = { [K in keyof T]: T[K] extends Listeners<any> ? K : never }[keyof T]; export type UnpackListeners<T> = T extends Listeners<infer U> ? Listener<U> : T; export type EventOfListeners<T extends Listeners<any>> = T extends Listeners<infer U> ? U : never; type ListenersMap<T> = { [Key in ListenersKeysOf<T>]?: UnpackListeners<T[Key]>}; export type JSXShorthands<T> = T extends {layoutData?: LayoutDataValue} ? {center?: true, stretch?: true, stretchX?: true, stretchY?: true} : {}; export type JSXCandidate = {set: any; jsxAttributes: any}; // JSX.Element? export type JSXAttributes< T extends JSXCandidate, U = Omit<T, 'set' | 'jsxAttributes'> // prevent self-reference issues > = Properties<U> & ListenersMap<U> & JSXShorthands<U>; /** * The attributes object for the given widget type, includes all properties, * events, children and shorthands. To be passed to a JSX element or new-less * widget constructor call. * * The optional second parameter is the type of the "data" property. */ export type Attributes<T extends JSXCandidate, TData = any> = T['jsxAttributes'] & {data?: TData}; export type JSXCompositeAttributes<T extends Composite, U extends Widget> = JSXAttributes<T> & {apply?: RuleSet<T>, children?: JSXChildren<U>}; type ExtendedEvent<EventData, Target = {}> = EventObject<Target> & EventData; export type Listener<T = {}> = (ev: ExtendedEvent<T>) => any; type ListenersTriggerParam<T> = Omit<T, keyof EventObject<any>>; type MinimalEventObject<T extends object> = {target: T}; type TargetType<E extends object> = E extends MinimalEventObject<infer Target> ? Target : object; export interface Listeners<EventData extends {target: object}> { // tslint:disable-next-line:callable-types (listener: Listener<ExtendedEvent<EventData>>): TargetType<EventData>; } export type JSXChildren<T extends Widget> = T|WidgetCollection<T>|Array<T|WidgetCollection<T>>|{cid?: never}|undefined; export type SFC<T> = (attributes: object|null, children: any[]) => T; type Flatten<T> = T|Array<T>|undefined; export type Factory< OriginalConstructor extends Constructor<JSXCandidate> & {prototype: Instance}, Instance extends JSXCandidate = InstanceType<OriginalConstructor>, Selector extends Function = (...args: any[]) => Widget > = { ${FACTORY_DOC} (attributes?: Attributes<Instance>, selector?: Selector): Instance }; export type CallableConstructor< OriginalConstructor extends Constructor<JSXCandidate> & {prototype: Instance}, Instance extends JSXCandidate = InstanceType<OriginalConstructor>, Selector extends Function = (...args: any[]) => Widget > = { /** ${NEWLESS} */ new (...args: ConstructorParameters<OriginalConstructor>): Instance, ${FACTORY_DOC} (attributes?: Attributes<Instance>, selector?: Selector): Instance, prototype: Instance }; export as namespace tabris; `.trim(); const EVENT_OBJECT = 'EventObject<T>'; const eventObjectNames = [EVENT_OBJECT]; type Config = {files: string, globalTypeDefFiles: string[], localTypeDefFiles: string, version: string}; exports.generateDts = function generateTsd(config: Config) { writeGlobalsDts(config); writeTabrisDts(config); }; // #region read/write function writeGlobalsDts(config: Config) { const apiDefinitions = filter(readJsonDefs(config.files), def => !def.markdown_only); const globalApiDefinitions = filter(apiDefinitions, def => def.namespace && def.namespace === 'global'); const text = new TextBuilder(config.globalTypeDefFiles.map(file => fs.readFileSync(file, {encoding: 'utf-8'}))); renderDts(text, globalApiDefinitions); fs.writeFileSync('build/tabris/globals.d.ts', text.toString()); } function writeTabrisDts(config: Config) { const apiDefinitions = filter(readJsonDefs(config.files), def => !def.markdown_only); const tabrisApiDefinitions = filter(apiDefinitions, def => !def.namespace || def.namespace === 'tabris'); const text = new TextBuilder([HEADER.replace(/\${VERSION}/g, config.version), config.localTypeDefFiles]); renderDts(text, tabrisApiDefinitions); fs.writeFileSync('build/tabris/tabris.d.ts', text.toString()); } // #endregion // #region render objects/types function renderDts(text: TextBuilder, apiDefinitions: ApiDefinitions) { text.append(''); Object.keys(apiDefinitions).forEach(name => { renderTypeDefinition(text, apiDefinitions[name]); }); text.append(''); return text.toString(); } function renderTypeDefinition(text: TextBuilder, def: ExtendedApi) { text.append('// ' + (def.type || def.object || def.title)); if (def.isNativeObject) { text.append(''); renderEventObjectInterfaces(text, def); } text.append(''); if (def.type) { renderClass(text, def); renderSingletonVariable(text, def); } else { renderMethods(text, def); } text.append(''); } function renderSingletonVariable(text: TextBuilder, def: ExtendedApi) { if (def.object) { text.append(''); if (def.namespace && def.namespace === 'global') { text.append(`declare var ${def.object}: ${def.type};`); } else { text.append(`export const ${def.object}: ${def.type};`); } } } function renderClass(text: TextBuilder, def: ExtendedApi) { renderClassHeader(text, def); renderClassConstructor(text, def); renderMethods(text, def); renderProperties(text, def); renderEventProperties(text, def); renderClassFooter(text, def); if (def.supportsFactory) { renderTypeAlias(text, def); renderFactory(text, def); } } function renderClassHeader(text: TextBuilder, def: ExtendedApi) { if (def.supportsFactory) { text.append('export namespace widgets {'); text.append(''); text.indent++; } text.append(createDoc(def)); let str = (def.namespace && def.namespace === 'global') ? 'declare' : 'export'; str += def.interface ? ' interface ' : ' class '; str += genericType(def); if (def.extends) { str += ' extends '; str += toTypeScript(def.extends); } text.append(str + ' {'); text.indent++; } function renderClassFooter(text: TextBuilder, def: ExtendedApi) { text.indent--; text.append('}'); if (def.supportsFactory) { text.indent--; text.append('}'); text.append(''); } text.append(''); } function renderClassConstructor(text: TextBuilder, def: ExtendedApi) { const hasConstructor = typeof def.constructor === 'object'; const constructor = hasConstructor ? def.constructor : getInheritedConstructor(def.superAPI); if (constructor) { text.append(''); const access = constructor.access ? constructor.access + ' ' : ''; const paramList = createParamList(def, constructor.parameters || []); text.append(createDoc(def, def.isWidget || def.isPopup ? NEWLESS : '')); text.append(`${access}constructor(${paramList});`); } } function renderTypeAlias(text: TextBuilder, def: ExtendedApi) { text.append( `export type ${def.type}${renderGenericsDef(def.generics)} = ` + `widgets.${def.type}${renderGenerics(def.generics)};` ); } function renderFactory(text: TextBuilder, def: ExtendedApi) { const hasConstructor = typeof def.constructor === 'object'; const constructorDef = hasConstructor ? def.constructor : getInheritedConstructor(def.superAPI); if (!constructorDef) { throw new Error('Can not render a separate constructor function without super constructor'); } const _class = 'widgets.' + def.type; const constructor = def.type + 'Constructor'; const factory = def.type + 'Factory'; text.append(`export type ${constructor} = typeof ${_class};`); // The "CallableConstructor" interface is not used here since it can not support static members text.append(`export interface ${factory} extends Factory<${constructor}>, ${constructor} {}`); text.append(`export const ${def.type}: ${factory};`); } // #endregion // #region render events interfaces function renderEventObjectInterfaces(text: TextBuilder, def: ExtendedApi) { if (def.events) { Object.keys(def.events).filter(name => !!def.events[name].parameters).sort().forEach(name => { const eventType = getEventTypeName(def, name, def.events[name].parameters); if (!eventObjectNames.find(eventObjectName => eventObjectName === eventType)) { eventObjectNames.push(eventType); text.append(''); renderEventObjectInterface(text, name, def); } }); } } function renderEventObjectInterface(text: TextBuilder, name: string, def: ExtendedApi) { const parameters = def.events[name].parameters || {}; const hasGenerics = def.generics?.some(entry => !entry.default); const target = hasGenerics ? 'object' : plainType(def.type); if (hasGenerics) { throw new Error('Generics types without default can not have specialized events'); } text.append( `export interface ${getEventTypeName(def, name, parameters)}<Target = ${target}>` ); text.append(' extends EventObject<Target>'); text.append('{'); text.indent++; Object.keys(parameters).sort().forEach(param => { const values = []; (parameters[param].values || []).sort().forEach(value => { values.push(`'${value}'`); }); text.append( `readonly ${param}: ${union(values) || toTypeScript(parameters[param].ts_type || parameters[param].type)};` ); }); text.indent--; text.append('}'); } // #endregion // #region render members function renderMethods(text: TextBuilder, def: ExtendedApi) { Object.keys(def.methods || {}).sort().forEach(name => { asArray(def.methods[name]).filter(method => !method.docs_only).forEach(method => { text.append(''); text.append(createMethod(name, method, def)); }); }); if (def.statics && def.statics.methods) { Object.keys(def.statics.methods).sort().forEach(name => { asArray(def.statics.methods[name]).filter(method => !method.docs_only).forEach(method => { text.append(''); text.append(createMethod(name, method, def, true)); }); }); } } function createMethod( name: string, method: schema.Method, def: ExtendedApi, isStatic: boolean = false ) { const result = []; result.push(createDoc(method)); const paramList = createParamList(def, method.parameters); const define = def.namespace === 'global' ? 'declare' : 'export'; const declaration = (def.type ? createMethodModifiers(method, isStatic) : define + ' function ') + `${name}${renderGenericsDef(method.generics)}` + `(${paramList}): ${toTypeScript(method.ts_returns || method.returns || 'void')};`; result.push(declaration); return result.join('\n'); } function createMethodModifiers(method: schema.Method, isStatic: boolean) { return accessor(method) + (isStatic ? 'static ' : ''); } function renderProperties(text: TextBuilder, def: ExtendedApi) { Object.keys(def.properties || {}).sort().forEach(name => { text.append(''); text.append(createProperty(name, def.properties, def)); }); if (def.statics && def.statics.properties) { Object.keys(def.statics.properties || {}).sort().forEach(name => { text.append(''); text.append(createProperty(name, def.statics.properties, def, true)); }); } } function renderEventProperties(text: TextBuilder, def: ExtendedApi) { if (def.isNativeObject) { if (def.events) { Object.keys(def.events).sort().forEach(name => { text.append(''); text.append(createEventProperty(def, name)); }); } if (def.properties) { Object.keys(def.properties) .filter(name => hasChangeEvent(def.properties[name])) .sort() .forEach( name => { text.append(''); text.append(createPropertyChangedEventProperty(def, name)); }); } } } function createEventProperty(def: ExtendedApi, eventName: string) { const event = def.events[eventName]; const result = []; result.push(createDoc(Object.assign({}, event, {parameters: []}))); result.push(`on${capitalizeFirstChar(eventName)}: ` + `Listeners<${getEventTypeName(def, eventName, event.parameters)}<this>>;`); return result.join('\n'); } function createPropertyChangedEventProperty(def: ExtendedApi, propName: string) { const property = def.properties[propName]; const result = []; const standardDescription = `Fired when the [*${propName}*](#${propName}) property has changed.`; result.push(createDoc({ description: property.changeEventDescription || standardDescription })); result.push(`on${capitalizeFirstChar(propName)}Changed: ` + `ChangeListeners<this, '${propName}'>;`); return result.join('\n'); } function createProperty(name: string, properties: Properties, def: ExtendedApi, isStatic: boolean = false) { const result = []; const property = properties[name]; result.push(createDoc(property)); const readonly = property.readonly ? 'readonly ' : ''; const _static = isStatic ? 'static ' : ''; const optional = property.optional ? '?' : ''; const type = decodeType(property); if (property.separateAccessors) { result.push( `${accessor(property)}${_static}get ${name}(): ${type};` ); result.push('\n\n'); if (!property.readonly) { result.push('\n\n'); result.push( `${accessor(property)}${_static}set ${name}(value: ${type});` ); } } else { result.push( `${accessor(property)}${_static}${readonly}${name}${optional}: ${type};` ); } return result.join('\n'); } function createParamList(def: ExtendedApi, parameters: schema.Parameter[]) { return (parameters || []).map(param => `${param.name}${param.optional ? '?' : ''}: ${decodeType(param)}` ).join(', '); } function decodeType(param: Partial<schema.Parameter & schema.Property>) { if (param.values) { return union(param.values); } return toTypeScript(param.ts_type || param.type); } function union(values: Array<string | number | boolean>) { return (values || []).sort().map(value => typeof value === 'string' ? `'${value}'` : `${value}`).join(' | '); } // #endregion function getInheritedConstructor(def: ExtendedApi): typeof def.constructor { if (!def) { return null; } if (typeof def.constructor === 'object') { return def.constructor; } return def.superAPI ? getInheritedConstructor(def.superAPI) : null; } function genericType(def: ExtendedApi) { let result = def.type; if (def.generics) { result += renderGenericsDef(def.generics); } return result; } function accessor(def: {protected?: boolean, private?: boolean}) { if (def.protected) { return 'protected '; } if (def.private) { return 'private '; } return ''; } function toTypeScript(ref: schema.TypeReference): string { if (typeof ref === 'string') { return ref; } if (isInterfaceReference(ref)) { if (ref.interface === 'Array' && ref.generics.every(type => typeof type === 'string')) { return ref.generics[0] + '[]'; } return ref.interface + renderGenerics(ref.generics); } if (isUnion(ref)) { return ref.union.map(toTypeScript).join(' | '); } if (isTuple(ref)) { return '[' + ref.tuple.map(toTypeScript).join(', ') + ']'; } if (isMap(ref)) { const {map} = ref; const content = Object.keys(map).map(key => `${key}${map[key].optional ? '?' : ''}: ${toTypeScript(map[key].ts_type || map[key].type)}` ).join(', '); return '{' + content + '}'; } if (isIndexedMap(ref)) { const name = Object.keys(ref.map)[0]; const indexType = ref.indexType === 'SelectorString' ? 'string' : ref.indexType; return `{[${name}: ${indexType}]: ${toTypeScript(ref.map[name])}}`; } if (isCallback(ref)) { const parameters = ref.callback.map( arg => arg.name + ':' + toTypeScript(arg.type) ).join(', '); return `((${parameters}) => ${toTypeScript(ref.returns.type)})`; } throw new Error('Can not convert to TypeScript: ' + JSON.stringify(ref)); } function renderGenericsDef(generics: schema.GenericsDef): string { if (!generics) { return ''; } const content = generics.map(({name, extends: ext, default: def}) => name + (ext ? ` extends ${toTypeScript(ext)}` : '') + (def ? ` = ${toTypeScript(def)}` : '') ).join(', '); return '<' + content + '>'; } function renderGenerics(generics: schema.Generics | schema.GenericsDef): string { if (!generics) { return ''; } const list = (generics as unknown[]).map(param => { if (typeof param === 'string') { return param; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const name = (param as any).name; if (typeof name === 'string') { return name; } return toTypeScript(param as schema.TypeReference); }); return '<' + list.join(', ') + '>'; }
the_stack
import { Response } from "@webiny/handler-graphql"; import { CmsEntry, CmsContext, CmsModel, CmsEntryListWhere } from "~/types"; import { NotAuthorizedResponse } from "@webiny/api-security"; import { GraphQLSchemaPlugin } from "@webiny/handler-graphql/plugins/GraphQLSchemaPlugin"; import { getEntryTitle } from "~/content/plugins/utils/getEntryTitle"; import WebinyError from "@webiny/error"; interface EntriesByModel { [key: string]: string[]; } type GetContentEntryType = "latest" | "published" | "exact"; interface CmsEntryRecord { id: string; entryId: string; model: { modelId: string; name: string; }; status: string; title: string; } interface FetchMethod { (model: CmsModel, ids: string[]): Promise<CmsEntry[]>; } const getFetchMethod = (type: GetContentEntryType, context: CmsContext): FetchMethod => { if (!getContentEntriesMethods[type]) { throw new WebinyError( `Unknown getContentEntries method "${type}". Could not fetch content entries.`, "UNKNOWN_METHOD_ERROR", { type } ); } const methodName = getContentEntriesMethods[type] as GetContentEntryMethods; if (!context.cms[methodName]) { throw new WebinyError( `Unknown context.cms method "${methodName}". Could not fetch content entries.`, "UNKNOWN_METHOD_ERROR", { type, methodName } ); } return context.cms[methodName]; }; /** * Function to get the list of content entries depending on latest, published or exact GraphQL queries. */ interface GetContentEntriesParams { args: { entries: Pick<CmsEntry, "id" | "modelId">[]; }; context: CmsContext; type: GetContentEntryType; } enum GetContentEntryMethods { getLatestEntriesByIds = "getLatestEntriesByIds", getPublishedEntriesByIds = "getPublishedEntriesByIds", getEntriesByIds = "getEntriesByIds" } const getContentEntriesMethods = { latest: "getLatestEntriesByIds", published: "getPublishedEntriesByIds", exact: "getEntriesByIds" }; const getContentEntries = async (params: GetContentEntriesParams): Promise<Response> => { const { args, context, type } = params; const method = getFetchMethod(type, context); const models = await context.cms.listModels(); const modelsMap = models.reduce((collection, model) => { collection[model.modelId] = model; return collection; }, {} as Record<string, CmsModel>); const argsEntries = args.entries as Pick<CmsEntry, "id" | "modelId">[]; const entriesByModel = argsEntries.reduce((collection, ref) => { if (!collection[ref.modelId]) { collection[ref.modelId] = []; } else if (collection[ref.modelId].includes(ref.id)) { return collection; } collection[ref.modelId].push(ref.id); return collection; }, {} as EntriesByModel); const getters: Promise<CmsEntry[]>[] = Object.keys(entriesByModel).map(async modelId => { return method(modelsMap[modelId], entriesByModel[modelId]); }); if (getters.length === 0) { return new Response([]); } const results = await Promise.all(getters); const entries = results .reduce((collection, items) => { return collection.concat( items.map(item => { const model = modelsMap[item.modelId]; return { id: item.id, entryId: item.entryId, model: { modelId: model.modelId, name: model.name }, status: item.status, title: getEntryTitle(model, item) }; }) ); }, [] as CmsEntryRecord[]) .filter(Boolean); return new Response(entries); }; /** * Function to fetch a single content entry depending on latest, published or exact GraphQL query. */ interface GetContentEntryParams { args: { entry: Pick<CmsEntry, "id" | "modelId">; }; context: CmsContext; type: "latest" | "published" | "exact"; } const getContentEntry = async ( params: GetContentEntryParams ): Promise<Response | NotAuthorizedResponse> => { const { args, context, type } = params; if (!getContentEntriesMethods[type]) { throw new WebinyError( `Unknown getContentEntry method "${type}". Could not fetch content entry.`, "UNKNOWN_METHOD_ERROR", { args, type } ); } const method = getFetchMethod(type, context); const { modelId, id } = args.entry; const models = await context.cms.listModels(); const model = models.find(m => m.modelId === modelId); if (!model) { return new NotAuthorizedResponse({ data: { modelId } }); } const result = await method(model, [id]); const entry = result.shift(); if (!entry) { return new Response(null); } return new Response({ id: entry.id, entryId: entry.entryId, model: { modelId: model.modelId, name: model.name }, status: entry.status, title: getEntryTitle(model, entry) }); }; const plugin = (context: CmsContext): GraphQLSchemaPlugin<CmsContext> => { if (!context.cms.MANAGE) { return new GraphQLSchemaPlugin({ typeDefs: "", resolvers: {} }); } return new GraphQLSchemaPlugin<CmsContext>({ typeDefs: /* GraphQL */ ` type CmsModelMeta { modelId: String name: String } type CmsPublishedContentEntry { id: ID! entryId: String! title: String } type CmsContentEntry { id: ID! entryId: String! model: CmsModelMeta status: String title: String published: CmsPublishedContentEntry } type CmsContentEntriesResponse { data: [CmsContentEntry] error: CmsError } type CmsContentEntryResponse { data: CmsContentEntry error: CmsError } input CmsModelEntryInput { modelId: ID! id: ID! } extend type Query { # Search content entries for given content models using the query string. searchContentEntries( modelIds: [ID!]! query: String fields: [String!] limit: Int ): CmsContentEntriesResponse # Get content entry meta data getContentEntry(entry: CmsModelEntryInput!): CmsContentEntryResponse getLatestContentEntry(entry: CmsModelEntryInput!): CmsContentEntryResponse getPublishedContentEntry(entry: CmsModelEntryInput!): CmsContentEntryResponse # Get content entries meta data getContentEntries(entries: [CmsModelEntryInput!]!): CmsContentEntriesResponse getLatestContentEntries(entries: [CmsModelEntryInput!]!): CmsContentEntriesResponse getPublishedContentEntries( entries: [CmsModelEntryInput!]! ): CmsContentEntriesResponse } `, resolvers: { CmsContentEntry: { published: async (parent, _, context) => { try { const models = await context.cms.listModels(); const model = models.find(({ modelId }) => { return parent.model.modelId === modelId; }); if (!model) { return null; } const [entry] = await context.cms.getPublishedEntriesByIds(model, [ parent.id ]); if (!entry) { return null; } return { id: entry.id, entryId: entry.entryId, title: getEntryTitle(model, entry) }; } catch (ex) { return null; } } }, Query: { async searchContentEntries(_, args: any, context) { const { modelIds, fields, query, limit = 10 } = args; const models = await context.cms.listModels(); const getters = models .filter(model => modelIds.includes(model.modelId)) .map(async model => { const modelManager = await context.cms.getModelManager(model.modelId); const where: CmsEntryListWhere = {}; const [items] = await modelManager.listLatest({ limit, where, search: !!query ? query : undefined, fields: fields || [] }); return items.map((entry: CmsEntry) => { return { id: entry.id, entryId: entry.entryId, model: { modelId: model.modelId, name: model.name }, status: entry.status, title: getEntryTitle(model, entry), // We need `savedOn` to sort entries from latest to oldest savedOn: entry.savedOn }; }); }); const entries = await Promise.all(getters).then(results => results.reduce((result, item) => result.concat(item), []) ); return new Response( entries .sort((a, b) => Date.parse(b.savedOn) - Date.parse(a.savedOn)) .slice(0, limit) ); }, async getContentEntry(_, args: any, context) { return getContentEntry({ args, context, type: "exact" }); }, async getLatestContentEntry(_, args: any, context) { return getContentEntry({ args, context, type: "latest" }); }, async getPublishedContentEntry(_, args: any, context) { return getContentEntry({ args, context, type: "published" }); }, async getContentEntries(_, args: any, context) { return getContentEntries({ args, context, type: "exact" }); // const models = await context.cms.listModels(); // // const modelsMap = models.reduce((collection, model) => { // collection[model.modelId] = model; // return collection; // }, {} as Record<string, CmsModel>); // // const argsEntries = args.entries as Pick<CmsEntry, "id" | "modelId">[]; // // const entriesByModel = argsEntries.reduce((collection, ref) => { // if (!collection[ref.modelId]) { // collection[ref.modelId] = []; // } else if (collection[ref.modelId].includes(ref.id)) { // return collection; // } // collection[ref.modelId].push(ref.id); // return collection; // }, {} as EntriesByModel); // // const getters: Promise<CmsEntry[]>[] = Object.keys(entriesByModel).map( // async modelId => { // return context.cms.getEntriesByIds( // modelsMap[modelId], // entriesByModel[modelId] // ); // } // ); // // if (getters.length === 0) { // return new Response([]); // } // // const results = await Promise.all(getters); // // const entries = results.reduce((collection, items) => { // return collection.concat( // items.map(item => { // const model = modelsMap[item.modelId]; // // return { // id: item.id, // model: { // modelId: model.modelId, // name: model.name // }, // status: item.status, // title: getEntryTitle(model, item) // }; // }) // ); // }, [] as any[]); // // return new Response(entries); }, async getLatestContentEntries(_, args: any, context) { return getContentEntries({ args, context, type: "latest" }); }, async getPublishedContentEntries(_, args: any, context) { return getContentEntries({ args, context, type: "published" }); } } } }); }; export default plugin;
the_stack
import * as msRest from "@azure/ms-rest-js"; import { TokenCredential } from "@azure/core-auth"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "./models"; import * as Mappers from "./models/mappers"; import * as Parameters from "./models/parameters"; import * as operations from "./operations"; import { RecoveryServicesBackupClientContext } from "./recoveryServicesBackupClientContext"; class RecoveryServicesBackupClient extends RecoveryServicesBackupClientContext { // Operation groups backupResourceVaultConfigs: operations.BackupResourceVaultConfigs; backupResourceEncryptionConfigs: operations.BackupResourceEncryptionConfigs; privateEndpointConnection: operations.PrivateEndpointConnectionOperations; privateEndpoint: operations.PrivateEndpointOperations; bMSPrepareDataMoveOperationResult: operations.BMSPrepareDataMoveOperationResult; protectedItems: operations.ProtectedItems; protectedItemOperationResults: operations.ProtectedItemOperationResults; recoveryPoints: operations.RecoveryPoints; restores: operations.Restores; backupPolicies: operations.BackupPolicies; protectionPolicies: operations.ProtectionPolicies; protectionPolicyOperationResults: operations.ProtectionPolicyOperationResults; backupJobs: operations.BackupJobs; jobDetails: operations.JobDetails; jobCancellations: operations.JobCancellations; jobOperationResults: operations.JobOperationResults; exportJobsOperationResults: operations.ExportJobsOperationResults; jobs: operations.Jobs; backupProtectedItems: operations.BackupProtectedItems; operation: operations.Operation; backupEngines: operations.BackupEngines; protectionContainerRefreshOperationResults: operations.ProtectionContainerRefreshOperationResults; protectableContainers: operations.ProtectableContainers; protectionContainers: operations.ProtectionContainers; backupWorkloadItems: operations.BackupWorkloadItems; protectionContainerOperationResults: operations.ProtectionContainerOperationResults; backups: operations.Backups; protectedItemOperationStatuses: operations.ProtectedItemOperationStatuses; itemLevelRecoveryConnections: operations.ItemLevelRecoveryConnections; backupOperationResults: operations.BackupOperationResults; backupOperationStatuses: operations.BackupOperationStatuses; protectionPolicyOperationStatuses: operations.ProtectionPolicyOperationStatuses; backupProtectableItems: operations.BackupProtectableItems; backupProtectionContainers: operations.BackupProtectionContainers; securityPINs: operations.SecurityPINs; recoveryPointsRecommendedForMove: operations.RecoveryPointsRecommendedForMove; backupUsageSummariesCRR: operations.BackupUsageSummariesCRR; aadProperties: operations.AadProperties; crossRegionRestore: operations.CrossRegionRestore; backupCrrJobDetails: operations.BackupCrrJobDetails; backupCrrJobs: operations.BackupCrrJobs; crrOperationResults: operations.CrrOperationResults; crrOperationStatus: operations.CrrOperationStatus; backupResourceStorageConfigs: operations.BackupResourceStorageConfigs; recoveryPointsCrr: operations.RecoveryPointsCrr; backupProtectedItemsCrr: operations.BackupProtectedItemsCrr; protectionIntent: operations.ProtectionIntentOperations; backupStatus: operations.BackupStatus; featureSupport: operations.FeatureSupport; backupProtectionIntent: operations.BackupProtectionIntent; backupUsageSummaries: operations.BackupUsageSummaries; operations: operations.Operations; /** * Initializes a new instance of the RecoveryServicesBackupClient class. * @param credentials Credentials needed for the client to connect to Azure. Credentials * implementing the TokenCredential interface from the @azure/identity package are recommended. For * more information about these credentials, see * {@link https://www.npmjs.com/package/@azure/identity}. Credentials implementing the * ServiceClientCredentials interface from the older packages @azure/ms-rest-nodeauth and * @azure/ms-rest-browserauth are also supported. * @param subscriptionId The subscription Id. * @param [options] The parameter options */ constructor( credentials: msRest.ServiceClientCredentials | TokenCredential, subscriptionId: string, options?: Models.RecoveryServicesBackupClientOptions ) { super(credentials, subscriptionId, options); this.backupResourceVaultConfigs = new operations.BackupResourceVaultConfigs(this); this.backupResourceEncryptionConfigs = new operations.BackupResourceEncryptionConfigs(this); this.privateEndpointConnection = new operations.PrivateEndpointConnectionOperations(this); this.privateEndpoint = new operations.PrivateEndpointOperations(this); this.bMSPrepareDataMoveOperationResult = new operations.BMSPrepareDataMoveOperationResult(this); this.protectedItems = new operations.ProtectedItems(this); this.protectedItemOperationResults = new operations.ProtectedItemOperationResults(this); this.recoveryPoints = new operations.RecoveryPoints(this); this.restores = new operations.Restores(this); this.backupPolicies = new operations.BackupPolicies(this); this.protectionPolicies = new operations.ProtectionPolicies(this); this.protectionPolicyOperationResults = new operations.ProtectionPolicyOperationResults(this); this.backupJobs = new operations.BackupJobs(this); this.jobDetails = new operations.JobDetails(this); this.jobCancellations = new operations.JobCancellations(this); this.jobOperationResults = new operations.JobOperationResults(this); this.exportJobsOperationResults = new operations.ExportJobsOperationResults(this); this.jobs = new operations.Jobs(this); this.backupProtectedItems = new operations.BackupProtectedItems(this); this.operation = new operations.Operation(this); this.backupEngines = new operations.BackupEngines(this); this.protectionContainerRefreshOperationResults = new operations.ProtectionContainerRefreshOperationResults( this ); this.protectableContainers = new operations.ProtectableContainers(this); this.protectionContainers = new operations.ProtectionContainers(this); this.backupWorkloadItems = new operations.BackupWorkloadItems(this); this.protectionContainerOperationResults = new operations.ProtectionContainerOperationResults( this ); this.backups = new operations.Backups(this); this.protectedItemOperationStatuses = new operations.ProtectedItemOperationStatuses(this); this.itemLevelRecoveryConnections = new operations.ItemLevelRecoveryConnections(this); this.backupOperationResults = new operations.BackupOperationResults(this); this.backupOperationStatuses = new operations.BackupOperationStatuses(this); this.protectionPolicyOperationStatuses = new operations.ProtectionPolicyOperationStatuses(this); this.backupProtectableItems = new operations.BackupProtectableItems(this); this.backupProtectionContainers = new operations.BackupProtectionContainers(this); this.securityPINs = new operations.SecurityPINs(this); this.recoveryPointsRecommendedForMove = new operations.RecoveryPointsRecommendedForMove(this); this.backupUsageSummariesCRR = new operations.BackupUsageSummariesCRR(this); this.aadProperties = new operations.AadProperties(this); this.crossRegionRestore = new operations.CrossRegionRestore(this); this.backupCrrJobDetails = new operations.BackupCrrJobDetails(this); this.backupCrrJobs = new operations.BackupCrrJobs(this); this.crrOperationResults = new operations.CrrOperationResults(this); this.crrOperationStatus = new operations.CrrOperationStatus(this); this.backupResourceStorageConfigs = new operations.BackupResourceStorageConfigs(this); this.recoveryPointsCrr = new operations.RecoveryPointsCrr(this); this.backupProtectedItemsCrr = new operations.BackupProtectedItemsCrr(this); this.protectionIntent = new operations.ProtectionIntentOperations(this); this.backupStatus = new operations.BackupStatus(this); this.featureSupport = new operations.FeatureSupport(this); this.backupProtectionIntent = new operations.BackupProtectionIntent(this); this.backupUsageSummaries = new operations.BackupUsageSummaries(this); this.operations = new operations.Operations(this); } /** * Fetches operation status for data move operation on vault * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param operationId * @param [options] The optional parameters * @returns Promise<Models.GetOperationStatusResponse> */ getOperationStatus( vaultName: string, resourceGroupName: string, operationId: string, options?: msRest.RequestOptionsBase ): Promise<Models.GetOperationStatusResponse>; /** * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param operationId * @param callback The callback */ getOperationStatus( vaultName: string, resourceGroupName: string, operationId: string, callback: msRest.ServiceCallback<Models.OperationStatus> ): void; /** * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param operationId * @param options The optional parameters * @param callback The callback */ getOperationStatus( vaultName: string, resourceGroupName: string, operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus> ): void; getOperationStatus( vaultName: string, resourceGroupName: string, operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus> ): Promise<Models.GetOperationStatusResponse> { return this.sendOperationRequest( { vaultName, resourceGroupName, operationId, options }, getOperationStatusOperationSpec, callback ) as Promise<Models.GetOperationStatusResponse>; } /** * Prepares source vault for Data Move operation * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param parameters Prepare data move request * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ bMSPrepareDataMove( vaultName: string, resourceGroupName: string, parameters: Models.PrepareDataMoveRequest, options?: msRest.RequestOptionsBase ): Promise<msRest.RestResponse> { return this.beginBMSPrepareDataMove( vaultName, resourceGroupName, parameters, options ).then((lroPoller) => lroPoller.pollUntilFinished()); } /** * Triggers Data Move Operation on target vault * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param parameters Trigger data move request * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ bMSTriggerDataMove( vaultName: string, resourceGroupName: string, parameters: Models.TriggerDataMoveRequest, options?: msRest.RequestOptionsBase ): Promise<msRest.RestResponse> { return this.beginBMSTriggerDataMove( vaultName, resourceGroupName, parameters, options ).then((lroPoller) => lroPoller.pollUntilFinished()); } /** * @summary Move recovery point from one datastore to another store. * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param fabricName * @param containerName * @param protectedItemName * @param recoveryPointId * @param parameters Move Resource Across Tiers Request * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ moveRecoveryPoint( vaultName: string, resourceGroupName: string, fabricName: string, containerName: string, protectedItemName: string, recoveryPointId: string, parameters: Models.MoveRPAcrossTiersRequest, options?: msRest.RequestOptionsBase ): Promise<msRest.RestResponse> { return this.beginMoveRecoveryPoint( vaultName, resourceGroupName, fabricName, containerName, protectedItemName, recoveryPointId, parameters, options ).then((lroPoller) => lroPoller.pollUntilFinished()); } /** * Prepares source vault for Data Move operation * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param parameters Prepare data move request * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginBMSPrepareDataMove( vaultName: string, resourceGroupName: string, parameters: Models.PrepareDataMoveRequest, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.sendLRORequest( { vaultName, resourceGroupName, parameters, options }, beginBMSPrepareDataMoveOperationSpec, options ); } /** * Triggers Data Move Operation on target vault * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param parameters Trigger data move request * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginBMSTriggerDataMove( vaultName: string, resourceGroupName: string, parameters: Models.TriggerDataMoveRequest, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.sendLRORequest( { vaultName, resourceGroupName, parameters, options }, beginBMSTriggerDataMoveOperationSpec, options ); } /** * @summary Move recovery point from one datastore to another store. * @param vaultName The name of the recovery services vault. * @param resourceGroupName The name of the resource group where the recovery services vault is * present. * @param fabricName * @param containerName * @param protectedItemName * @param recoveryPointId * @param parameters Move Resource Across Tiers Request * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginMoveRecoveryPoint( vaultName: string, resourceGroupName: string, fabricName: string, containerName: string, protectedItemName: string, recoveryPointId: string, parameters: Models.MoveRPAcrossTiersRequest, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.sendLRORequest( { vaultName, resourceGroupName, fabricName, containerName, protectedItemName, recoveryPointId, parameters, options }, beginMoveRecoveryPointOperationSpec, options ); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationStatusOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupstorageconfig/vaultstorageconfig/operationStatus/{operationId}", urlParameters: [ Parameters.vaultName, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.operationId ], queryParameters: [Parameters.apiVersion0], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.NewErrorResponse } }, serializer }; const beginBMSPrepareDataMoveOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupstorageconfig/vaultstorageconfig/prepareDataMove", urlParameters: [Parameters.vaultName, Parameters.resourceGroupName, Parameters.subscriptionId], queryParameters: [Parameters.apiVersion0], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.PrepareDataMoveRequest, required: true } }, responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.NewErrorResponse } }, serializer }; const beginBMSTriggerDataMoveOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupstorageconfig/vaultstorageconfig/triggerDataMove", urlParameters: [Parameters.vaultName, Parameters.resourceGroupName, Parameters.subscriptionId], queryParameters: [Parameters.apiVersion0], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.TriggerDataMoveRequest, required: true } }, responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.NewErrorResponse } }, serializer }; const beginMoveRecoveryPointOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/move", urlParameters: [ Parameters.vaultName, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.fabricName, Parameters.containerName, Parameters.protectedItemName, Parameters.recoveryPointId ], queryParameters: [Parameters.apiVersion0], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.MoveRPAcrossTiersRequest, required: true } }, responses: { 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; export { RecoveryServicesBackupClient, RecoveryServicesBackupClientContext, Models as RecoveryServicesBackupModels, Mappers as RecoveryServicesBackupMappers }; export * from "./operations";
the_stack
import assert from 'assert'; import * as Ast from '../ast'; import Type from "../type"; import ReduceOp from './reduceop'; // Low-level ThingTalk operations // Each ThingTalk AST node can be implemented in terms of these low-level ops // Each of these ops can be compiled into JS code individually // PointWiseOp : operates on each produced tuple export class PointWiseOp { } export namespace PointWiseOp { export class Projection extends PointWiseOp { constructor(public args : Set<string>) { super(); } toString() { return `PointWiseOp.Projection(${this.args})`; } } export class Compute extends PointWiseOp { constructor(public expression : Ast.Value, public alias : string) { super(); } toString() { return `PointWiseOp.Compute(${this.expression} as ${this.alias})`; } } export class BooleanCompute extends PointWiseOp { constructor(public booleanExpression : Ast.BooleanExpression) { super(); } toString() { return `PointWiseOp.BooleanCompute(${this.booleanExpression})`; } } } type SortHint = [string, 'asc'|'desc']; export class QueryInvocationHints { projection : Set<string>; filter : Ast.BooleanExpression; sort : SortHint|undefined; limit : number|undefined; constructor(projection : Set<string>, filter = Ast.BooleanExpression.True, sort ?: SortHint, limit ?: number) { assert(filter instanceof Ast.BooleanExpression); assert(sort === undefined || Array.isArray(sort)); assert(projection instanceof Set); assert(limit === undefined || typeof limit === 'number'); this.filter = filter; this.sort = sort; this.projection = projection; this.limit = limit; } clone() : QueryInvocationHints { return new QueryInvocationHints(new Set(this.projection), this.filter, this.sort, this.limit); } } /** * A low-level operation on streams */ export abstract class StreamOp { abstract ast : Ast.Expression|null; } export namespace StreamOp { export class Now extends StreamOp { constructor(public table : TableOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.Now(${this.table})`; } } export class InvokeVarRef extends StreamOp { constructor(public name : string, public in_params : Ast.InputParam[], public ast : Ast.Expression, public hints : QueryInvocationHints) { super(); } toString() { return `StreamOp.InvokeVarRef(${this.name}, ${this.in_params.map((ip) => ip.prettyprint()).join(', ')})`; } } export class InvokeSubscribe extends StreamOp { constructor(public invocation : Ast.Invocation, public ast : Ast.Expression, public hints : QueryInvocationHints) { super(); } toString() { return `StreamOp.InvokeSubscribe(${this.invocation.prettyprint()})`; } } export class Timer extends StreamOp { constructor(public base : Ast.Value|undefined, public interval : Ast.Value, public frequency : Ast.Value|undefined, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.Timer(${this.base}, ${this.interval}, ${this.frequency})`; } } export class AtTimer extends StreamOp { constructor(public time : Ast.Value, public expiration_date : Ast.Value|undefined, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.AtTimer(${this.time}, ${this.expiration_date})`; } } export class OnTimer extends StreamOp { constructor(public date : Ast.Value, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.OnTimer(${this.date})`; } } export class Filter extends StreamOp { constructor(public stream : StreamOp, public filter : BooleanExpressionOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.Filter(${this.stream}, ${this.filter})`; } } export class Map extends StreamOp { constructor(public stream : StreamOp, public op : PointWiseOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.Map(${this.stream}, ${this.op})`; } } export class EdgeNew extends StreamOp { constructor(public stream : StreamOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.EdgeNew(${this.stream})`; } } export class EdgeFilter extends StreamOp { constructor(public stream : StreamOp, public filter : BooleanExpressionOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.EdgeFilter(${this.stream}, ${this.filter})`; } } export class Union extends StreamOp { constructor(public lhs : StreamOp, public rhs : StreamOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.Union(${this.lhs}, ${this.rhs})`; } } /** When the stream fires, get the whole table (ignore the stream). This is used to implement certain "monitor(table)" where the table needs to be recomputed on subscribe. */ export class InvokeTable extends StreamOp { constructor(public stream : StreamOp, public table : TableOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.InvokeTable(${this.stream}, ${this.table})`; } } /** * When the stream fires, get the whole table and join it. */ export class Join extends StreamOp { constructor(public stream : StreamOp, public table : TableOp, public ast : Ast.Expression) { super(); } toString() { return `StreamOp.Join(${this.stream}, ${this.table})`; } } } type UnaryStreamOp = StreamOp.Filter | StreamOp.Map | StreamOp.EdgeFilter | StreamOp.EdgeNew; export function isUnaryStreamOp(op : StreamOp) : op is UnaryStreamOp { return op instanceof StreamOp.Filter || op instanceof StreamOp.Map || op instanceof StreamOp.EdgeFilter || op instanceof StreamOp.EdgeNew; } /** * A low-level operation on an in-memory table. */ export abstract class TableOp { handle_thingtalk = false; abstract device : Ast.DeviceSelector|null; abstract ast : Ast.Expression; } export namespace TableOp { export class InvokeVarRef extends TableOp { device = null; constructor(public name : string, public in_params : Ast.InputParam[], public ast : Ast.Expression, public hints : QueryInvocationHints) { super(); } toString() { return `TableOp.InvokeVarRef(${this.name}, ${this.in_params.map((ip) => ip.prettyprint())})`; } } export class InvokeGet extends TableOp { constructor(public invocation : Ast.Invocation, public device : Ast.DeviceSelector|null, public handle_thingtalk : boolean, public ast : Ast.Expression, public hints : QueryInvocationHints) { super(); } toString() { return `TableOp.InvokeGet(${this.invocation.prettyprint()})`; } } export class Filter extends TableOp { constructor(public table : TableOp, public filter : BooleanExpressionOp, public device : Ast.DeviceSelector|null, public handle_thingtalk : boolean, public ast : Ast.Expression) { super(); } toString() { return `TableOp.Filter(${this.table}, ${this.filter})`; } } export class Map extends TableOp { constructor(public table : TableOp, public op : PointWiseOp, public device : Ast.DeviceSelector|null, public handle_thingtalk : boolean, public ast : Ast.Expression) { super(); } toString() { return `TableOp.Map(${this.table}, ${this.op})`; } } export class Reduce extends TableOp { constructor(public table : TableOp, public op : ReduceOp<unknown>, public device : Ast.DeviceSelector|null, public handle_thingtalk : boolean, public ast : Ast.Expression) { super(); } toString() { return `TableOp.Reduce(${this.table}, ${this.op})`; } } export class Join extends TableOp { constructor(public lhs : TableOp, public rhs : TableOp, public device : Ast.DeviceSelector|null, public handle_thingtalk : boolean, public ast : Ast.Expression) { super(); } toString() { return `TableOp.Join(${this.lhs}, ${this.rhs})`; } } export class CrossJoin extends TableOp { constructor(public lhs : TableOp, public rhs : TableOp, public device : Ast.DeviceSelector|null, public handle_thingtalk : boolean, public ast : Ast.Expression) { super(); } toString() { return `TableOp.CrossJoin(${this.lhs}, ${this.rhs})`; } } export class NestedLoopJoin extends TableOp { constructor(public lhs : TableOp, public rhs : TableOp, public device : Ast.DeviceSelector|null, public handle_thingtalk : boolean, public ast : Ast.Expression) { super(); } toString() { return `TableOp.NestedLoopJoin(${this.lhs}, ${this.rhs})`; } } } type UnaryTableOp = TableOp.Filter | TableOp.Map | TableOp.Reduce; export function isUnaryTableOp(op : TableOp) : op is UnaryTableOp { return op instanceof TableOp.Filter || op instanceof TableOp.Map || op instanceof TableOp.Reduce; } export abstract class ActionOp { } export namespace ActionOp { export class InvokeDo extends ActionOp { constructor(public invocation : Ast.Invocation, public ast : Ast.Expression) { super(); } toString() { return `ActionOp.InvokeDo(${this.invocation.prettyprint()})`; } } export class InvokeVarRef extends ActionOp { constructor(public name : string, public in_params : Ast.InputParam[], public ast : Ast.Expression) { super(); } toString() { return `ActionOp.InvokeVarRef(${this.name}, ${this.in_params.map((ip) => ip.prettyprint())})`; } } } /** * The overall structure of the rule. * This reflects the overall "when => get* => do" structure of ThingTalk * which is what it optimizes for. */ export class RuleOp { constructor(public stream : StreamOp|null, public action : ActionOp|null, public ast : Ast.ExpressionStatement|Ast.ReturnStatement) { } toString() { return `RuleOp(${this.stream}, ${this.action})`; } } export abstract class BooleanExpressionOp { static True : ConstantBooleanExpressionOp; static False : ConstantBooleanExpressionOp; public ast : Ast.BooleanExpression; protected constructor(ast : Ast.BooleanExpression) { this.ast = ast; } } class ConstantBooleanExpressionOp extends BooleanExpressionOp { constructor(public readonly value : boolean) { super(value ? Ast.BooleanExpression.True : Ast.BooleanExpression.False); } toString() { return `BooleanExpressionOp.Constant(${this.value})`; } } BooleanExpressionOp.True = new ConstantBooleanExpressionOp(true); BooleanExpressionOp.False = new ConstantBooleanExpressionOp(false); export namespace BooleanExpressionOp { export class And extends BooleanExpressionOp { constructor(ast : Ast.AndBooleanExpression, public operands : BooleanExpressionOp[]) { super(ast); } toString() { return `BooleanExpressionOp.And(${this.operands.join(', ')})`; } } export class Or extends BooleanExpressionOp { constructor(ast : Ast.OrBooleanExpression, public operands : BooleanExpressionOp[]) { super(ast); } toString() { return `BooleanExpressionOp.Or(${this.operands.join(', ')})`; } } export class Not extends BooleanExpressionOp { constructor(ast : Ast.NotBooleanExpression, public expr : BooleanExpressionOp) { super(ast); } toString() { return `BooleanExpressionOp.Not(${this.expr})`; } } export class Atom extends BooleanExpressionOp { constructor(ast : Ast.AtomBooleanExpression|Ast.ComputeBooleanExpression, public lhs : Ast.Value, public operator : string, public rhs : Ast.Value, public overload : Type[]|null) { super(ast); } toString() { return `BooleanExpressionOp.Atom(${this.lhs}, ${this.operator}, ${this.rhs})`; } } export class ExistentialSubquery extends BooleanExpressionOp { constructor(ast : Ast.ExistentialSubqueryBooleanExpression, public subquery : TableOp) { super(ast); } toString() { return `BooleanExpressionOp.ExistentialSubquery(${this.subquery})`; } } export class ComparisonSubquery extends BooleanExpressionOp { constructor(ast : Ast.ComparisonSubqueryBooleanExpression, public lhs : Ast.Value, public operator : string, public rhs : Ast.Value, public subquery : TableOp, public overload : Type[]|null) { super(ast); } toString() { return `BooleanExpressionOp.ComparisonSubquery(${this.lhs}, ${this.operator}, ${this.rhs}, ${this.subquery})`; } } }
the_stack
import { mapToInternalRecordValidationSchema } from './record-schema.mapper'; import { RecordValidationSchema, RecordValidationFunctionSync, InternalRecordValidationSchema, RecordValidationFunctionAsync, FullRecordValidation, } from '../model'; describe('record-schema.mapper specs', () => { it('spec #1: should return empty object when it feeds recordValidationSchema equals undefined', () => { // Arrange const recordValidationSchema: RecordValidationSchema = void 0; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert expect(result).toEqual({}); }); it('spec #2: should return empty object when it feeds recordValidationSchema equals null', () => { // Arrange const recordValidationSchema: RecordValidationSchema = null; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert expect(result).toEqual({}); }); it('spec #3: should return empty object when it feeds recordValidationSchema equals empty object', () => { // Arrange const recordValidationSchema: RecordValidationSchema = {}; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert expect(result).toEqual({}); }); it('spec #4: should return InternalRecordValidationSchema when it feeds recordValidationSchema with one RecordValidationFunctionSync', done => { // Arrange const validator: RecordValidationFunctionSync = () => ({ succeeded: true, message: 'test message', type: 'test type', }); const recordValidationSchema: RecordValidationSchema = { recordId: [validator], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: void 0, }, ], }; expect(result).toEqual(expectedResult); result['recordId'][0].validator(null).then(validationResult => { expect(validationResult).toEqual({ succeeded: true, message: 'test message', type: 'test type', }); done(); }); }); it('spec #5: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two RecordValidationFunctionSync', done => { // Arrange const validator1: RecordValidationFunctionSync = () => ({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const validator2: RecordValidationFunctionSync = () => ({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const recordValidationSchema: RecordValidationSchema = { recordId: [validator1, validator2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: void 0, }, { validator: expect.any(Function), message: void 0, }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId'][0].validator(null), result['recordId'][1].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #6: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two records with one RecordValidationFunctionSync', done => { // Arrange const validator1: RecordValidationFunctionSync = () => ({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const validator2: RecordValidationFunctionSync = () => ({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const recordValidationSchema: RecordValidationSchema = { recordId1: [validator1], recordId2: [validator2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId1: [ { validator: expect.any(Function), message: void 0, }, ], recordId2: [ { validator: expect.any(Function), message: void 0, }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId1'][0].validator(null), result['recordId2'][0].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #7: should return InternalRecordValidationSchema when it feeds recordValidationSchema with one RecordValidationFunctionAsync', done => { // Arrange const validator: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: true, message: 'test message', type: 'test type', }); const recordValidationSchema: RecordValidationSchema = { recordId: [validator], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: void 0, }, ], }; expect(result).toEqual(expectedResult); result['recordId'][0].validator(null).then(validationResult => { expect(validationResult).toEqual({ succeeded: true, message: 'test message', type: 'test type', }); done(); }); }); it('spec #8: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two RecordValidationFunctionAsync', done => { // Arrange const validator1: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const validator2: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const recordValidationSchema: RecordValidationSchema = { recordId: [validator1, validator2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: void 0, }, { validator: expect.any(Function), message: void 0, }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId'][0].validator(null), result['recordId'][1].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #9: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two records with one RecordValidationFunctionAsync', done => { // Arrange const validator1: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const validator2: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const recordValidationSchema: RecordValidationSchema = { recordId1: [validator1], recordId2: [validator2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId1: [ { validator: expect.any(Function), message: void 0, }, ], recordId2: [ { validator: expect.any(Function), message: void 0, }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId1'][0].validator(null), result['recordId2'][0].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #10: should return InternalRecordValidationSchema when it feeds recordValidationSchema with one FullRecordValidation and sync validator', done => { // Arrange const validator: RecordValidationFunctionSync = () => ({ succeeded: true, message: 'test message', type: 'test type', }); const fullRecordValidation: FullRecordValidation = { validator, message: 'updated message', }; const recordValidationSchema: RecordValidationSchema = { recordId: [fullRecordValidation], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: 'updated message', }, ], }; expect(result).toEqual(expectedResult); result['recordId'][0].validator(null).then(validationResult => { expect(validationResult).toEqual({ succeeded: true, message: 'test message', type: 'test type', }); done(); }); }); it('spec #11: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two FullRecordValidation and sync validator', done => { // Arrange const validator1: RecordValidationFunctionSync = () => ({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const fullRecordValidation1: FullRecordValidation = { validator: validator1, message: 'updated message 1', }; const validator2: RecordValidationFunctionSync = () => ({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const fullRecordValidation2: FullRecordValidation = { validator: validator2, message: 'updated message 2', }; const recordValidationSchema: RecordValidationSchema = { recordId: [fullRecordValidation1, fullRecordValidation2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: 'updated message 1', }, { validator: expect.any(Function), message: 'updated message 2', }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId'][0].validator(null), result['recordId'][1].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #12: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two records with one FullRecordValidation and sync validator', done => { // Arrange const validator1: RecordValidationFunctionSync = () => ({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const fullRecordValidation1: FullRecordValidation = { validator: validator1, message: 'updated message 1', }; const validator2: RecordValidationFunctionSync = () => ({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const fullRecordValidation2: FullRecordValidation = { validator: validator2, message: 'updated message 2', }; const recordValidationSchema: RecordValidationSchema = { recordId1: [fullRecordValidation1], recordId2: [fullRecordValidation2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId1: [ { validator: expect.any(Function), message: 'updated message 1', }, ], recordId2: [ { validator: expect.any(Function), message: 'updated message 2', }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId1'][0].validator(null), result['recordId2'][0].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #13: should return InternalRecordValidationSchema when it feeds recordValidationSchema with one FullRecordValidation and async validator', done => { // Arrange const validator: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: true, message: 'test message', type: 'test type', }); const fullRecordValidation: FullRecordValidation = { validator, message: 'updated message', }; const recordValidationSchema: RecordValidationSchema = { recordId: [fullRecordValidation], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: 'updated message', }, ], }; expect(result).toEqual(expectedResult); result['recordId'][0].validator(null).then(validationResult => { expect(validationResult).toEqual({ succeeded: true, message: 'test message', type: 'test type', }); done(); }); }); it('spec #14: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two FullRecordValidation and async validator', done => { // Arrange const validator1: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const fullRecordValidation1: FullRecordValidation = { validator: validator1, message: 'updated message 1', }; const validator2: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const fullRecordValidation2: FullRecordValidation = { validator: validator2, message: 'updated message 2', }; const recordValidationSchema: RecordValidationSchema = { recordId: [fullRecordValidation1, fullRecordValidation2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId: [ { validator: expect.any(Function), message: 'updated message 1', }, { validator: expect.any(Function), message: 'updated message 2', }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId'][0].validator(null), result['recordId'][1].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #15: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two records with one FullRecordValidation and async validator', done => { // Arrange const validator1: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const fullRecordValidation1: FullRecordValidation = { validator: validator1, message: 'updated message 1', }; const validator2: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: false, message: 'test message 2', type: 'test type 2', }); const fullRecordValidation2: FullRecordValidation = { validator: validator2, message: 'updated message 2', }; const recordValidationSchema: RecordValidationSchema = { recordId1: [fullRecordValidation1], recordId2: [fullRecordValidation2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId1: [ { validator: expect.any(Function), message: 'updated message 1', }, ], recordId2: [ { validator: expect.any(Function), message: 'updated message 2', }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId1'][0].validator(null), result['recordId2'][0].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); it('spec #16: should return InternalRecordValidationSchema when it feeds recordValidationSchema with two records with one FullRecordValidation and the another one with validator object', done => { // Arrange const validator1: RecordValidationFunctionAsync = () => Promise.resolve({ succeeded: true, message: 'test message 1', type: 'test type 1', }); const fullRecordValidation1: FullRecordValidation = { validator: validator1, message: 'updated message 1', }; const validator2 = { validator: () => Promise.resolve({ succeeded: false, message: 'test message 2', type: 'test type 2', }), }; const fullRecordValidation2: FullRecordValidation = { validator: validator2, message: 'updated message 2', }; const recordValidationSchema: RecordValidationSchema = { recordId1: [fullRecordValidation1], recordId2: [fullRecordValidation2], }; // Act const result = mapToInternalRecordValidationSchema(recordValidationSchema); // Assert const expectedResult: InternalRecordValidationSchema = { recordId1: [ { validator: expect.any(Function), message: 'updated message 1', }, ], recordId2: [ { validator: expect.any(Function), message: 'updated message 2', }, ], }; expect(result).toEqual(expectedResult); Promise.all([ result['recordId1'][0].validator(null), result['recordId2'][0].validator(null), ]).then(validationResults => { expect(validationResults[0]).toEqual({ succeeded: true, message: 'test message 1', type: 'test type 1', }); expect(validationResults[1]).toEqual({ succeeded: false, message: 'test message 2', type: 'test type 2', }); done(); }); }); });
the_stack
import type { ComplexView, ContainerView, PrimitiveView, ViewConstructor, ViewFieldLayout, ViewInstance, ViewLayout, ViewSchema, } from "./view-types.ts"; import { BooleanView } from "./boolean-view.ts"; import { BigInt64View, BigUint64View, Float32View, Float64View, Int16View, Int32View, Int8View, Uint16View, Uint32View, Uint8View, } from "./numeric-view.ts"; import { ObjectView } from "./object-view.ts"; import { ArrayView } from "./array-view.ts"; import { VectorView } from "./vector-view.ts"; import { MapView } from "./map-view.ts"; import { StringView } from "./string-view.ts"; import { TypedArrayView } from "./typed-array-view.ts"; import { BinaryView } from "./binary-view.ts"; import { log2 } from "./utilities.ts"; import { Constructor } from "./utility-types.ts"; type UnknownViewConstructor = ViewConstructor< unknown, PrimitiveView<unknown> | ContainerView<unknown> | ComplexView<unknown> >; export class View { static Views = new Map<string, UnknownViewConstructor>([ ["int8", Int8View], ["uint8", Uint8View], ["int16", Int16View], ["uint16", Uint16View], ["int32", Int32View], ["number", Float64View], ["integer", Int32View], ["uint32", Uint32View], ["float32", Float32View], ["float64", Float64View], ["bigint64", BigInt64View], ["biguint64", BigUint64View], ["boolean", BooleanView], ["string", StringView], ["binary", BinaryView], ]); static TaggedViews = new Map<number, UnknownViewConstructor>(); static tagName = "tag"; static maxLength = 8192; static ObjectClass = ObjectView; static ArrayClass = ArrayView; static TypedArrayClass = TypedArrayView; static VectorClass = VectorView; static MapClass = MapView; static _maxView: DataView; static get maxView(): DataView { if (!this._maxView) { this._maxView = new DataView(new ArrayBuffer(this.maxLength)); } return this._maxView; } static create<T>( schema: ViewSchema<T>, constructor?: T extends object ? Constructor<T> : never, ): ViewConstructor<T> { const schemas = this.getSchemaOrdering(schema as ViewSchema<unknown>); for (let i = schemas.length - 1; i >= 0; i--) { const objectSchema = schemas[i]; const id = this.getSchemaId(objectSchema); if (this.Views.has(id)) continue; // use provided constructor for top object const objectCtor = objectSchema === schema ? constructor : undefined; const View = objectSchema.btype === "map" ? this.getMapView(objectSchema, objectCtor) : this.getObjectView(objectSchema, objectCtor); // cache the view by id this.Views.set(id, View); // cache by tag if present const tag = (objectSchema.properties as Record<string, ViewSchema<unknown>>)[ this.tagName ]?.default; if (typeof tag === "number") { this.TaggedViews.set(tag, View); } } if (schema.type === "array") return this.getArray<T>(schema)[0]; return this.getExistingView<T>(schema); } static view<T>(view: DataView): ViewInstance<T> | undefined { const tag = view.getUint8(0); const ViewClass = this.TaggedViews.get(tag) as ViewConstructor<T>; if (!ViewClass) return undefined; return new ViewClass(view.buffer, view.byteOffset); } static decode<T>(view: DataView): T | undefined { const tag = view.getUint8(0); const ViewClass = this.TaggedViews.get(tag) as ViewConstructor<T>; if (!ViewClass) return undefined; return ViewClass.decode(view, 0); } static encode<T>(value: T, view?: DataView): ViewInstance<T> | undefined { const ViewClass = this.TaggedViews.get( // deno-lint-ignore no-explicit-any (value as any)[this.tagName] as number, ) as ViewConstructor<T>; if (!ViewClass) return undefined; if (!view) return ViewClass.from(value); ViewClass.encode(value, view, 0); return new ViewClass(view.buffer, view.byteOffset); } static getArray<T>( schema: ViewSchema<T>, ): [view: ViewConstructor<T>, length: number] { const arrays: Array<ViewSchema<Array<unknown>>> = []; let currentField = schema as ViewSchema<unknown>; // go down the array(s) to the item field while (currentField && currentField.type === "array") { arrays.push(currentField as ViewSchema<Array<unknown>>); currentField = currentField.items!; } let currentArray = arrays.pop()!; // get existing view of the item const itemView = this.getExistingView(currentField); // check const itemId = this.getSchemaId(currentField as ViewSchema<unknown>); const isArray = currentArray.btype !== "vector"; const viewId = isArray ? `ArrayView_${itemId}` : `VectorView_${itemId}`; let View: UnknownViewConstructor; if (!this.Views.has(viewId)) { View = isArray ? this.getArrayView(itemView, currentField.maxLength) : this.getVectorView(itemView, this.maxView); // cache array views of unspecified length if (currentField.maxLength === undefined) this.Views.set(viewId, View); } else { View = this.Views.get(viewId)!; } // initialize nested arrays let itemLength = isArray ? View.getLength(currentArray.maxItems) : 0; for (let i = arrays.length - 1; i >= 0; i--) { currentArray = arrays[i]; if (currentArray.btype !== "vector") { View = this.getArrayView(View as ViewConstructor<unknown>, itemLength); itemLength = View.getLength(currentArray.maxItems); } else { View = this.getVectorView( View as ViewConstructor<unknown>, this.maxView, ); } } return [(View as unknown) as ViewConstructor<T>, itemLength]; } static getArrayView<T>( View: ViewConstructor<T>, maxLength?: number, ): ViewConstructor<Array<T>> { const itemLength = maxLength || View.viewLength; if (itemLength <= 0 || itemLength >= Infinity) { throw TypeError("ArrayView should have fixed sized items."); } const offset = log2[View.viewLength]; if (offset !== undefined) { return class extends this.TypedArrayClass<T> { static View = View; static offset = offset; static itemLength = itemLength; }; } return class extends this.ArrayClass<T> { static View = View; static itemLength = itemLength; }; } static getDefaultData<T extends unknown>( layout: ViewLayout<T>, viewLength: number, fields: Array<keyof T>, ): Uint8Array { const buffer = new ArrayBuffer(viewLength); const view = new DataView(buffer); const array = new Uint8Array(buffer); for (const name of fields) { const field = layout[name]; if (Reflect.has(field, "default")) { field.View.encode(field.default!, view, field.start, field.length); } else if (field.View.defaultData) { array.set(field.View.defaultData, field.start); } } return array; } static getDefaultConstructor<T>( fields: Array<keyof T>, layout: ViewLayout<T>, ): Constructor<T> { const content: Array<string> = []; for (const field of fields) { const View: ViewConstructor<unknown, unknown> = layout[field].View; let value = ""; switch (View) { case Int8View: case Int16View: case Uint16View: case Uint8View: case Int32View: value = "0"; break; case Float32View: case Float64View: value = "0.0"; break; case BigInt64View: case BigUint64View: value = "0n"; break; case BooleanView: value = "false"; break; case StringView: value = "''"; break; default: value = "null"; } content.push(`${field}:${value}`); } return new Function( "return {" + content.join(",") + "}", ) as Constructor<T>; } static getExistingView<T>(schema: ViewSchema<T>): ViewConstructor<T> { let type = schema.$id || schema.$ref?.slice(1); if (type) { if (!this.Views.has(type)) throw Error(`View "${type}" is not found.`); } else { type = schema.btype || schema.type; if (!this.Views.has(type)) { throw TypeError(`Type "${type}" is not supported.`); } } return this.Views.get(type) as ViewConstructor<T>; } static getFieldLayout<T>( field: ViewSchema<T>, start: number, required: boolean, name: string, ): ViewFieldLayout<T> { let View: ViewConstructor<T>; let length = 0; if (field.type !== "array") { View = this.getExistingView(field); length = field.maxLength || View.viewLength; } else { [View, length] = this.getArray(field); } if (!length) length = Infinity; if (required && length === Infinity) { throw new TypeError( `The length of a required field "${name}" is undefined.`, ); } const layout: ViewFieldLayout<T> = { start, View, length, required }; if (Reflect.has(field, "default")) { layout.default = (field.default as unknown) as T; } return layout; } static getMapView<T extends object>( schema: ViewSchema<T>, constructor?: Constructor<T>, ): ViewConstructor<T, ComplexView<T>> { const required: Array<keyof T> = schema.required || []; const optional = (Object.keys(schema.properties!) as Array<keyof T>).filter( (i) => !required.includes(i), ); const layout = {} as ViewLayout<T>; let offset = 0; for (const property of required) { const field = schema.properties![property]; const fieldLayout = this.getFieldLayout( field, offset, true, property as string, ); offset += fieldLayout.length; // @ts-ignore TS2322 layout[property] = fieldLayout; } const optionalOffset = offset; for (let i = 0; i < optional.length; i++) { const property = optional[i]; const field = schema.properties![property]; // @ts-ignore TS2322 layout[property as keyof T] = this.getFieldLayout( field, offset + (i << 2), false, property as string, ); } const maxView = this.maxView; const defaultData = this.getDefaultData( layout, optionalOffset, required as Array<keyof T>, ); const ObjectConstructor = constructor || this.getDefaultConstructor(required as Array<keyof T>, layout); return class extends this.MapClass<T> { static layout = layout; static lengthOffset = optionalOffset + (optional.length << 2); static optionalOffset = optionalOffset; static fields = required; static optionalFields = optional; static maxView = maxView; static defaultData = defaultData; static ObjectConstructor = ObjectConstructor; }; } static getObjectView<T extends object>( schema: ViewSchema<T>, constructor?: Constructor<T>, ): ViewConstructor<T, ComplexView<T>> { const fields = Object.keys(schema.properties!) as Array<keyof T>; const layout = {} as ViewLayout<T>; let lastOffset = 0; for (const property of fields) { const field = schema.properties![property]; const fieldLayout = this.getFieldLayout( field, lastOffset, true, property as string, ); lastOffset += fieldLayout.length; // @ts-ignore TS2322 layout[property] = fieldLayout; } const defaultData = this.getDefaultData(layout, lastOffset, fields); const ObjectConstructor = constructor || this.getDefaultConstructor(fields, layout); return class extends this.ObjectClass<T> { static viewLength = lastOffset; static layout = layout; static fields = fields; static defaultData = defaultData; static ObjectConstructor = ObjectConstructor; }; } // deno-lint-ignore no-explicit-any static getSchemaId(schema: ViewSchema<any>): string { return schema.$id || schema.$ref?.slice(1) || schema.btype || schema.type; } static getSchemaOrdering( schema: ViewSchema<unknown>, ): Array<ViewSchema<object>> { // create graph let object = schema; // reach the nested object if an array is provided while (object.type === "array") object = object.items!; // return if no object found if (object.type !== "object") return []; const mainId = object.$id!; let id = mainId; const objects = { [id]: object }; const adjacency: Record<string, Array<string>> = { [id]: [] }; const indegrees = { [id]: 0 }; const processing = [id]; while (processing.length) { id = processing.pop()!; object = objects[id]; if (!object.properties) continue; const properties = Object.keys(object.properties); for (const property of properties) { let field = (object.properties! as Record<string, ViewSchema<unknown>>)[property]; if (field.type === "array") { while (field.type === "array") field = field.items!; } const { $id, $ref } = field; if ($id) { objects[$id] = field; adjacency[id].push($id); adjacency[$id] = []; indegrees[$id] = indegrees[$id] ? indegrees[$id] + 1 : 1; processing.push($id); } else if ($ref) { const refId = $ref.slice(1); indegrees[refId] = indegrees[refId] ? indegrees[refId] + 1 : 1; adjacency[id].push(refId); } } } // topologically sort the graph let visited = 0; const order: Array<ViewSchema<object>> = []; processing.push(mainId); while (processing.length) { id = processing.shift()!; const children = adjacency[id]; if (!children) continue; // $ref no external links order.push(objects[id] as ViewSchema<object>); for (const child of children) { indegrees[child] -= 1; if (indegrees[child] === 0) processing.push(child); } visited++; } // check for recursive links if (visited !== Object.keys(objects).length) { throw TypeError("The schema has recursive references."); } return order; } static getVectorView<T>( View: ViewConstructor<T>, maxView: DataView, ): ViewConstructor<Array<T | undefined>> { return class extends this.VectorClass<T> { static View = View; static maxView = maxView; }; } }
the_stack
* @module OrbitGT */ //package orbitgt.spatial.ecrs; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { Message } from "../../system/runtime/Message"; import { Strings } from "../../system/runtime/Strings"; import { Coordinate } from "../geom/Coordinate"; import { CRS } from "./CRS"; import { Registry } from "./Registry"; import { VerticalModel } from "./VerticalModel"; /** * Class Transform transforms coordinates between coordinate reference systems. * * @version 1.0 September 2005 */ /** @internal */ export class Transform { /** The name of this module */ private static readonly MODULE: string = "Transform"; /** Define the different paths a CRS transformation can take */ private static readonly _SAME_CRS: int32 = 1; private static readonly _FORWARD_PROJECTION: int32 = 2; private static readonly _INVERSE_PROJECTION: int32 = 3; private static readonly _TWO_PROJECTIONS: int32 = 4; private static readonly _TO_WGS: int32 = 6; private static readonly _FROM_WGS: int32 = 7; private static readonly _FULL_TRANSFORM: int32 = 8; private static readonly _VERTICAL: int32 = 9; /** * Prevent instantiation. */ private constructor() { } /** * Is a conversion between two coordinate systems possible/needed? * @param sourceCRS the name/code of the source reference system. * @param targetCRS the name/code of the target reference system. * @return true if a conversion is possible/needed. */ public static canTransform(sourceCRS: string, targetCRS: string): boolean { /* We need two CRSs */ if (sourceCRS == null || Strings.getLength(sourceCRS) == 0) return false; if (targetCRS == null || Strings.getLength(targetCRS) == 0) return false; /* Same CRS ? */ if (Strings.equalsIgnoreCase(targetCRS, sourceCRS)) return true; /* Get the two CRSs */ let source: CRS = Registry.getCRS2(sourceCRS); let target: CRS = Registry.getCRS2(targetCRS); /* We need two CRSs */ if (source == null) return false; if (target == null) return false; /* Vertical transform ? */ if (source.hasVerticalComponent() || target.hasVerticalComponent()) { /* Get the horizontal components */ let sourceHor: CRS = (source.hasVerticalComponent()) ? source.getHorizontalComponent() : source; let targetHor: CRS = (target.hasVerticalComponent()) ? target.getHorizontalComponent() : target; /* Check transform in the horizontal CRS */ return Transform.canTransform("" + sourceHor.getCode(), "" + targetHor.getCode()); } /* Same datum ? */ if (source.getDatum().isCompatible(target.getDatum())) return true; /* Chained transform ? */ if ((source.getCode() != CRS.WGS84_2D_CRS_CODE) && (target.getCode() != CRS.WGS84_2D_CRS_CODE)) { /* Use WGS as in-between */ if (source.isWGSCompatible() == false) return false; if (target.isWGSCompatible() == false) return false; /* Possible */ return true; } /* To WGS ? */ if (target.getCode() == CRS.WGS84_2D_CRS_CODE) { /* Use WGS */ if (source.isWGSCompatible() == false) return false; /* Possible */ return true; } /* From WGS ? */ if (source.getCode() == CRS.WGS84_2D_CRS_CODE) { /* Use WGS */ if (target.isWGSCompatible() == false) return false; /* Possible */ return true; } /* Not possible */ return false; } /** * Do a vertical transform. * @param horizontalCRS the horizontal CRS. * @param fromVerticalCRS the vertical CRS to convert from. * @param from the coordinate to convert from. * @param toVerticalCRS the vertical CRS to convert to. * @param to the coordinate to convert to. */ public static transformVertical(horizontalCRS: CRS, fromVerticalCRS: CRS, from: Coordinate, toVerticalCRS: CRS, to: Coordinate): void { /* 1: From 'ellipsoid' to 'ellipsoid' height ? */ if ((fromVerticalCRS == null) && (toVerticalCRS == null)) { /* Straight copy */ to.setX(from.getX()); to.setY(from.getY()); to.setZ(from.getZ()); //Message.print(MODULE,"_VERTICAL: ellipsoid->ellipsoid: "+from.getZ()); } /* 2: From 'ellipsoid' to 'local' height ? */ else if ((fromVerticalCRS == null) && (toVerticalCRS != null)) { /* Get the geoid separation */ let geoidModel: VerticalModel = toVerticalCRS.getVerticalModel(); let toZ: float64 = from.getZ(); if (geoidModel != null) toZ = geoidModel.toLocalHeight(horizontalCRS, from); else Message.printWarning(Transform.MODULE, "Target vertical CRS " + toVerticalCRS + " does not have a height model"); //Message.print(MODULE,"_VERTICAL: ellipsoid->local: "+from.getZ()+"->"+toZ); /* Substract the separation */ to.setX(from.getX()); to.setY(from.getY()); to.setZ(toZ); } /* 3: From 'local' to 'ellipsoid' height ? */ else if ((fromVerticalCRS != null) && (toVerticalCRS == null)) { /* Get the geoid separation */ let geoidModel: VerticalModel = fromVerticalCRS.getVerticalModel(); let toZ: float64 = from.getZ(); if (geoidModel != null) toZ = geoidModel.toEllipsoidHeight(horizontalCRS, from); else Message.printWarning(Transform.MODULE, "Source vertical CRS " + fromVerticalCRS + " does not have a height model"); //Message.print(MODULE,"_VERTICAL: local->ellipsoid: "+from.getZ()+"->"+toZ); /* Add the separation */ to.setX(from.getX()); to.setY(from.getY()); to.setZ(toZ); } /* 4: From 'local1' to 'local2' */ else { /* Same ? */ if (fromVerticalCRS.getCode() == toVerticalCRS.getCode()) { /* Straight copy */ to.setX(from.getX()); to.setY(from.getY()); to.setZ(from.getZ()); //Message.print(MODULE,"_VERTICAL: local->local same: "+from.getZ()); } else { /* Get the 'from' ellipsoid height */ let fromGeoidModel: VerticalModel = fromVerticalCRS.getVerticalModel(); let fromZ: float64 = from.getZ(); if (fromGeoidModel != null) fromZ = fromGeoidModel.toEllipsoidHeight(horizontalCRS, from); else Message.printWarning(Transform.MODULE, "Source vertical CRS " + fromVerticalCRS + " does not have a height model"); /* Copy */ to.setX(from.getX()); to.setY(from.getY()); to.setZ(fromZ); /* Get the 'to' local height */ let toGeoidModel: VerticalModel = toVerticalCRS.getVerticalModel(); let toZ: float64 = to.getZ(); if (toGeoidModel != null) toZ = toGeoidModel.toLocalHeight(horizontalCRS, to); else Message.printWarning(Transform.MODULE, "Target vertical CRS " + toVerticalCRS + " does not have a height model"); //Message.print(MODULE,"_VERTICAL: local->local: "+from.getZ()+"->"+fromZ+"->"+toZ); /* Copy */ to.setZ(toZ); } } } /** * Get the transformation path from one CRS to another CRS. * @param sourceCRS the source reference system. * @param targetCRS the target reference system. * @return the transformation path. */ public static getTransformPath(sourceCRS: CRS, targetCRS: CRS): int32 { /* Same CRS ? */ if (targetCRS.getCode() == sourceCRS.getCode()) { return Transform._SAME_CRS; } /* Compatible CRS ? */ if (targetCRS.isCompatible(sourceCRS)) { return Transform._SAME_CRS; } /* Vertical transform ? */ if (sourceCRS.hasVerticalComponent() || targetCRS.hasVerticalComponent()) { return Transform._VERTICAL; } /* Same datum/ellipsoid ? (added on 24/11/2011) */ if (sourceCRS.getDatum().isCompatible(targetCRS.getDatum())) { /* Is the target a projection of the source ? (added on 05/12/2011) */ if (targetCRS.isProjectionOf(sourceCRS)) { return Transform._FORWARD_PROJECTION; } /* Is the source a projection of the target ? (added on 05/12/2011) */ if (sourceCRS.isProjectionOf(targetCRS)) { return Transform._INVERSE_PROJECTION; } /* Two projections of the same base? */ if (sourceCRS.isProjected() && targetCRS.isProjected() && (targetCRS.getBaseCRS().isCompatible(sourceCRS.getBaseCRS()))) { return Transform._TWO_PROJECTIONS; } } /* To WGS ? */ if (targetCRS.getCode() == CRS.WGS84_2D_CRS_CODE) { return Transform._TO_WGS; } /* From WGS ? */ if (sourceCRS.getCode() == CRS.WGS84_2D_CRS_CODE) { return Transform._FROM_WGS; } /* Use WGS as in-between (slowest path) */ return Transform._FULL_TRANSFORM; } /** * Convert between two coordinate reference systems. * @param sourceCRS the source reference system. * @param from the coordinate to convert from. * @param targetCRS the target reference system. * @param to the coordinate to convert to. */ public static transformWithPath(path: int32, sourceCRS: CRS, from: Coordinate, targetCRS: CRS, to: Coordinate): void { //Message.print(MODULE,"---------->>>"); //Message.print(MODULE,"TRANSFORM: sourceCRS = "+sourceCRS.getCode()); //Message.print(MODULE,"TRANSFORM: targetCRS = "+targetCRS.getCode()); //Message.print(MODULE,"TRANSFORM: from = "+from); //Message.print(MODULE,"TRANSFORM: path = "+path); /* Same CRS ? */ if (path == Transform._SAME_CRS) { //Message.print(MODULE,"TRANSFORM: _SAME_CRS"); /* Straight copy */ to.setX(from.getX()); to.setY(from.getY()); to.setZ(from.getZ()); //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } /* Is the target a projection of the source ? (added on 05/12/2011) */ if (path == Transform._FORWARD_PROJECTION) { //Message.print(MODULE,"TRANSFORM: _FORWARD_PROJECTION"); /* Apply the projection */ targetCRS.toProjected(from, to); //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } /* Is the source a projection of the target ? (added on 05/12/2011) */ if (path == Transform._INVERSE_PROJECTION) { //Message.print(MODULE,"TRANSFORM: _INVERSE_PROJECTION"); /* Reverse the projection */ sourceCRS.fromProjected(from, to); //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } /* Two projections of the same base? */ if (path == Transform._TWO_PROJECTIONS) { //Message.print(MODULE,"TRANSFORM: _TWO_PROJECTIONS"); /* Reverse the projection */ sourceCRS.fromProjected(from, to); /* Apply the projection */ targetCRS.toProjected(to, to); //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } /* To WGS ? */ if (path == Transform._TO_WGS) { //Message.print(MODULE,"TRANSFORM: _TO_WGS"); /* Use WGS */ let toWGS: Coordinate = sourceCRS.toWGS(from); /* Set the target */ to.setX(toWGS.getX()); to.setY(toWGS.getY()); to.setZ(toWGS.getZ()); //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } /* From WGS ? */ if (path == Transform._FROM_WGS) { //Message.print(MODULE,"TRANSFORM: _FROM_WGS"); /* Use WGS */ let fromWGS: Coordinate = targetCRS.fromWGS(from); /* Set the target */ to.setX(fromWGS.getX()); to.setY(fromWGS.getY()); to.setZ(fromWGS.getZ()); //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } /* Full transform ? */ if (path == Transform._FULL_TRANSFORM) { //Message.print(MODULE,"TRANSFORM: _FULL_TRANSFORM"); /* Use WGS as in-between */ let toWGS: Coordinate = sourceCRS.toWGS(from); let fromWGS: Coordinate = targetCRS.fromWGS(toWGS); /* Set the target */ to.setX(fromWGS.getX()); to.setY(fromWGS.getY()); to.setZ(fromWGS.getZ()); //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } /* Vertical transform ? */ if (path == Transform._VERTICAL) { //Message.print(MODULE,"TRANSFORM: _VERTICAL"); /* Get the horizontal components */ let sourceHorCRS: CRS = (sourceCRS.hasVerticalComponent()) ? sourceCRS.getHorizontalComponent() : sourceCRS; let targetHorCRS: CRS = (targetCRS.hasVerticalComponent()) ? targetCRS.getHorizontalComponent() : targetCRS; /* Get the vertical components */ let sourceVerCRS: CRS = (sourceCRS.hasVerticalComponent()) ? sourceCRS.getVerticalComponent() : null; let targetVerCRS: CRS = (targetCRS.hasVerticalComponent()) ? targetCRS.getVerticalComponent() : null; /* Put the source coordinate in the ellipsoid height */ if (sourceVerCRS != null) { /* Move to the default 'ellipsoid' height */ //Message.print(MODULE,"TRANSFORM: source to ellipsoidZ"); Transform.transformVertical(sourceHorCRS, sourceVerCRS, from, null, to); from = to; //Message.print(MODULE,"TRANSFORM: source ellipsoidZ = "+to); } /* Get the ellipsoid height */ let ellipsoidZ: float64 = from.getZ(); if (sourceHorCRS.isGeoCentric()) { /* Calculate the ellipsoid height */ let geographic: Coordinate = new Coordinate(0.0, 0.0, 0.0); sourceHorCRS.getEllipsoid().toGeoGraphic(from, geographic); ellipsoidZ = geographic.getZ(); } /* Transform in the horizontal CRS (keep the WGS Z (and not the Bessel Z) for transform from WGS to RD-NAP) */ //Message.print(MODULE,"TRANSFORM: ellipsoidZ = "+ellipsoidZ); //Message.print(MODULE,"TRANSFORM: horizontal "+sourceHorCRS.getCode()+" -> "+targetHorCRS.getCode()); Transform.transformCRS(sourceHorCRS, from, targetHorCRS, to); /* Is the target CRS horizontal? */ if (targetHorCRS.isGeoCentric() == false) { /* Keep the ellipsoid height after the horizontal transform */ to.setZ(ellipsoidZ); } from = to; //Message.print(MODULE,"TRANSFORM: intermediate = "+from); /* Put the target coordinate in the vertical CRS */ if (targetVerCRS != null) { /* Move from the default 'ellipsoid' height */ Transform.transformVertical(targetHorCRS, null, from, targetVerCRS, to); from = to; //Message.print(MODULE,"TRANSFORM: target vtransf = "+to); } /* Done */ //Message.print(MODULE,"TRANSFORMED: to = "+to); return; } //Message.print(MODULE,"TRANSFORMED: UNKNOWN!"); } /** * Convert between two coordinate reference systems. * @param sourceCRS the source reference system. * @param from the coordinate to convert from. * @param targetCRS the target reference system. * @param to the coordinate to convert to. */ public static transformCRS(sourceCRS: CRS, from: Coordinate, targetCRS: CRS, to: Coordinate): void { Transform.transformWithPath(Transform.getTransformPath(sourceCRS, targetCRS), sourceCRS, from, targetCRS, to); } /** * Convert between two coordinate reference systems. * @param sourceCRS the name/code of the source reference system. * @param from the coordinate to convert from. * @param targetCRS the name/code of the target reference system. * @param to the coordinate to convert to. */ public static transform(sourceCRS: string, from: Coordinate, targetCRS: string, to: Coordinate): void { /* Same CRS ? */ if (Strings.equalsIgnoreCase(targetCRS, sourceCRS)) { /* Straight copy */ to.setX(from.getX()); to.setY(from.getY()); to.setZ(from.getZ()); return; } /* Get the two CRSs */ let source: CRS = Registry.getCRS2(sourceCRS); let target: CRS = Registry.getCRS2(targetCRS); /* Transform */ Transform.transformCRS(source, from, target, to); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; export const LanguagesResultTranslationLanguageCode: msRest.CompositeMapper = { serializedName: "LanguagesResult_translation_languageCode", type: { name: "Composite", className: "LanguagesResultTranslationLanguageCode", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, nativeName: { serializedName: "nativeName", type: { name: "String" } }, dir: { serializedName: "dir", type: { name: "String" } } } } }; export const LanguagesResultTranslation: msRest.CompositeMapper = { serializedName: "LanguagesResult_translation", type: { name: "Composite", className: "LanguagesResultTranslation", modelProperties: { languageCode: { serializedName: "languageCode", type: { name: "Composite", className: "LanguagesResultTranslationLanguageCode" } } } } }; export const LanguagesResultTransliterationLanguageCodeScriptsItemToScriptsItem: msRest.CompositeMapper = { serializedName: "LanguagesResult_transliteration_languageCode_scriptsItem_toScriptsItem", type: { name: "Composite", className: "LanguagesResultTransliterationLanguageCodeScriptsItemToScriptsItem", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, name: { serializedName: "name", type: { name: "String" } }, nativeName: { serializedName: "nativeName", type: { name: "String" } }, dir: { serializedName: "dir", type: { name: "String" } } } } }; export const LanguagesResultTransliterationLanguageCodeScriptsItem: msRest.CompositeMapper = { serializedName: "LanguagesResult_transliteration_languageCode_scriptsItem", type: { name: "Composite", className: "LanguagesResultTransliterationLanguageCodeScriptsItem", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, name: { serializedName: "name", type: { name: "String" } }, nativeName: { serializedName: "nativeName", type: { name: "String" } }, dir: { serializedName: "dir", type: { name: "String" } }, toScripts: { serializedName: "toScripts", type: { name: "Sequence", element: { type: { name: "Composite", className: "LanguagesResultTransliterationLanguageCodeScriptsItemToScriptsItem" } } } } } } }; export const LanguagesResultTransliterationLanguageCode: msRest.CompositeMapper = { serializedName: "LanguagesResult_transliteration_languageCode", type: { name: "Composite", className: "LanguagesResultTransliterationLanguageCode", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, nativeName: { serializedName: "nativeName", type: { name: "String" } }, scripts: { serializedName: "scripts", type: { name: "Sequence", element: { type: { name: "Composite", className: "LanguagesResultTransliterationLanguageCodeScriptsItem" } } } } } } }; export const LanguagesResultTransliteration: msRest.CompositeMapper = { serializedName: "LanguagesResult_transliteration", type: { name: "Composite", className: "LanguagesResultTransliteration", modelProperties: { languageCode: { serializedName: "languageCode", type: { name: "Composite", className: "LanguagesResultTransliterationLanguageCode" } } } } }; export const LanguagesResultDictionaryLanguageCodeTranslationsItem: msRest.CompositeMapper = { serializedName: "LanguagesResult_dictionary_languageCode_translationsItem", type: { name: "Composite", className: "LanguagesResultDictionaryLanguageCodeTranslationsItem", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, nativeName: { serializedName: "nativeName", type: { name: "String" } }, dir: { serializedName: "dir", type: { name: "String" } }, code: { serializedName: "code", type: { name: "String" } } } } }; export const LanguagesResultDictionaryLanguageCode: msRest.CompositeMapper = { serializedName: "LanguagesResult_dictionary_languageCode", type: { name: "Composite", className: "LanguagesResultDictionaryLanguageCode", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, nativeName: { serializedName: "nativeName", type: { name: "String" } }, dir: { serializedName: "dir", type: { name: "String" } }, translations: { serializedName: "translations", type: { name: "Sequence", element: { type: { name: "Composite", className: "LanguagesResultDictionaryLanguageCodeTranslationsItem" } } } } } } }; export const LanguagesResultDictionary: msRest.CompositeMapper = { serializedName: "LanguagesResult_dictionary", type: { name: "Composite", className: "LanguagesResultDictionary", modelProperties: { languageCode: { serializedName: "languageCode", type: { name: "Composite", className: "LanguagesResultDictionaryLanguageCode" } } } } }; export const LanguagesResult: msRest.CompositeMapper = { serializedName: "LanguagesResult", type: { name: "Composite", className: "LanguagesResult", modelProperties: { translation: { serializedName: "translation", type: { name: "Composite", className: "LanguagesResultTranslation" } }, transliteration: { serializedName: "transliteration", type: { name: "Composite", className: "LanguagesResultTransliteration" } }, dictionary: { serializedName: "dictionary", type: { name: "Composite", className: "LanguagesResultDictionary" } } } } }; export const DictionaryExampleResultItemExamplesItem: msRest.CompositeMapper = { serializedName: "DictionaryExampleResultItem_examplesItem", type: { name: "Composite", className: "DictionaryExampleResultItemExamplesItem", modelProperties: { sourcePrefix: { serializedName: "sourcePrefix", type: { name: "String" } }, sourceTerm: { serializedName: "sourceTerm", type: { name: "String" } }, sourceSuffix: { serializedName: "sourceSuffix", type: { name: "String" } }, targetPrefix: { serializedName: "targetPrefix", type: { name: "String" } }, targetTerm: { serializedName: "targetTerm", type: { name: "String" } }, targetSuffix: { serializedName: "targetSuffix", type: { name: "String" } } } } }; export const DictionaryExampleResultItem: msRest.CompositeMapper = { serializedName: "DictionaryExampleResultItem", type: { name: "Composite", className: "DictionaryExampleResultItem", modelProperties: { normalizedSource: { serializedName: "normalizedSource", type: { name: "String" } }, normalizedTarget: { serializedName: "normalizedTarget", type: { name: "String" } }, examples: { serializedName: "examples", type: { name: "Sequence", element: { type: { name: "Composite", className: "DictionaryExampleResultItemExamplesItem" } } } } } } }; export const DictionaryLookupResultItemTranslationsItemBackTranslationsItem: msRest.CompositeMapper = { serializedName: "DictionaryLookupResultItem_translationsItem_backTranslationsItem", type: { name: "Composite", className: "DictionaryLookupResultItemTranslationsItemBackTranslationsItem", modelProperties: { normalizedText: { serializedName: "normalizedText", type: { name: "String" } }, displayText: { serializedName: "displayText", type: { name: "String" } }, numExamples: { serializedName: "numExamples", type: { name: "Number" } }, frequencyCount: { serializedName: "frequencyCount", type: { name: "Number" } } } } }; export const DictionaryLookupResultItemTranslationsItem: msRest.CompositeMapper = { serializedName: "DictionaryLookupResultItem_translationsItem", type: { name: "Composite", className: "DictionaryLookupResultItemTranslationsItem", modelProperties: { normalizedTarget: { serializedName: "normalizedTarget", type: { name: "String" } }, displayTarget: { serializedName: "displayTarget", type: { name: "String" } }, posTag: { serializedName: "posTag", type: { name: "String" } }, confidence: { serializedName: "confidence", type: { name: "Number" } }, prefixWord: { serializedName: "prefixWord", type: { name: "String" } }, backTranslations: { serializedName: "backTranslations", type: { name: "Sequence", element: { type: { name: "Composite", className: "DictionaryLookupResultItemTranslationsItemBackTranslationsItem" } } } } } } }; export const DictionaryLookupResultItem: msRest.CompositeMapper = { serializedName: "DictionaryLookupResultItem", type: { name: "Composite", className: "DictionaryLookupResultItem", modelProperties: { normalizedSource: { serializedName: "normalizedSource", type: { name: "String" } }, displaySource: { serializedName: "displaySource", type: { name: "String" } }, translations: { serializedName: "translations", type: { name: "Sequence", element: { type: { name: "Composite", className: "DictionaryLookupResultItemTranslationsItem" } } } } } } }; export const TranslateResultItemTranslationItem: msRest.CompositeMapper = { serializedName: "TranslateResultItem_translationItem", type: { name: "Composite", className: "TranslateResultItemTranslationItem", modelProperties: { text: { serializedName: "text", type: { name: "String" } }, to: { serializedName: "to", type: { name: "String" } } } } }; export const TranslateResultItem: msRest.CompositeMapper = { serializedName: "TranslateResultItem", type: { name: "Composite", className: "TranslateResultItem", modelProperties: { translation: { serializedName: "translation", type: { name: "Sequence", element: { type: { name: "Composite", className: "TranslateResultItemTranslationItem" } } } } } } }; export const TranslateResultAllItemDetectedLanguage: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem_detectedLanguage", type: { name: "Composite", className: "TranslateResultAllItemDetectedLanguage", modelProperties: { language: { serializedName: "language", type: { name: "String" } }, score: { serializedName: "score", type: { name: "Number" } } } } }; export const TranslateResultAllItemTranslationsItemTransliteration: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem_translationsItem_transliteration", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemTransliteration", modelProperties: { text: { serializedName: "text", type: { name: "String" } }, script: { serializedName: "script", type: { name: "String" } } } } }; export const TranslateResultAllItemTranslationsItemAlignment: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem_translationsItem_alignment", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemAlignment", modelProperties: { proj: { serializedName: "proj", type: { name: "String" } } } } }; export const TranslateResultAllItemTranslationsItemSentLenSrcSentLenItem: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem_translationsItem_sentLen_srcSentLenItem", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemSentLenSrcSentLenItem", modelProperties: { integer: { serializedName: "integer", type: { name: "Number" } } } } }; export const TranslateResultAllItemTranslationsItemSentLenTransSentLenItem: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem_translationsItem_sentLen_transSentLenItem", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemSentLenTransSentLenItem", modelProperties: { integer: { serializedName: "integer", type: { name: "Number" } } } } }; export const TranslateResultAllItemTranslationsItemSentLen: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem_translationsItem_sentLen", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemSentLen", modelProperties: { srcSentLen: { serializedName: "srcSentLen", type: { name: "Sequence", element: { type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemSentLenSrcSentLenItem" } } } }, transSentLen: { serializedName: "transSentLen", type: { name: "Sequence", element: { type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemSentLenTransSentLenItem" } } } } } } }; export const TranslateResultAllItemTranslationsItem: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem_translationsItem", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItem", modelProperties: { text: { serializedName: "text", type: { name: "String" } }, transliteration: { serializedName: "transliteration", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemTransliteration" } }, to: { serializedName: "to", type: { name: "String" } }, alignment: { serializedName: "alignment", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemAlignment" } }, sentLen: { serializedName: "sentLen", type: { name: "Composite", className: "TranslateResultAllItemTranslationsItemSentLen" } } } } }; export const TranslateResultAllItem: msRest.CompositeMapper = { serializedName: "TranslateResultAllItem", type: { name: "Composite", className: "TranslateResultAllItem", modelProperties: { detectedLanguage: { serializedName: "detectedLanguage", type: { name: "Composite", className: "TranslateResultAllItemDetectedLanguage" } }, translations: { serializedName: "translations", type: { name: "Sequence", element: { type: { name: "Composite", className: "TranslateResultAllItemTranslationsItem" } } } } } } }; export const BreakSentenceResultItem: msRest.CompositeMapper = { serializedName: "BreakSentenceResultItem", type: { name: "Composite", className: "BreakSentenceResultItem", modelProperties: { sentLen: { serializedName: "sentLen", type: { name: "Sequence", element: { type: { name: "Number" } } } } } } }; export const TransliterateResultItem: msRest.CompositeMapper = { serializedName: "TransliterateResultItem", type: { name: "Composite", className: "TransliterateResultItem", modelProperties: { text: { serializedName: "text", type: { name: "String" } }, script: { serializedName: "script", type: { name: "String" } } } } }; export const DetectResultItem: msRest.CompositeMapper = { serializedName: "DetectResultItem", type: { name: "Composite", className: "DetectResultItem", modelProperties: { text: { serializedName: "text", type: { name: "String" } } } } }; export const BreakSentenceTextInput: msRest.CompositeMapper = { serializedName: "BreakSentenceTextInput", type: { name: "Composite", className: "BreakSentenceTextInput", modelProperties: { text: { serializedName: "text", type: { name: "String" } } } } }; export const ErrorMessageError: msRest.CompositeMapper = { serializedName: "ErrorMessage_error", type: { name: "Composite", className: "ErrorMessageError", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } } } } }; export const ErrorMessage: msRest.CompositeMapper = { serializedName: "ErrorMessage", type: { name: "Composite", className: "ErrorMessage", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "ErrorMessageError" } } } } }; export const DetectTextInput: msRest.CompositeMapper = { serializedName: "DetectTextInput", type: { name: "Composite", className: "DetectTextInput", modelProperties: { text: { serializedName: "text", type: { name: "String" } } } } }; export const DictionaryLookupTextInput: msRest.CompositeMapper = { serializedName: "DictionaryLookupTextInput", type: { name: "Composite", className: "DictionaryLookupTextInput", modelProperties: { text: { serializedName: "text", type: { name: "String" } } } } }; export const DictionaryExampleTextInput: msRest.CompositeMapper = { serializedName: "DictionaryExampleTextInput", type: { name: "Composite", className: "DictionaryExampleTextInput", modelProperties: { text: { serializedName: "text", type: { name: "String" } }, translation: { serializedName: "translation", type: { name: "String" } } } } }; export const TranslateTextInput: msRest.CompositeMapper = { serializedName: "TranslateTextInput", type: { name: "Composite", className: "TranslateTextInput", modelProperties: { text: { serializedName: "text", type: { name: "String" } } } } }; export const TransliterateTextInput: msRest.CompositeMapper = { serializedName: "TransliterateTextInput", type: { name: "Composite", className: "TransliterateTextInput", modelProperties: { text: { serializedName: "text", type: { name: "String" } } } } };
the_stack
import type { TwitterUserEntities, LimitStatus, Limit, ReactionV2Kind, } from './background/twitter-api' const userNameBlacklist = [ 'about', 'account', 'blog', 'compose', 'download', 'explore', 'followers', 'followings', 'hashtag', 'home', 'i', 'intent', 'lists', 'login', 'logout', 'messages', 'notifications', 'oauth', 'privacy', 'search', 'session', 'settings', 'share', 'signup', 'tos', 'welcome', ] export const enum SessionStatus { Initial, AwaitingUntilRecur, Running, RateLimited, Completed, Stopped, Error, } export class EventEmitter<T> { protected events: EventStore = new Proxy( {}, { get(target: EventStore, name: string) { const originalValue = Reflect.get(target, name) if (Array.isArray(originalValue)) { return originalValue } Reflect.set(target, name, []) return Reflect.get(target, name) }, } ) on<K extends keyof T>(eventName: string & K, handler: (p: T[K]) => void) { this.events[eventName].push(handler) return this } emit<K extends keyof T>(eventName: string & K, eventHandlerParameter: T[K]) { const handlers = [...this.events[eventName], ...this.events['*']] // console.debug('EventEmitter: emit "%s" with %o', eventName, eventHandlerParameter) handlers.forEach(handler => handler(eventHandlerParameter)) return this } } export class TwitterUserMap extends Map<string, TwitterUser> { public addUser(user: TwitterUser) { return this.set(user.id_str, user) } public hasUser(user: TwitterUser) { return this.has(user.id_str) } public toUserArray(): TwitterUser[] { return Array.from(this.values()) } public toUserObject(): TwitterUserEntities { const usersObj: TwitterUserEntities = Object.create(null) for (const [userId, user] of this) { usersObj[userId] = user } return usersObj } public static fromUsersArray(users: TwitterUser[]): TwitterUserMap { return new TwitterUserMap(users.map((user): [string, TwitterUser] => [user.id_str, user])) } public map<T>(fn: (user: TwitterUser, index: number, array: TwitterUser[]) => T): T[] { return this.toUserArray().map(fn) } public filter( fn: (user: TwitterUser, index: number, array: TwitterUser[]) => boolean ): TwitterUserMap { return TwitterUserMap.fromUsersArray(this.toUserArray().filter(fn)) } public merge(anotherMap: TwitterUserMap) { for (const user of anotherMap.values()) { this.addUser(user) } } } export class TwitterURL extends URL { public constructor(url: string | URL | Location | HTMLAnchorElement) { super(url.toString()) this.validateURL(this) } public static nullable(url: string | URL | Location | HTMLAnchorElement): TwitterURL | null { try { const twURL = new TwitterURL(url) return twURL } catch { return null } } public getUserName(): string | null { const { pathname } = this const nonUserPagePattern = /^\/[a-z]{2}\/(?:tos|privacy)/ if (nonUserPagePattern.test(pathname)) { return null } const pattern = /^\/([0-9A-Za-z_]{1,15})/i const match = pattern.exec(pathname) if (!match) { return null } const userName = match[1] if (validateUserName(userName)) { return userName } return null } public getTweetId(): string | null { const match = /\/status\/(\d+)/.exec(this.pathname) return match && match[1] } public getAudioSpaceId(): string | null { const match = /^\/i\/spaces\/([A-Za-z0-9]+)/.exec(this.pathname) return match && match[1] } public getHashTag(): string | null { const match = /^\/hashtag\/(.+)$/.exec(this.pathname) return match && decodeURIComponent(match[1]) } private validateURL(url: URL | Location | HTMLAnchorElement) { if (url.protocol !== 'https:') { throw new Error(`invalid protocol "${this.protocol}"!`) } const validHostnames = ['twitter.com', 'mobile.twitter.com', 'tweetdeck.twitter.com'] if (!validHostnames.includes(this.hostname)) { throw new Error(`invalid hostname "${this.hostname}"!`) } } } export function validateUserName(userName: string): boolean { const pattern = /[0-9A-Za-z_]{1,15}/i if (userNameBlacklist.includes(userName.toLowerCase())) { return false } return pattern.test(userName) } export function sleep(time: number): Promise<void> { return new Promise(resolve => window.setTimeout(resolve, time)) } export function copyFrozenObject<T extends object>(obj: T): Readonly<T> { return Object.freeze(Object.assign({}, obj)) } export async function collectAsync<T>(generator: AsyncIterableIterator<T>): Promise<T[]> { const result: T[] = [] for await (const val of generator) { result.push(val) } return result } export function getFollowersCount(user: TwitterUser, followKind: FollowKind): number | null { switch (followKind) { case 'followers': return user.followers_count case 'friends': return user.friends_count case 'mutual-followers': return null } } export function getReactionsV2CountsFromTweet(tweet: Tweet): { [react in ReactionV2Kind]: number } { const result: { [react in ReactionV2Kind]: number } = { Like: 0, Hmm: 0, Haha: 0, Sad: 0, Cheer: 0, } as const Object.assign(result, Object.fromEntries(tweet.ext.signalsReactionMetadata.r.ok.reactionTypeMap)) return result } export function getTotalCountOfReactions(target: TweetReactionSessionTarget): number { let result = 0 const { retweet_count, favorite_count } = target.tweet const mentions = target.tweet.entities.user_mentions || [] if (target.includeRetweeters) { result += retweet_count } if (target.includeLikers) { result += favorite_count } else { const v2Reactions = getReactionsV2CountsFromTweet(target.tweet) target.includedReactionsV2.forEach(reaction => { result += v2Reactions[reaction] }) } if (target.includeMentionedUsers) { result += mentions.length } if (target.includeQuotedUsers) { result += target.tweet.quote_count } if (target.includeNonLinkedMentions) { result += findNonLinkedMentionsFromTweet(target.tweet).length } return result } export function getParticipantsInAudioSpaceCount(target: AudioSpaceSessionTarget): number { const { audioSpace, includeHostsAndSpeakers, includeListeners } = target let count = 0 if (includeHostsAndSpeakers) { count += audioSpace.participants.admins.length count += audioSpace.participants.speakers.length } if (includeListeners) { count += audioSpace.participants.listeners.length } return count } export function getCountOfUsersToBlock({ target, }: SessionRequest<AnySessionTarget>): number | null { switch (target.type) { case 'follower': case 'lockpicker': return getFollowersCount(target.user, target.list) case 'tweet_reaction': return getTotalCountOfReactions(target) case 'import': return target.userIds.length + target.userNames.length case 'audio_space': return getParticipantsInAudioSpaceCount(target) case 'user_search': case 'export_my_blocklist': return null } } /* runningSession이면... * 확장기능버튼 뱃지숫자에 합산됨 * 동일세션 실행여부에 포함 * '완료세션 지우기'에서 예외가 됨. */ export function isRunningSession({ status }: SessionInfo): boolean { const runningStatuses = [ SessionStatus.Initial, SessionStatus.AwaitingUntilRecur, SessionStatus.Running, SessionStatus.RateLimited, ] return runningStatuses.includes(status) } export function isRewindableSession({ status, request }: SessionInfo): boolean { if (request.purpose.type === 'export') { return false } const rewindableStatus: SessionStatus[] = [ SessionStatus.AwaitingUntilRecur, SessionStatus.Completed, SessionStatus.Stopped, ] return rewindableStatus.includes(status) } export function getLimitResetTime(limit: Limit): string { const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone const formatter = new Intl.DateTimeFormat('ko-KR', { timeZone, hour: '2-digit', minute: '2-digit', }) const datetime = new Date(limit.reset * 1000 + 120000) return formatter.format(datetime) } export function unwrap<T>(maybeValue: Either<Error, T>) { if (maybeValue.ok) { return maybeValue.value } else { const { error } = maybeValue console.error(error) throw error } } export function wrapEitherRight<T>(value: T): EitherRight<T> { return { ok: true, value, } } export function assertNever(shouldBeNever: never): never { console.error('triggered assertNever with: ', shouldBeNever) throw new Error('unreachable: assertNever') } /* function* resumableIterate<T>(generator: Generator<T>) { while (true) { let item = generator.next() if (item.done) { return item.value } else { yield item.value } } } */ // generator를 for-of loop등으로 iterate하는 도중 break를 걸면, 그 generator를 다시 iterate할 수 없더라. // 이를 해결하기 위해 while loop과 .next()로 수동으로 iterate하는 함수 만듦 export async function* resumableAsyncIterate<T>(asyncGenerator: AsyncIterableIterator<T>) { while (true) { const item = await asyncGenerator.next() if (item.done) { return item.value } else { yield item.value } } } function* iterateRegExpMatches(pattern: RegExp, text: string): Generator<string[]> { if (!pattern.global) { throw new TypeError('TypeError: pattern must set global flag') } let matches: RegExpExecArray | null let limitcounter = 5000 while ((matches = pattern.exec(text))) { if (limitcounter-- <= 0) { throw new Error('too many loops?') } yield matches } } export function findMentionsFromText(text: string): string[] { const iterator = iterateRegExpMatches(/@([A-Za-z0-9_]{1,15})/gi, text) const result = new Set<string>() for (const matches of iterator) { const userName = matches[1] if (validateUserName(userName)) { result.add(userName) } } return Array.from(result) } export function findNonLinkedMentions(text: string): string[] { const iterator = iterateRegExpMatches(/@[ ./]([A-Za-z0-9_]{1,15})\b/gi, text) const result = new Set<string>() for (const matches of iterator) { const userName = matches[1] if (validateUserName(userName)) { result.add(userName) } } return Array.from(result) } export function findNonLinkedMentionsFromTweet(tweet: Tweet) { return findNonLinkedMentions(tweet.full_text) } export function stripSensitiveInfo(user: TwitterUser): TwitterUser { try { const userAsAny = user as any if (Object.isFrozen(userAsAny)) { const clonedUser = Object.assign(Object.create(null), userAsAny) return stripSensitiveInfo(clonedUser) } delete userAsAny.email delete userAsAny.phone } catch (err) { console.error(err) } return user } export function isExportableTarget(target: AnySessionTarget): target is ExportableSessionTarget { switch (target.type) { case 'follower': case 'tweet_reaction': case 'audio_space': case 'export_my_blocklist': return true case 'import': case 'lockpicker': case 'user_search': return false } } export function extractRateLimit(limitStatuses: LimitStatus, apiKind: ScrapingApiKind): Limit { switch (apiKind) { case 'followers': return limitStatuses.followers['/followers/list'] case 'friends': return limitStatuses.friends['/friends/list'] case 'mutual-followers': return limitStatuses.followers['/followers/list'] case 'tweet-reactions': return limitStatuses.statuses['/statuses/retweeted_by'] case 'lookup-users': return limitStatuses.users['/users/lookup'] case 'search': return limitStatuses.search['/search/adaptive'] case 'block-ids': return limitStatuses.blocks['/blocks/ids'] } }
the_stack
type SteamID = import('steamid'); import SteamUser = require('..'); import EventEmitter = require('events'); export = SteamChatRoomClient; declare class SteamChatRoomClient extends EventEmitter { constructor(user: SteamUser); // EVENTS on<K extends keyof ChatEvents>(event: K, listener: (...args: ChatEvents[K]) => void): this; once<K extends keyof ChatEvents>(event: K, listener: (...args: ChatEvents[K]) => void): this; off<K extends keyof ChatEvents>(event: K, listener: (...args: ChatEvents[K]) => void): this; removeListener<K extends keyof ChatEvents>(event: K, listener: (...args: ChatEvents[K]) => void): this; removeAllListeners(event?: keyof ChatEvents): this; /** * Get a list of the chat room groups you're in. * @param [callback] */ getGroups(callback?: (err: Error | null, response: { chat_room_groups: Record<string, ChatRoomGroup> }) => void): Promise<{ chat_room_groups: Record<string, ChatRoomGroup> }>; /** * Set which groups are actively being chatted in by this session. It's unclear what effect this has on the chatting * experience, other than retrieving chat room group states. * @param groupIDs - Array of group IDs you want data for * @param [callback] */ setSessionActiveGroups(groupIDs: number[] |string[] | number | string, callback?: ( err: Error | null, response: { chat_room_groups: Record<string, ChatRoomGroupState> }, ) => void ): Promise<{ chat_room_groups: Record<string, ChatRoomGroupState> }>; /** * Get details from a chat group invite link. * @param linkUrl * @param [callback] */ getInviteLinkInfo(linkUrl: string, callback: (err: Error | null, response: InviteLinkInfo) => void): Promise<InviteLinkInfo>; /** * Get the chat room group info for a clan (Steam group). Allows you to join a group chat. * @param clanSteamID - The group's SteamID or a string that can parse into one * @param [callback] */ getClanChatGroupInfo(clanSteamID: SteamID | string, callback?: ( err: Error | null, response: { chat_group_summary: ChatRoomGroupSummary }, ) => void ): Promise<{ chat_group_summary: ChatRoomGroupSummary }>; /** * Join a chat room group. * @param groupId - The group's ID * @param [inviteCode] - An invite code to join this chat. Not necessary for public Steam groups. * @param [callback] */ joinGroup(groupId: number | string, inviteCode?: string, callback?: ( err: Error | null, response: { state: ChatRoomGroupState; user_chat_state: UserChatRoomGroupState }, ) => void ): Promise<{ state: ChatRoomGroupState; user_chat_state: UserChatRoomGroupState }>; /** * Invite a friend to a chat room group. * @param groupId * @param steamId * @param [callback] */ inviteUserToGroup(groupId: number, steamId: SteamID | string, callback?: (err: Error | null) => void): Promise<void>; /** * Create an invite link for a given chat group. * @param groupId * @param [options] * @param [callback] */ createInviteLink(groupId: number, options?: {secondsValid?: number; voiceChatId?: number}, callback?: ( err: Error | null, response: { invite_code: string; invite_url: string; seconds_valid: number }, ) => void ): Promise<{ invite_code: string; invite_url: string; seconds_valid: number }>; /** * Get all active invite links for a given chat group. * @param groupId * @param [callback] */ getGroupInviteLinks(groupId: number, callback?: ( err: Error | null, response: { invite_links: GroupInviteLinks[] }, ) => void ): Promise<{ invite_links: GroupInviteLinks[] }>; /** * Revoke and delete an active invite link. * @param linkUrl * @param [callback] */ deleteInviteLink(linkUrl: string, callback?: (err: Error | null) => void): Promise<void>; /** * Send a direct chat message to a friend. * @param steamId * @param message * @param [options] * @param [callback] */ sendFriendMessage(steamId: SteamID | string, message: string, options?: { chatEntryType?: SteamUser.EChatEntryType; containsBbCode?: boolean }, callback?: ( err: Error | null, response: SentMessage, ) => void ): Promise<SentMessage>; /** * Inform a friend that you're typing a message to them. * @param steamId * @param [callback] */ sendFriendTyping(steamId: SteamID | string, callback?: (err: Error | null) => void): Promise<void>; /** * Send a message to a chat room. * @param groupId * @param chatId * @param message * @param [callback] */ sendChatMessage(groupId: number | string, chatId: number | string, message: string, callback?: ( err: Error | null, response: SentMessage, ) => void ): Promise<SentMessage>; /** * Delete one or more messages from a chat channel. * @param groupId * @param chatId * @param messages * @param [callback] */ deleteChatMessages(groupId: number | string, chatId: number | string, messages: Array<MessageToDelete1 | MessageToDelete2>, callback?: (err: Error | null) => void): Promise<void>; /** * Create a text/voice chat room in a group, provided you have permissions to do so. * @param groupId - The ID of the group in which you want to create the channel * @param name - The name of your new channel * @param [options] - Options for your new room * @param [callback] */ createChatRoom(groupId: number | string, name: string, options?: { isVoiceRoom: boolean }, callback?: ( err: Error | null, response: { chat_room: ChatRoomState }, ) => void ): Promise<{ chat_room: ChatRoomState }>; /** * Rename a text/voice chat room in a group, provided you have permissions to do so. * @param groupId - The ID of the group in which you want to rename the room * @param chatId - The ID of the chat room you want to rename * @param newChatRoomName - The new name for the room * @param [callback] */ renameChatRoom(groupId: number | string, chatId: number | string, newChatRoomName: string, callback?: (err: Error | null) => void): Promise<void>; /** * Delete a text/voice chat room in a group (and all the messages it contains), provided you have permissions to do so. * @param groupId - The ID of the group in which you want to delete a room * @param chatId - The ID of the room you want to delete * @param [callback] */ deleteChatRoom(groupId: number | string, chatId: number | string, callback?: (err: Error | null) => void): Promise<void>; /** * Kick a user from a chat room group. * @param groupId * @param steamId * @param [expireTime] - Time when they should be allowed to join again. Omit for immediate. * @param [callback] */ kickUserFromGroup(groupId: number | string, steamId: SteamID | string, expireTime?: Date | number, callback?: (err: Error | null) => void): Promise<void>; /** * Get the ban list for a chat room group, provided you have the appropriate permissions. * @param groupId * @param [callback] */ getGroupBanList(groupId?: number | string, callback?: (err: Error | null, response: { bans: Ban[] }) => void): Promise<{ bans: Ban[] }>; /** * Ban or unban a user from a chat room group, provided you have the appropriate permissions. * @param groupId * @param userSteamId * @param banState - True to ban, false to unban * @param [callback] */ setGroupUserBanState(groupId: number | string, userSteamId: SteamID | string, banState: boolean, callback?: (err: Error | null) => void): Promise<void>; /** * Get a list of which friends we have "active" (recent) message sessions with. * @param [options] * @param [callback] */ getActiveFriendMessageSessions(options?: { conversationsSince: Date | number }, callback?: ( err: Error | null, response: { sessions: ActiveFriendMessageSession[]; timestamp: Date }, ) => void ): Promise<any>; /** * Get your chat message history with a Steam friend. * @param friendSteamId * @param [options] * @param [callback] */ getFriendMessageHistory(friendSteamId: SteamID | string, options?: GetMessageHistoryOptions, callback?: ( err: Error | null, response: { messages: FriendMessage[], more_available: boolean }, ) => void ): Promise<{ messages: FriendMessage[], more_available: boolean }>; /** * Get message history for a chat (channel). * @param groupId * @param chatId * @param [options] * @param [callback] */ getChatMessageHistory(groupId: number | string, chatId: number | string, options?: GetMessageHistoryOptions, callback?: ( err: Error | null, response: { message: ChatMessage[], more_available: boolean }, ) => void ): Promise<{ message: ChatMessage[], more_available: boolean }>; /** * Acknowledge (mark as read) a friend message * @param friendSteamId - The SteamID of the friend whose message(s) you want to acknowledge * @param timestamp - The timestamp of the newest message you're acknowledging (will ack all older messages) */ ackFriendMessage(friendSteamId: SteamID | string, timestamp: Date | number): void; } //#region "Events" interface ChatEvents { friendMessage: [message: IncomingFriendMessage]; friendMessageEcho: [message: IncomingFriendMessage]; friendTyping: [message: IncomingFriendMessage]; friendTypingEcho: [message: IncomingFriendMessage]; friendLeftConversation: [message: IncomingFriendMessage]; friendLeftConversationEcho: [message: IncomingFriendMessage]; chatMessage: [message: IncomingChatMessage]; chatMessagesModified: [details: ModifiedMessage[]]; } //#endregion "Events" //#region "Response Interfaces" interface ChatMessage { sender: SteamID; server_timestamp: Date; ordinal: number; message: string; server_message: ServerMessage; deleted: boolean; } interface FriendMessage { sender: SteamID; server_timestamp: Date; ordinal: number; message: string; message_bbcode_parsed: null | Array<string | Record<string, any>>; } interface ActiveFriendMessageSession { steamid_friend: SteamID; time_last_message: Date; time_last_view: Date; unread_message_count: number; } interface Ban { steamid: SteamID; steamid_actor: SteamID; time_banned: Date; ban_reason: ''; // always empty, SteamUI doesn't support ban reasons } interface SentMessage { modified_message: string; server_timestamp: Date; ordinal: number; } interface GroupInviteLinks { invite_code: string; invite_url: string; steamid_creator: SteamID; time_expires: Date | null; chat_id: string; } interface InviteLinkInfo { invite_code: string; steamid_sender: SteamID; time_expires: Date | null; group_summary: ChatRoomGroupSummary; time_kick_expire: Date | null; banned: boolean; } //#endregion "Response Interfaces" //#region "Interfaces" interface ModifiedMessage { chat_group_id: string; chat_id: string; messages: { server_timestamp: Date; ordinal: number; deleted: boolean; }; } interface MessageToDelete1 { server_timestamp: Date; ordinal?: number; } interface MessageToDelete2 { timestamp: Date; ordinal?: number; } interface GetMessageHistoryOptions { maxCount?: number; wantBbcode?: boolean; startTime?: Date | number; startOrdinal?: number; lastTime?: Date | number; lastOrdinal?: number; } interface ServerMessage { message: SteamUser.EChatRoomServerMessage; string_param?: string; steamid_param?: SteamID; } interface ChatMentions { mention_all: boolean; mention_here: boolean; mention_steamids: SteamID[]; } interface IncomingChatMessage { chat_group_id: string; chat_id: string; steamid_sender: SteamID; message: string; message_no_bbcode: string; server_timestamp: Date; ordinal: number; mentions: ChatMentions | null; server_message: ServerMessage | null; chat_name: string; } interface IncomingFriendMessage { steamid_friend: SteamID; chat_entry_type: SteamUser.EChatEntryType; from_limited_account: boolean; message: string; message_no_bbcode: string; message_bbcode_parsed: Array<string | Record<string, any>>; server_timestamp: Date; ordinal: number; local_echo: boolean; low_priority: boolean; } interface UserChatRoomState { chat_id: string; time_joined: Date; time_last_ack: Date | null; desktop_notification_level: SteamUser.EChatRoomNotificationLevel; mobile_notification_level: SteamUser.EChatRoomNotificationLevel; time_last_mention: Date | null; unread_indicator_muted: boolean; time_first_unread: Date; } interface UserChatRoomGroupState { chat_group_id: string; time_joined: Date; user_chat_room_state: UserChatRoomState[]; desktop_notification_level: SteamUser.EChatRoomNotificationLevel; mobile_notification_level: SteamUser.EChatRoomNotificationLevel; time_last_group_ack: Date | null; unread_indicator_muted: boolean; } interface ChatRoleActions { role_id: string; can_create_rename_delete_channel: boolean; can_kick: boolean; can_ban: boolean; can_invite: boolean; can_change_tagline_avatar_name: boolean; can_chat: boolean; can_view_history: boolean; can_change_group_roles: boolean; can_change_user_roles: boolean; can_mention_all: boolean; can_set_watching_broadcast: boolean; } interface ChatRole { role_id: string; name: string; ordinal: number; } interface ChatRoomGroupHeaderState { chat_group_id: string; chat_name: string; clanid: SteamID | null; steamid_owner: SteamID; appid: number | null; tagline: string; avatar_sha: Buffer | null; avatar_url: string | null; default_role_id: string; roles: ChatRole[]; role_actions: ChatRoleActions[]; watching_broadcast_steamid?: SteamID | null; // not sure if optional or null } interface ChatRoomMember { steamid: SteamID; state: SteamUser.EChatRoomJoinState; rank: SteamUser.EChatRoomGroupRank; time_kick_expire: Date | null; role_ids: string[]; } interface ChatRoomGroupState { members: ChatRoomMember[]; chat_rooms: ChatRoomState[]; kicked: ChatRoomMember[]; default_chat_id: string; header_state: ChatRoomGroupHeaderState; } interface ChatRoomState { chat_id: string; chat_name: string; voice_allowed: boolean; members_in_voice: SteamID[]; time_last_message: Date; sort_order: number; last_message: string; steamid_last_message: SteamID; } interface ChatRoomGroupSummary { chat_rooms: ChatRoomState[]; top_members: SteamID[]; chat_group_id: string; chat_group_name: string; active_member_count: number; active_voice_member_count: number; default_chat_id: string; chat_group_tagline: string; appid: number | null; steamid_owner: SteamID; watching_broadcast_steamid?: SteamID | null; // not sure if optional or null chat_group_avatar_sha: Buffer | null; chat_group_avatar_url: string | null; } interface ChatRoomGroup { group_summary: ChatRoomGroupSummary; } //#endregion "Interfaces"
the_stack
import { BrowserModule } from '@angular/platform-browser'; import { NgModule, APP_INITIALIZER } from '@angular/core'; import { HttpModule, Http } from '@angular/http'; import { HttpClient } from '@angular/common/http'; import { AppComponent } from './app.component'; import { Observable } from 'rxjs'; // Directives import { TooltipModule } from 'ng2-tooltip-directive'; // Import the library module import { environment } from '../environments/environment'; import { HttpClientModule} from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { LocalStorageModule } from 'angular-2-local-storage'; import { MomentModule } from 'angular2-moment'; import { LinkyModule } from 'angular-linky'; import { AngularResizedEventModule } from 'angular-resize-event'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader/src/http-loader'; //pipe import { MarkedPipe } from './directives/marked.pipe'; import { HtmlEntitiesEncodePipe } from './directives/html-entities-encode.pipe'; import { SafeHtmlPipe } from './directives/safe-html.pipe'; // utils import { Globals } from './utils/globals'; // users import { UserLoginComponent } from './users/user-login/user-login.component'; import { UserProfileComponent } from './users/user-profile/user-profile.component'; // providers import { GlobalSettingsService } from './providers/global-settings.service'; import { SettingsSaverService } from './providers/settings-saver.service'; import { StorageService } from './providers/storage.service'; import { ChatPresenceHandlerService } from './providers/chat-presence-handler.service'; import { AuthService_old } from './providers/auth.service'; import { MessagingService } from './providers/messaging.service'; import { ConversationsService } from './providers/conversations.service'; import { ContactService } from './providers/contact.service'; import { AgentAvailabilityService } from './providers/agent-availability.service'; import { TranslatorService } from './providers/translator.service'; import { WaitingService } from './providers/waiting.service'; import { AppConfigService } from './providers/app-config.service'; //------------------------>>>>> COMPONENTS <<<<<------------------------// // ______________ HOME ________________ // import { HomeComponent } from './components/home/home.component'; import { HomeConversationsComponent } from './components/home-conversations/home-conversations.component'; // ___________DEPARTMENT______________// import { SelectionDepartmentComponent } from './components/selection-department/selection-department.component'; import { LauncherButtonComponent } from './components/launcher-button/launcher-button.component'; import { MessageAttachmentComponent } from './components/message-attachment/message-attachment.component'; import { PrechatFormComponent } from './components/prechat-form/prechat-form.component'; import { EyeeyeCatcherCardComponent } from './components/eyeeye-catcher-card/eyeeye-catcher-card.component'; import { PreviewLoadingFilesComponent } from './components/preview-loading-files/preview-loading-files.component'; import { MenuOptionsComponent } from './components/menu-options/menu-options.component'; import { StarRatingWidgetComponent } from './components/star-rating-widget/star-rating-widget.component'; import { StarRatingWidgetService } from './components/star-rating-widget/star-rating-widget.service'; import { LastMessageComponent } from './components/last-message/last-message.component'; import { SendButtonComponent } from './components/send-button/send-button.component'; // ___________ CONVERSATIONS LIST ______________// import { ListAllConversationsComponent } from './components/list-all-conversations/list-all-conversations.component'; import { ListConversationsComponent } from './components/list-conversations/list-conversations.component'; // ___________ CONVERSATIONS ELEMENT ______________// import { ConversationComponent } from './components/conversation-detail/conversation/conversation.component'; import { ConversationHeaderComponent } from './components/conversation-detail/conversation-header/conversation-header.component'; import { ConversationContentComponent } from './components/conversation-detail/conversation-content/conversation-content.component'; import { ConversationFooterComponent } from './components/conversation-detail/conversation-footer/conversation-footer.component'; import { ConversationPreviewComponent } from './components/conversation-detail/conversation-preview/conversation-preview.component'; import { BubbleMessageComponent } from './components/message/bubble-message/bubble-message.component'; import { TextComponent } from './components/message/text/text.component'; import { HtmlComponent } from './components/message/html/html.component'; import { ImageComponent } from './components/message/image/image.component'; import { TextButtonComponent } from './components/message/buttons/text-button/text-button.component'; import { FrameComponent } from './components/message/frame/frame.component'; import { LinkButtonComponent } from './components/message/buttons/link-button/link-button.component'; import { ActionButtonComponent } from './components/message/buttons/action-button/action-button.component'; import { AvatarComponent } from './components/message/avatar/avatar.component'; import { ReturnReceiptComponent } from './components/message/return-receipt/return-receipt.component'; import { InfoMessageComponent } from './components/message/info-message/info-message.component'; import { InterlalFrameComponent } from './components/conversation-detail/interlal-frame/interlal-frame.component'; // **************** CHAT21-CORE ************************ // //COMPONENTS import { UserTypingComponent } from '../../src/chat21-core/utils/user-typing/user-typing.component'; //CONSTANTS import { CHAT_ENGINE_MQTT, UPLOAD_ENGINE_NATIVE } from '../../src/chat21-core/utils/constants'; //TRIGGER-HANDLER import { Triggerhandler } from '../chat21-core/utils/triggerHandler'; //SERVICES // import { DatabaseProvider } from '../chat21-core/providers/database'; import { ChatManager } from './../chat21-core/providers/chat-manager'; import { CustomTranslateService } from './../chat21-core/providers/custom-translate.service'; //ABSTRACT SERVICES import { MessagingAuthService } from '../chat21-core/providers/abstract/messagingAuth.service'; import { ConversationHandlerBuilderService } from '../chat21-core/providers/abstract/conversation-handler-builder.service'; import { ConversationsHandlerService } from '../chat21-core/providers/abstract/conversations-handler.service'; import { ArchivedConversationsHandlerService } from '../chat21-core/providers/abstract/archivedconversations-handler.service'; import { ConversationHandlerService } from '../chat21-core/providers/abstract/conversation-handler.service'; import { ImageRepoService } from '../chat21-core/providers/abstract/image-repo.service'; import { TypingService } from '../chat21-core/providers/abstract/typing.service'; import { PresenceService } from '../chat21-core/providers/abstract/presence.service'; import { UploadService } from '../chat21-core/providers/abstract/upload.service'; import { AppStorageService } from '../chat21-core/providers/abstract/app-storage.service'; //FIREBASE SERVICES import { FirebaseInitService } from '../chat21-core/providers/firebase/firebase-init-service'; import { FirebaseAuthService } from '../chat21-core/providers/firebase/firebase-auth-service'; import { FirebaseConversationHandlerBuilderService } from '../chat21-core/providers/firebase/firebase-conversation-handler-builder.service'; import { FirebaseConversationsHandler } from '../chat21-core/providers/firebase/firebase-conversations-handler'; import { FirebaseArchivedConversationsHandler } from '../chat21-core/providers/firebase/firebase-archivedconversations-handler'; import { FirebaseConversationHandler } from '../chat21-core/providers/firebase/firebase-conversation-handler'; import { FirebaseTypingService } from '../chat21-core/providers/firebase/firebase-typing.service'; import { FirebasePresenceService } from '../chat21-core/providers/firebase/firebase-presence.service'; import { FirebaseImageRepoService } from '../chat21-core/providers/firebase/firebase-image-repo'; import { FirebaseUploadService } from '../chat21-core/providers/firebase/firebase-upload.service'; // MQTT import { Chat21Service } from '../chat21-core/providers/mqtt/chat-service'; import { MQTTAuthService } from '../chat21-core/providers/mqtt/mqtt-auth-service'; import { MQTTConversationHandlerBuilderService } from '../chat21-core/providers/mqtt/mqtt-conversation-handler-builder.service'; import { MQTTConversationsHandler } from '../chat21-core/providers/mqtt/mqtt-conversations-handler'; import { MQTTArchivedConversationsHandler } from '../chat21-core/providers/mqtt/mqtt-archivedconversations-handler'; import { MQTTConversationHandler } from '../chat21-core/providers/mqtt/mqtt-conversation-handler'; import { MQTTTypingService } from '../chat21-core/providers/mqtt/mqtt-typing.service'; import { MQTTPresenceService } from '../chat21-core/providers/mqtt/mqtt-presence.service'; //NATIVE import { NativeUploadService } from '../chat21-core/providers/native/native-upload-service'; import { NativeImageRepoService } from '../chat21-core/providers/native/native-image-repo'; //TILEDESK import { TiledeskAuthService } from './../chat21-core/providers/tiledesk/tiledesk-auth.service'; //LOGGER SERVICES import { CustomLogger } from '../chat21-core/providers/logger/customLogger'; import { LocalSessionStorage } from '../chat21-core/providers/localSessionStorage'; import { LoggerInstance } from '../chat21-core/providers/logger/loggerInstance'; //FORM COMPONENT import { FormBuilderComponent } from './components/form/form-builder/form-builder.component'; import { RadioButtonComponent } from './components/form/inputs/radio-button/radio-button.component'; import { SelectComponent } from './components/form/inputs/select/select.component'; import { FormTextComponent } from './components/form/inputs/form-text/form-text.component'; import { FormLabelComponent } from './components/form/inputs/form-label/form-label.component'; import { FormCheckboxComponent } from './components/form/inputs/form-checkbox/form-checkbox.component'; import { FormTextareaComponent } from './components/form/inputs/form-textarea/form-textarea.component'; export class TranslateHttpLoaderCustom implements TranslateLoader { constructor(private http: HttpClient, public prefix: string = "/assets/i18n/", public suffix: string = ".json") {} public getTranslation(lang: string): Observable<Object> { console.log('getTranslation', lang) return this.http.get(`${this.prefix}${lang}${this.suffix}`).catch(err => { console.log('err', err) lang = 'en' return this.http.get(`${this.prefix}${lang}${this.suffix}`); }); } } // FACTORIES export function createTranslateLoader(http: HttpClient) { let localUrl = './assets/i18n/'; if (location.pathname.includes('/assets/')) { localUrl = '../i18n/'; } console.log('translate factoryyyyyyyy APP MODULE') return new TranslateHttpLoaderCustom(http, localUrl, '.json'); } const appInitializerFn = (appConfig: AppConfigService) => { return () => { let customLogger = new CustomLogger() LoggerInstance.setInstance(customLogger) if (environment.remoteConfig) { return appConfig.loadAppConfig(); } }; }; export function authenticationFactory(http: HttpClient, appConfig: AppConfigService, chat21Service: Chat21Service, appSorage: AppStorageService) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { chat21Service.config = config.chat21Config; chat21Service.initChat(); const auth = new MQTTAuthService(http, chat21Service, appSorage); auth.setBaseUrl(appConfig.getConfig().apiUrl) return auth } else { FirebaseInitService.initFirebase(config.firebaseConfig) const auth= new FirebaseAuthService(http); auth.setBaseUrl(config.apiUrl) return auth } } export function conversationsHandlerFactory(chat21Service: Chat21Service, httpClient: HttpClient, appConfig: AppConfigService ) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTConversationsHandler(chat21Service); } else { return new FirebaseConversationsHandler(httpClient, appConfig); } } export function archivedConversationsHandlerFactory(chat21Service: Chat21Service, appConfig: AppConfigService) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTArchivedConversationsHandler(chat21Service); } else { return new FirebaseArchivedConversationsHandler(); } } export function conversationHandlerBuilderFactory(chat21Service: Chat21Service, appConfig: AppConfigService) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTConversationHandlerBuilderService(chat21Service); } else { return new FirebaseConversationHandlerBuilderService(); } } export function conversationHandlerFactory(chat21Service: Chat21Service, appConfig: AppConfigService) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTConversationHandler(chat21Service, true); } else { return new FirebaseConversationHandler(true); } } export function typingFactory(appConfig: AppConfigService) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTTypingService(); } else { return new FirebaseTypingService(); } } export function presenceFactory(appConfig: AppConfigService) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTPresenceService(); } else { return new FirebasePresenceService(); } } export function imageRepoFactory(appConfig: AppConfigService, http: HttpClient) { const config = appConfig.getConfig() if (config.uploadEngine === UPLOAD_ENGINE_NATIVE) { const imageService = new NativeImageRepoService() imageService.setImageBaseUrl(config.baseImageUrl) return imageService } else { const imageService = new FirebaseImageRepoService(); FirebaseInitService.initFirebase(config.firebaseConfig) imageService.setImageBaseUrl(config.baseImageUrl) return imageService } } export function uploadFactory(http: HttpClient, appConfig: AppConfigService, appStorage: AppStorageService) { const config = appConfig.getConfig() if (config.uploadEngine === UPLOAD_ENGINE_NATIVE) { const nativeUploadService = new NativeUploadService(http, appStorage) nativeUploadService.setBaseUrl(config.apiUrl) return nativeUploadService } else { return new FirebaseUploadService(); } } @NgModule({ declarations: [ AppComponent, UserLoginComponent, UserProfileComponent, StarRatingWidgetComponent, SelectionDepartmentComponent, HomeConversationsComponent, HomeComponent, LauncherButtonComponent, ConversationComponent, PrechatFormComponent, EyeeyeCatcherCardComponent, PreviewLoadingFilesComponent, MenuOptionsComponent, ListAllConversationsComponent, MessageAttachmentComponent, LastMessageComponent, MarkedPipe, HtmlEntitiesEncodePipe, ListConversationsComponent, ConversationHeaderComponent, UserTypingComponent, ConversationFooterComponent, ConversationContentComponent, BubbleMessageComponent, TextComponent, ImageComponent, TextButtonComponent, FrameComponent, LinkButtonComponent, ActionButtonComponent, AvatarComponent, ReturnReceiptComponent, InfoMessageComponent, InterlalFrameComponent, FormBuilderComponent, RadioButtonComponent, SelectComponent, FormTextComponent, FormLabelComponent, FormCheckboxComponent, FormTextareaComponent, ConversationPreviewComponent, SendButtonComponent, HtmlComponent, SafeHtmlPipe ], imports: [ BrowserModule, // firebase.initializeApp(environment.firebase), // AngularFireModule.initializeApp(environment.firebase), // AngularFireAuthModule, // imports firebase/auth, only needed for auth features // AngularFireDatabaseModule, // imports firebase/database, only needed for database features // AngularFirestoreModule, BrowserAnimationsModule, HttpModule, HttpClientModule, FormsModule, ReactiveFormsModule, LinkyModule, // https://medium.com/codingthesmartway-com-blog/using-bootstrap-with-angular-c83c3cee3f4a // NgbModule.forRoot(), LocalStorageModule.withConfig({ prefix: 'chat21-web-widget', storageType: 'localStorage' }), MomentModule, AngularResizedEventModule, TranslateModule.forRoot(//), { // loader: { // provide: TranslateLoader, // useFactory: (createTranslateLoader), // deps: [HttpClient] // } }), TooltipModule, //RouterModule.forRoot([]) ], providers: [ AppConfigService, // https://juristr.com/blog/2018/01/ng-app-runtime-config/ { provide: APP_INITIALIZER, useFactory: appInitializerFn, multi: true, deps: [AppConfigService] }, { provide: MessagingAuthService, useFactory: authenticationFactory, deps: [HttpClient, AppConfigService, Chat21Service, AppStorageService ] }, { provide: ConversationsHandlerService, useFactory: conversationsHandlerFactory, deps: [Chat21Service, HttpClient, AppConfigService] }, { provide: ArchivedConversationsHandlerService, useFactory: archivedConversationsHandlerFactory, deps: [Chat21Service, AppConfigService] }, { provide: ConversationHandlerBuilderService, useFactory: conversationHandlerBuilderFactory, deps: [Chat21Service, AppConfigService] }, { provide: ConversationHandlerService, useFactory: conversationHandlerFactory, deps: [Chat21Service, AppConfigService] }, { provide: TypingService, useFactory: typingFactory, deps: [AppConfigService] }, { provide: PresenceService, useFactory: presenceFactory, deps: [AppConfigService] }, { provide: ImageRepoService, useFactory: imageRepoFactory, deps: [AppConfigService, HttpClient] }, { provide: UploadService, useFactory: uploadFactory, deps: [HttpClient, AppConfigService, AppStorageService ] }, { provide: AppStorageService, useClass: LocalSessionStorage }, //AuthService, //MessagingService, Globals, GlobalSettingsService, SettingsSaverService, ConversationsService, //UploadService, ContactService, StarRatingWidgetService, AgentAvailabilityService, TranslatorService, //ChatPresenceHandlerService, StorageService, WaitingService, //********chat21-core***********// CustomTranslateService, ChatManager, Triggerhandler, Chat21Service, TiledeskAuthService, ], bootstrap: [AppComponent] }) export class AppModule { }
the_stack
import * as appsync from "@aws-cdk/aws-appsync-alpha"; import { aws_apigateway, aws_events_targets, aws_stepfunctions, Stack, } from "aws-cdk-lib"; // eslint-disable-next-line import/no-extraneous-dependencies import { StepFunctions } from "aws-sdk"; import { Construct } from "constructs"; import { ApiGatewayVtlIntegration } from "./api"; import { AppSyncVtlIntegration } from "./appsync"; import { ASL, isMapOrForEach, MapTask, StateMachine, States, Task, } from "./asl"; import { assertDefined } from "./assert"; import { validateFunctionDecl, FunctionDecl } from "./declaration"; import { ErrorCodes, SynthError } from "./error-code"; import { EventBus, PredicateRuleBase, Rule } from "./event-bridge"; import { EventBusTargetIntegration, makeEventBusIntegration, } from "./event-bridge/event-bus"; import { Event } from "./event-bridge/types"; import { CallExpr } from "./expression"; import { NativeIntegration, PrewarmClients } from "./function"; import { isComputedPropertyNameExpr, isErr, isFunctionDecl, isFunctionExpr, isNumberLiteralExpr, isObjectLiteralExpr, isPropAssignExpr, isSpreadAssignExpr, isStringLiteralExpr, } from "./guards"; import { Integration, IntegrationCall, IntegrationInput, makeIntegration, } from "./integration"; import { AnyFunction, ensureItemOf } from "./util"; import { VTL } from "./vtl"; export type AnyStepFunction = | ExpressStepFunction<any, any> | StepFunction<any, any>; export namespace $SFN { export const kind = "SFN"; /** * Wait for a specific number of {@link seconds}. * * ```ts * new ExpressStepFunction(this, "F", (seconds: number) => $SFN.waitFor(seconds)) * ``` * * @see https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-wait-state.html */ export const waitFor = makeStepFunctionIntegration< "waitFor", (seconds: number) => void >("waitFor", { asl(call) { const seconds = call.args[0].expr; if (seconds === undefined) { throw new Error("the 'seconds' argument is required"); } if (isNumberLiteralExpr(seconds)) { return { Type: "Wait" as const, Seconds: seconds.value, }; } else { return { Type: "Wait" as const, SecondsPath: ASL.toJsonPath(seconds), }; } }, }); /** * Wait until a {@link timestamp}. * * ```ts * new ExpressStepFunction(this, "F", (timestamp: string) => $SFN.waitUntil(timestamp)) * ``` * * @see https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-wait-state.html */ export const waitUntil = makeStepFunctionIntegration< "waitUntil", (timestamp: string) => void >("waitUntil", { asl(call) { const timestamp = call.args[0]?.expr; if (timestamp === undefined) { throw new Error("the 'timestamp' argument is required"); } if (isStringLiteralExpr(timestamp)) { return { Type: "Wait", Timestamp: timestamp.value, }; } else { return { Type: "Wait", TimestampPath: ASL.toJsonPath(timestamp), }; } }, }); interface ForEach { /** * Process each item in an {@link array} in parallel and run with the default maxConcurrency. * * Example: * ```ts * new ExpressStepFunction(this, "F"} (items: string[]) => { * $SFN.forEach(items, { maxConcurrency: 2 }, item => task(item)); * }); * ``` * * @param array the list of items to process * @param callbackfn function to process each item */ <T>( array: T[], callbackfn: (item: T, index: number, array: T[]) => void ): void; /** * Process each item in an {@link array} in parallel and run with the default maxConcurrency. * * Example: * ```ts * new ExpressStepFunction(this, "F"} (items: string[]) => { * $SFN.forEach(items, { maxConcurrency: 2 }, item => task(item)); * }); * ``` * * @param array the list of items to process * @param props configure the maxConcurrency * @param callbackfn function to process each item */ <T>( array: T[], props: { maxConcurrency: number; }, callbackfn: (item: T, index: number, array: T[]) => void ): void; } export const forEach = makeStepFunctionIntegration<"forEach", ForEach>( "forEach", { asl(call, context) { return mapOrForEach(call, context); }, } ); interface Map { /** * Map over each item in an {@link array} in parallel and run with the default maxConcurrency. * * Example: * ```ts * new ExpressStepFunction(this, "F", (items: string[]) => { * return $SFN.map(items, item => task(item)) * }); * ``` * * @param array the list of items to map over * @param callbackfn function to process each item * @returns an array containing the result of each mapped item */ <T, U>( array: T[], callbackfn: (item: T, index: number, array: T[]) => U ): U[]; /** * Map over each item in an {@link array} in parallel and run with the default maxConcurrency. * * Example: * ```ts * new ExpressStepFunction(this, "F", (items: string[]) => { * return $SFN.map(items, item => task(item)) * }); * ``` * * @param array the list of items to map over * @param props configure the maxConcurrency * @param callbackfn function to process each item * @returns an array containing the result of each mapped item */ <T, U>( array: T[], props: { maxConcurrency: number; }, callbackfn: (item: T, index: number, array: T[]) => U ): U[]; } export const map = makeStepFunctionIntegration<"map", Map>("map", { asl(call, context) { return mapOrForEach(call, context); }, }); function mapOrForEach(call: CallExpr, context: ASL): MapTask { if (isMapOrForEach(call)) { const callbackfn = call.getArgument("callbackfn")?.expr; if (callbackfn === undefined || callbackfn.kind !== "FunctionExpr") { throw new Error("missing callbackfn in $SFN.map"); } const callbackStates = context.execute(callbackfn.body); const callbackStart = context.getStateName(callbackfn.body.step()!); const props = call.getArgument("props")?.expr; let maxConcurrency: number | undefined; if (props !== undefined) { if (isObjectLiteralExpr(props)) { const maxConcurrencyProp = props.getProperty("maxConcurrency"); if ( isPropAssignExpr(maxConcurrencyProp) && isNumberLiteralExpr(maxConcurrencyProp.expr) ) { maxConcurrency = maxConcurrencyProp.expr.value; if (maxConcurrency <= 0) { throw new Error("maxConcurrency must be > 0"); } } else { throw new Error( "property 'maxConcurrency' must be a NumberLiteralExpr" ); } } else { throw new Error("argument 'props' must be an ObjectLiteralExpr"); } } const array = call.getArgument("array")?.expr; if (array === undefined) { throw new Error("missing argument 'array'"); } const arrayPath = ASL.toJsonPath(array); return { Type: "Map", ...(maxConcurrency ? { MaxConcurrency: maxConcurrency, } : {}), Iterator: { States: callbackStates, StartAt: callbackStart, }, ItemsPath: arrayPath, Parameters: Object.fromEntries( callbackfn.parameters.map((param, i) => [ `${param.name}.$`, i === 0 ? "$$.Map.Item.Value" : i == 1 ? "$$.Map.Item.Index" : arrayPath, ]) ), }; } throw new Error("invalid arguments to $SFN.map"); } /** * Run 1 or more workflows in parallel. * * ```ts * new ExpressStepFunction(this, "F", (id: string) => { * const results = $SFN.parallel( * () => task1(id) * () => task2(id) * ) * }) * ``` * @param paths */ export const parallel = makeStepFunctionIntegration< "parallel", <Paths extends readonly (() => any)[]>( ...paths: Paths ) => { [i in keyof Paths]: i extends `${number}` ? ReturnType<Extract<Paths[i], () => any>> : Paths[i]; } >("parallel", { asl(call, context) { const paths = call.getArgument("paths")?.expr; if (paths === undefined) { throw new Error("missing required argument 'paths'"); } if (paths.kind !== "ArrayLiteralExpr") { throw new Error("invalid arguments to $SFN.parallel"); } ensureItemOf( paths.items, isFunctionExpr, "each parallel path must be an inline FunctionExpr" ); return { Type: "Parallel", Branches: paths.items.map((func) => ({ StartAt: context.getStateName(func.body.step()!), States: context.execute(func.body), })), }; }, }); } function makeStepFunctionIntegration<K extends string, F extends AnyFunction>( methodName: K, integration: Omit<IntegrationInput<`$SFN.${K}`, F>, "kind"> ): F { return makeIntegration<`$SFN.${K}`, F>({ kind: `$SFN.${methodName}`, unhandledContext(kind, context) { throw new Error( `${kind} is only allowed within a '${VTL.ContextName}' context, but was called within a '${context}' context.` ); }, ...integration, }); } export function isStepFunction<P = any, O = any>( a: any ): a is StepFunction<P, O> | ExpressStepFunction<P, O> { return a?.kind === "StepFunction"; } /** * {@see https://docs.aws.amazon.com/step-functions/latest/dg/cw-events.html} */ interface StepFunctionDetail { executionArn: string; stateMachineArn: string; name: string; status: "SUCCEEDED" | "RUNNING" | "FAILED" | "TIMED_OUT" | "ABORTED"; startDate: number; stopDate: number | null; input: string; inputDetails: { included: boolean; }; output: null | string; outputDetails: null | { included: boolean; }; } export interface StepFunctionStatusChangedEvent extends Event< StepFunctionDetail, "Step Functions Execution Status Change", "aws.states" > {} interface StepFunctionEventBusTargetProps extends Omit<aws_events_targets.SfnStateMachineProps, "input"> {} abstract class BaseStepFunction< Payload extends Record<string, any> | undefined, CallIn, CallOut > implements Integration< "StepFunction", (input: CallIn) => CallOut, EventBusTargetIntegration< Payload, StepFunctionEventBusTargetProps | undefined > > { readonly kind = "StepFunction"; readonly functionlessKind = "StepFunction"; readonly appSyncVtl: AppSyncVtlIntegration; // @ts-ignore readonly __functionBrand: (arg: CallIn) => CallOut; constructor(readonly resource: aws_stepfunctions.StateMachine) { // Integration object for appsync vtl this.appSyncVtl = this.appSyncIntegration({ request: (call, context) => { const { name, input, traceHeader } = retrieveMachineArgs(call); const inputObj = context.var("{}"); input && context.put( inputObj, context.str("input"), `$util.toJson(${context.eval(input)})` ); name && context.put(inputObj, context.str("name"), context.eval(name)); traceHeader && context.put( inputObj, context.str("traceHeader"), context.eval(traceHeader) ); context.put( inputObj, context.str("stateMachineArn"), context.str(resource.stateMachineArn) ); return `{ "version": "2018-05-29", "method": "POST", "resourcePath": "/", "params": { "headers": { "content-type": "application/x-amz-json-1.0", "x-amz-target": "${ this.resource.stateMachineType === aws_stepfunctions.StateMachineType.EXPRESS ? "AWSStepFunctions.StartSyncExecution" : "AWSStepFunctions.StartExecution" }" }, "body": $util.toJson(${inputObj}) } }`; }, }); } public appSyncIntegration( integration: Pick<AppSyncVtlIntegration, "request"> ): AppSyncVtlIntegration { return { ...integration, dataSourceId: () => this.resource.node.addr, dataSource: (api, dataSourceId) => { const ds = new appsync.HttpDataSource(api, dataSourceId, { api, endpoint: `https://${ this.resource.stateMachineType === aws_stepfunctions.StateMachineType.EXPRESS ? "sync-states" : "states" }.${this.resource.stack.region}.amazonaws.com/`, authorizationConfig: { signingRegion: api.stack.region, signingServiceName: "states", }, }); this.resource.grantRead(ds.grantPrincipal); if ( this.resource.stateMachineType === aws_stepfunctions.StateMachineType.EXPRESS ) { this.resource.grantStartSyncExecution(ds.grantPrincipal); } else { this.resource.grantStartExecution(ds.grantPrincipal); } return ds; }, result: (resultVariable) => { const returnValName = "$sfn__result"; if ( this.resource.stateMachineType === aws_stepfunctions.StateMachineType.EXPRESS ) { return { returnVariable: returnValName, template: `#if(${resultVariable}.statusCode == 200) #set(${returnValName} = $util.parseJson(${resultVariable}.body)) #if(${returnValName}.output == 'null') $util.qr(${returnValName}.put("output", $null)) #else #set(${returnValName}.output = $util.parseJson(${returnValName}.output)) #end #else $util.error(${resultVariable}.body, "${resultVariable}.statusCode") #end`, }; } else { return { returnVariable: returnValName, template: `#if(${resultVariable}.statusCode == 200) #set(${returnValName} = $util.parseJson(${resultVariable}.body)) #else $util.error(${resultVariable}.body, "${resultVariable}.statusCode") #end`, }; } }, }; } public asl(call: CallExpr, context: ASL) { this.resource.grantStartExecution(context.role); if ( this.resource.stateMachineType === aws_stepfunctions.StateMachineType.EXPRESS ) { this.resource.grantStartSyncExecution(context.role); } const { name, input, traceHeader } = retrieveMachineArgs(call); return { Type: "Task" as const, Resource: `arn:aws:states:::aws-sdk:sfn:${ this.resource.stateMachineType === aws_stepfunctions.StateMachineType.EXPRESS ? "startSyncExecution" : "startExecution" }`, Parameters: { StateMachineArn: this.resource.stateMachineArn, ...(input ? ASL.toJsonAssignment("Input", input) : {}), ...(name ? ASL.toJsonAssignment("Name", name) : {}), ...(traceHeader ? ASL.toJsonAssignment("TraceHeader", traceHeader) : {}), }, }; } public readonly eventBus = makeEventBusIntegration< Payload, StepFunctionEventBusTargetProps | undefined >({ target: (props, targetInput) => { return new aws_events_targets.SfnStateMachine(this.resource, { ...props, input: targetInput, }); }, }); private statusChangeEventDocument() { return { doc: { source: { value: "aws.states" }, "detail-type": { value: "Step Functions Execution Status Change" }, detail: { doc: { stateMachineArn: { value: this.resource.stateMachineArn }, }, }, }, }; } public onSucceeded( scope: Construct, id: string ): Rule<StepFunctionStatusChangedEvent> { const bus = EventBus.default<StepFunctionStatusChangedEvent>(this.resource); return new PredicateRuleBase( scope, id, bus, this.statusChangeEventDocument(), { doc: { detail: { doc: { status: { value: "SUCCEEDED" }, }, }, }, } ); } public onFailed( scope: Construct, id: string ): Rule<StepFunctionStatusChangedEvent> { const bus = EventBus.default<StepFunctionStatusChangedEvent>(this.resource); return new PredicateRuleBase<StepFunctionStatusChangedEvent>( scope, id, bus, this.statusChangeEventDocument(), { doc: { detail: { doc: { status: { value: "FAILED" }, }, }, }, } ); } public onStarted( scope: Construct, id: string ): Rule<StepFunctionStatusChangedEvent> { const bus = EventBus.default<StepFunctionStatusChangedEvent>(this.resource); return new PredicateRuleBase<StepFunctionStatusChangedEvent>( scope, id, bus, this.statusChangeEventDocument(), { doc: { detail: { doc: { status: { value: "RUNNING" }, }, }, }, } ); } public onTimedOut( scope: Construct, id: string ): Rule<StepFunctionStatusChangedEvent> { const bus = EventBus.default<StepFunctionStatusChangedEvent>(this.resource); return new PredicateRuleBase( scope, id, bus, this.statusChangeEventDocument(), { doc: { detail: { doc: { status: { value: "TIMED_OUT" }, }, }, }, } ); } public onAborted( scope: Construct, id: string ): Rule<StepFunctionStatusChangedEvent> { const bus = EventBus.default<StepFunctionStatusChangedEvent>(this.resource); return new PredicateRuleBase<StepFunctionStatusChangedEvent>( scope, id, bus, this.statusChangeEventDocument(), { doc: { detail: { doc: { status: { value: "ABORTED" }, }, }, }, } ); } /** * Create event bus rule that matches any status change on this machine. */ public onStatusChanged( scope: Construct, id: string ): Rule<StepFunctionStatusChangedEvent> { const bus = EventBus.default<StepFunctionStatusChangedEvent>(this.resource); // We are not able to use the nice "when" function here because we don't compile return new PredicateRuleBase<StepFunctionStatusChangedEvent>( scope, id, bus, this.statusChangeEventDocument() ); } } function retrieveMachineArgs(call: CallExpr) { // object reference // machine(inputObj) => inputObj: { name: "hi", input: ... } // Inline Object // machine({ input: { ... } }) // Inline with reference // machine({ input: ref, name: "hi", traceHeader: "hi" }) const arg = call.args[0]; if (!arg.expr || !isObjectLiteralExpr(arg.expr)) { throw Error( "Step function invocation must use a single, inline object parameter. Variable references are not supported currently." ); } else if ( arg.expr.properties.some( (x) => isSpreadAssignExpr(x) || isComputedPropertyNameExpr(x.name) ) ) { throw Error( "Step function invocation must use a single, inline object instantiated without computed or spread keys." ); } // we know the keys cannot be computed, so it is safe to use getProperty return { name: arg.expr.getProperty("name")?.expr, traceHeader: arg.expr.getProperty("traceHeader")?.expr, input: arg.expr.getProperty("input")?.expr, }; } export interface StepFunctionProps extends Omit< aws_stepfunctions.StateMachineProps, "definition" | "stateMachineType" > {} /** * An {@link ExpressStepFunction} is a callable Function which executes on the managed * AWS Step Function infrastructure. Like a Lambda Function, it runs within memory of * a single machine, except unlike Lambda, the entire environment is managed and operated * by AWS. Meaning, there is no Operating System, Memory, CPU, Credentials or API Clients * to manage. The entire workflow is configured at build-time via the Amazon State Language (ASL). * * With Functionless, the ASL is derived from type-safe TypeScript code instead of JSON. * * ```ts * import * as f from "functionless"; * * const table = new f.Table(this, "Table", { ... }); * * const getItem = new ExpressStepFunction(this, "F", () => { * return f.$AWS.DynamoDB.GetItem({ * TableName: table, * Key: { * .. * } * }); * }); * ``` */ export interface IExpressStepFunction< Payload extends Record<string, any> | undefined, Out > { (input: StepFunctionRequest<Payload>): SyncExecutionResult<Out>; } class BaseExpressStepFunction< Payload extends Record<string, any> | undefined, Out > extends BaseStepFunction< Payload, StepFunctionRequest<Payload>, SyncExecutionResult<Out> > implements IExpressStepFunction<Payload, Out> { /** * This static property identifies this class as an ExpressStepFunction to the TypeScript plugin. */ public static readonly FunctionlessType = "ExpressStepFunction"; readonly native: NativeIntegration< (input: StepFunctionRequest<Payload>) => SyncExecutionResult<Out> >; constructor(machine: aws_stepfunctions.StateMachine) { super(machine); const stateMachineArn = this.resource.stateMachineArn; this.native = { bind: (context) => { this.resource.grantStartSyncExecution(context.resource); }, preWarm(preWarmContext) { preWarmContext.getOrInit(PrewarmClients.STEP_FUNCTIONS); }, call: async (args, prewarmContext) => { const stepFunctionsClient = prewarmContext.getOrInit<StepFunctions>( PrewarmClients.STEP_FUNCTIONS ); const [payload] = args; const result = await stepFunctionsClient .startSyncExecution({ ...payload, stateMachineArn: stateMachineArn, input: payload.input ? JSON.stringify(payload.input) : undefined, }) .promise(); return result.error ? ({ ...result, error: result.error, status: result.status as "FAILED" | "TIMED_OUT", startDate: result.startDate.getUTCMilliseconds(), stopDate: result.stopDate.getUTCMilliseconds(), } as SyncExecutionFailedResult) : ({ ...result, startDate: result.startDate.getUTCMilliseconds(), stopDate: result.stopDate.getUTCMilliseconds(), output: result.output ? JSON.parse(result.output) : undefined, } as SyncExecutionSuccessResult<Out>); }, }; } } interface BaseExpressStepFunction< Payload extends Record<string, any> | undefined, Out > { (input: StepFunctionRequest<Payload>): SyncExecutionResult<Out>; } /** * An {@link ExpressStepFunction} is a callable Function which executes on the managed * AWS Step Function infrastructure. Like a Lambda Function, it runs within memory of * a single machine, except unlike Lambda, the entire environment is managed and operated * by AWS. Meaning, there is no Operating System, Memory, CPU, Credentials or API Clients * to manage. The entire workflow is configured at build-time via the Amazon State Language (ASL). * * With Functionless, the ASL is derived from type-safe TypeScript code instead of JSON. * * ```ts * import * as f from "functionless"; * * const table = new f.Table(this, "Table", { ... }); * * const getItem = new ExpressStepFunction(this, "F", () => { * return f.$AWS.DynamoDB.GetItem({ * TableName: table, * Key: { * .. * } * }); * }); * ``` */ export class ExpressStepFunction< Payload extends Record<string, any> | undefined, Out > extends BaseExpressStepFunction<Payload, Out> { readonly definition: StateMachine<States>; // Integration object for api gateway vtl readonly apiGWVtl: ApiGatewayVtlIntegration = { renderRequest: (call, context) => { const args = retrieveMachineArgs(call); return `{\n"stateMachineArn":"${ this.resource.stateMachineArn }",\n${Object.entries(args) .filter( (arg): arg is [typeof arg[0], Exclude<typeof arg[1], undefined>] => arg[1] !== undefined ) .map(([argName, argVal]) => { if (argName === "input") { // stringify the JSON input const input = context.exprToJson(argVal).replace(/"/g, '\\"'); return `"${argName}":"${input}"`; } else { return `"${argName}":${context.exprToJson(argVal)}`; } }) .join(",")}\n}`; }, createIntegration: (options) => { const credentialsRole = options.credentialsRole; this.resource.grantRead(credentialsRole); this.resource.grantStartSyncExecution(credentialsRole); return new aws_apigateway.AwsIntegration({ service: "states", action: "StartSyncExecution", integrationHttpMethod: "POST", options: { ...options, credentialsRole, passthroughBehavior: aws_apigateway.PassthroughBehavior.NEVER, }, }); }, }; /** * Wrap a {@link aws_stepfunctions.StateMachine} with Functionless. * * A wrapped {@link StepFunction} provides common integrations like execute (`machine()`) and `describeExecution`. * * {@link ExpressStepFunction} should only be used to wrap a Express Step Function. * Express Step Functions should use {@link StepFunction}. * * ```ts * ExpressStepFunction.fromStateMachine(new aws_stepfunctions.StateMachine(this, "F", { * stateMachineType: aws_stepfunctions.StateMachineType.EXPRESS, * ... * })); * ``` */ public static fromStateMachine< Payload extends Record<string, any> | undefined, Out >( machine: aws_stepfunctions.StateMachine ): IExpressStepFunction<Payload, Out> { return new ImportedExpressStepFunction<Payload, Out>(machine); } constructor( scope: Construct, id: string, props: StepFunctionProps, func: (arg: Payload) => Out ); constructor(scope: Construct, id: string, func: (arg: Payload) => Out); constructor( scope: Construct, id: string, ...args: | [props: StepFunctionProps, func: (arg: Payload) => Out] | [func: (arg: Payload) => Out] ) { const [props, func] = getStepFunctionArgs(...args); const [definition, machine] = synthesizeStateMachine(scope, id, func, { ...props, stateMachineType: aws_stepfunctions.StateMachineType.EXPRESS, }); super(machine); this.definition = definition; } } class ImportedExpressStepFunction< Payload extends Record<string, any> | undefined, Out > extends BaseExpressStepFunction<Payload, Out> { constructor(machine: aws_stepfunctions.StateMachine) { if ( machine.stateMachineType !== aws_stepfunctions.StateMachineType.EXPRESS ) { throw new SynthError(ErrorCodes.Incorrect_StateMachine_Import_Type); } super(machine); } } interface BaseSyncExecutionResult { billingDetails?: { billedDurationInMilliseconds: number; billedMemoryUsedInMB: number; }; executionArn: string; input: string; inputDetails: { included: boolean; }; name: string; outputDetails: { included: boolean; }; startDate: number; stateMachineArn: string; status: "SUCCEEDED" | "FAILED" | "TIMED_OUT"; stopDate: number; traceHeader: string; } export interface SyncExecutionFailedResult extends BaseSyncExecutionResult { cause: string; error: string; status: "FAILED" | "TIMED_OUT"; } export interface SyncExecutionSuccessResult<T> extends BaseSyncExecutionResult { output: T; status: "SUCCEEDED"; } export type SyncExecutionResult<T> = | SyncExecutionFailedResult | SyncExecutionSuccessResult<T>; // do not support undefined values, arguments must be present or missing export type StepFunctionRequest<P extends Record<string, any> | undefined> = (P extends undefined ? { input?: P } : { input: P }) & ( | { name: string; traceHeader: string; } | { name: string; } | { traceHeader: string; } | {} ); export interface ExpressStepFunction< Payload extends Record<string, any> | undefined, Out > { (input: StepFunctionRequest<Payload>): SyncExecutionResult<Out>; } /** * A {@link StepFunction} is a callable Function which executes on the managed * AWS Step Function infrastructure. Like a Lambda Function, it runs within memory of * a single machine, except unlike Lambda, the entire environment is managed and operated * by AWS. Meaning, there is no Operating System, Memory, CPU, Credentials or API Clients * to manage. The entire workflow is configured at build-time via the Amazon State Language (ASL). * * With Functionless, the ASL is derived from type-safe TypeScript code instead of JSON. * * ```ts * import * as f from "functionless"; * * const table = new f.Table(this, "Table", { ... }); * * const getItem = new StepFunction(this, "F", () => { * return f.$AWS.DynamoDB.GetItem({ * TableName: table, * Key: { * .. * } * }); * }); * ``` * * @typeParam Payload - the object payload to the step function. * @typeParam Out - the type of object the step function outputs. * currently not used: https://github.com/functionless/functionless/issues/129 */ export interface IStepFunction< Payload extends Record<string, any> | undefined, _Out > extends Integration< "StepFunction", ( input: StepFunctionRequest<Payload> ) => AWS.StepFunctions.StartExecutionOutput, EventBusTargetIntegration< Payload, StepFunctionEventBusTargetProps | undefined > > { describeExecution: IntegrationCall< "StepFunction.describeExecution", (executionArn: string) => AWS.StepFunctions.DescribeExecutionOutput >; (input: StepFunctionRequest<Payload>): AWS.StepFunctions.StartExecutionOutput; } class BaseStandardStepFunction< Payload extends Record<string, any> | undefined, Out > extends BaseStepFunction< Payload, StepFunctionRequest<Payload>, AWS.StepFunctions.StartExecutionOutput > implements IStepFunction<Payload, Out> { /** * This static property identifies this class as an StepFunction to the TypeScript plugin. */ public static readonly FunctionlessType = "StepFunction"; readonly native: NativeIntegration< ( input: StepFunctionRequest<Payload> ) => AWS.StepFunctions.StartExecutionOutput >; constructor(resource: aws_stepfunctions.StateMachine) { super(resource); const stateMachineArn = this.resource.stateMachineArn; this.native = { bind: (context) => { this.resource.grantStartExecution(context.resource); }, preWarm(preWarmContext) { preWarmContext.getOrInit(PrewarmClients.STEP_FUNCTIONS); }, call: async (args, prewarmContext) => { const stepFunctionsClient = prewarmContext.getOrInit<StepFunctions>( PrewarmClients.STEP_FUNCTIONS ); const [payload] = args; const result = await stepFunctionsClient .startExecution({ ...payload, stateMachineArn: stateMachineArn, input: payload.input ? JSON.stringify(payload.input) : undefined, }) .promise(); return result; }, }; } public describeExecution = makeIntegration< "StepFunction.describeExecution", (executionArn: string) => AWS.StepFunctions.DescribeExecutionOutput >({ kind: "StepFunction.describeExecution", appSyncVtl: this.appSyncIntegration({ request(call, context) { const executionArn = getArgs(call); return `{ "version": "2018-05-29", "method": "POST", "resourcePath": "/", "params": { "headers": { "content-type": "application/x-amz-json-1.0", "x-amz-target": "AWSStepFunctions.DescribeExecution" }, "body": { "executionArn": ${context.json(context.eval(executionArn))} } } }`; }, }), asl: (call, context) => { // need DescribeExecution this.resource.grantRead(context.role); const executionArnExpr = assertDefined( call.args[0].expr, "Describe Execution requires a single string argument." ); const argValue = ASL.toJsonAssignment("ExecutionArn", executionArnExpr); const task: Task = { Type: "Task", Resource: "arn:aws:states:::aws-sdk:sfn:describeExecution", Parameters: argValue, }; return task; }, native: { bind: (context) => this.resource.grantRead(context.resource), preWarm(prewarmContext) { prewarmContext.getOrInit(PrewarmClients.STEP_FUNCTIONS); }, call: async (args, prewarmContext) => { const stepFunctionClient = prewarmContext.getOrInit<StepFunctions>( PrewarmClients.STEP_FUNCTIONS ); const [arn] = args; const result = await stepFunctionClient .describeExecution({ executionArn: arn, }) .promise(); return result; }, }, unhandledContext: (kind, contextKind) => { throw new Error( `${kind} is only available in the ${ASL.ContextName} and ${VTL.ContextName} context, but was used in ${contextKind}.` ); }, }); } interface BaseStandardStepFunction< Payload extends Record<string, any> | undefined, Out > { (input: StepFunctionRequest<Payload>): AWS.StepFunctions.StartExecutionOutput; } /** * A {@link StepFunction} is a callable Function which executes on the managed * AWS Step Function infrastructure. Like a Lambda Function, it runs within memory of * a single machine, except unlike Lambda, the entire environment is managed and operated * by AWS. Meaning, there is no Operating System, Memory, CPU, Credentials or API Clients * to manage. The entire workflow is configured at build-time via the Amazon State Language (ASL). * * With Functionless, the ASL is derived from type-safe TypeScript code instead of JSON. * * ```ts * import * as f from "functionless"; * * const table = new f.Table(this, "Table", { ... }); * * const getItem = new StepFunction(this, "F", () => { * return f.$AWS.DynamoDB.GetItem({ * TableName: table, * Key: { * .. * } * }); * }); * ``` * * @typeParam Payload - the object payload to the step function. * @typeParam Out - the type of object the step function outputs. * currently not used: https://github.com/functionless/functionless/issues/129 */ export class StepFunction<Payload extends Record<string, any> | undefined, Out> extends BaseStandardStepFunction<Payload, Out> implements IStepFunction<Payload, Out> { readonly definition: StateMachine<States>; /** * Wrap a {@link aws_stepfunctions.StateMachine} with Functionless. * * A wrapped {@link StepFunction} provides common integrations like execute (`machine()`) and `describeExecution`. * * {@link StepFunction} should only be used to wrap a Standard Step Function. * Express Step Functions should use {@link ExpressStepFunction}. * * ```ts * StepFunction.fromStateMachine(new aws_stepfunctions.StateMachine(this, "F", { * ... * })); * ``` */ public static fromStateMachine< Payload extends Record<string, any> | undefined, Out >(machine: aws_stepfunctions.StateMachine): IStepFunction<Payload, Out> { return new ImportedStepFunction<Payload, Out>(machine); } constructor( scope: Construct, id: string, props: StepFunctionProps, func: (arg: Payload) => Out ); constructor(scope: Construct, id: string, func: (arg: Payload) => Out); constructor( scope: Construct, id: string, ...args: | [props: StepFunctionProps, func: (arg: Payload) => Out] | [func: (arg: Payload) => Out] ) { const [props, func] = getStepFunctionArgs(...args); const [definition, machine] = synthesizeStateMachine(scope, id, func, { ...props, stateMachineType: aws_stepfunctions.StateMachineType.STANDARD, }); super(machine); this.definition = definition; } } function getStepFunctionArgs< Payload extends Record<string, any> | undefined, Out >( ...args: | [props: StepFunctionProps, func: (arg: Payload) => Out] | [func: (arg: Payload) => Out] ) { const props = isFunctionDecl(args[0]) || isErr(args[0]) ? {} : (args[1] as StepFunctionProps); const func = validateFunctionDecl( args.length > 1 ? args[1] : args[0], "StepFunction" ); return [props, func] as const; } function synthesizeStateMachine( scope: Construct, id: string, decl: FunctionDecl, props: StepFunctionProps & { stateMachineType: aws_stepfunctions.StateMachineType; } ): [StateMachine<States>, aws_stepfunctions.StateMachine] { const machine = new aws_stepfunctions.StateMachine(scope, id, { ...props, definition: new aws_stepfunctions.Pass(scope, "dummy"), }); const definition = new ASL(scope, machine.role, decl).definition; const resource = machine.node.findChild( "Resource" ) as aws_stepfunctions.CfnStateMachine; resource.definitionString = Stack.of(resource).toJsonString(definition); // remove the dummy pass node because we don't need it. scope.node.tryRemoveChild("dummy"); return [definition, machine]; } class ImportedStepFunction< Payload extends Record<string, any> | undefined, Out > extends BaseStandardStepFunction<Payload, Out> { constructor(machine: aws_stepfunctions.StateMachine) { if ( machine.stateMachineType !== aws_stepfunctions.StateMachineType.STANDARD ) { throw new SynthError(ErrorCodes.Incorrect_StateMachine_Import_Type); } super(machine); } } function getArgs(call: CallExpr) { const executionArn = call.args[0]?.expr; if (executionArn === undefined) { throw new Error("missing argument 'executionArn'"); } return executionArn; }
the_stack
import * as _ from 'lodash'; import { AfterViewInit, Component, ElementRef, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core'; import { ScrollLoadingGridModel } from './scroll-loading-grid.model'; import { GridOption, Option } from '@common/component/grid/grid.option'; import { Header, SlickGridHeader } from '@common/component/grid/grid.header'; declare const jQuery_1_7; declare const Slick: any; @Component({ selector: '[scroll-grid-component]', template: `<div class="myGrid"></div>`, styleUrls: [ '../../../../../../../assets/grid/slick.grid.css', // slickGrid default css '../../../../../../../assets/grid/slick.columnpicker.css', // columnpicker plugin css '../../../../../../../assets/grid/slick.grid.override.css', // slickGrid custom css '../../../../../../../assets/grid/slick.headerbuttons.css', // slickGrid header button css '../../../../../../../assets/grid/slick.headermenu.css' // slickGrid header button css ] }) export class ScrollLoadingGridComponent implements OnInit, AfterViewInit, OnDestroy { public static readonly ID_PROPERTY: string = '_idProperty_'; // 아이디 /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ private $ = jQuery_1_7; // Fixed jQuery version 1.7 private _selectColumnIds: string[] = []; // 선택된 컬럼의 아이디 목록 저장 private _gridSelectionModelType: string = ''; // 선택 모델 형식 private _clickEnabled: boolean = true; // 클릭 이벤트 타임아웃 체크 private _columnResized: boolean = false; // 컬럼 리사이징 여부 private _loadingIndicator: any; private _grid; private _option: Option; // 그리드 옵션 private _gridModel: ScrollLoadingGridModel; // 데이터 모델 private readonly _GRID_ID: string; // 그리드 아이디 private readonly _GRID_DEFAULT_OPTION: Option; // 그리드 기본 옵션 private readonly _ROW_EMPTY: number = -1; // 로우 데이터가 없는 경우 -1 private _selectedRows: any = []; // 그리드에서 선택된 로우 리스트 /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Output() private selectedHeaderEvent = new EventEmitter(); // 헤더 선택시 알림 @Output() private selectedEvent = new EventEmitter(); // 로우 선택시 알림 @Output() private onColumnResize = new EventEmitter(); // 컬럼 크기 조정시 이벤트 @Output() private onContextMenuClick = new EventEmitter(); @Output() private onHeaderRowCellRendered = new EventEmitter(); @Output() private onGridContextCloseEvent = new EventEmitter(); // 그리드 context menu close public totalRowCnt: number = 0; private _currentScrollLeft: number = 0; // grid current scrollLeft value private _gridTimer = null; // grid timer /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(public elementRef: ElementRef) { this._GRID_ID = this._createGridUniqueId(); // 그리드 유니크 아이디 생성 // 그리드 기본 옵션 this._GRID_DEFAULT_OPTION = new GridOption() .SyncColumnCellResize(true) .MultiColumnSort(false) .build(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 컴포넌트 초기 실행 */ public ngOnInit() { } /** * 화면 초기화 */ public ngAfterViewInit() { this.elementRef.nativeElement.children[0].id = this._GRID_ID; } /** * 컴포넌트 제거 */ public ngOnDestroy() { } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public getPageInfo(): any { return this._gridModel.getPageInfo(); } public setExternalData(data:any, currentPage:number): void { this._gridModel.setExternalData(data, currentPage); } public searchProcessReset(): void { this._gridModel.searchProcessReset(); } /** * 그리드 생성 * @param {header[]} headers * @param {ScrollLoadingGridModel} gridModel * @param {Option} option * @param {number} ruleIdx * @param {number} totalRowCnt */ public create(headers: Header[], gridModel: ScrollLoadingGridModel, option: Option = null, ruleIdx: number, totalRowCnt: number) { // 기존 그리드 삭제 this.destroy(); // Header 검사 if (0 === headers.length) { throw new TypeError('Invalid header value.'); } // 옵션 검사 if (!(null === option)) { this._option = JSON.stringify(option) === '{}' ? this._GRID_DEFAULT_OPTION : option; } else { this._option = this._GRID_DEFAULT_OPTION; } // DualSelectionActivate 옵션 활성화시 // 헤더 목록 처음에 아이디 프로퍼트 컬럼의 헤더 데이터 추가 if (this._option.dualSelectionActivate) { headers.unshift(new SlickGridHeader() .Id(ScrollLoadingGridComponent.ID_PROPERTY) .Name(!this._option.enableSeqSort ? '' : 'SEQ') .Field(ScrollLoadingGridComponent.ID_PROPERTY) .Behavior('select') .CssClass(`dual_selection${ScrollLoadingGridComponent.ID_PROPERTY}`) .CssClass('txt-center') .Width(this._option.enableSeqSort ? 60 : 0) .CannotTriggerInsert(true) .Resizable(true) .Unselectable(true) .Sortable(this._option.enableSeqSort) .Formatter((_row, _cell, value, columnDef) => { if (this._option.enableHeaderClick && columnDef.id === ScrollLoadingGridComponent.ID_PROPERTY) { return '<div style=\'line-height:30px;\'>' + '&middot;' + '</div>'; } else { return value } }) .build() ); } // 그리드 모델 정의 this._gridModel = gridModel; // this._gridModel. // 데이터 전체 카운트 & ruleIdx if(this._gridModel) { this._gridModel.setTotalRowCnt(totalRowCnt); this._gridModel.setRuleIndex(ruleIdx); } // 그리드 생성 this._grid = this._generateGrid(headers, gridModel); // horizontal_scroll_in_histogram_area const naviAgent: string = navigator.userAgent.toLowerCase(); let ieBrowser: boolean = false; if(naviAgent.indexOf('msie') > 0 || naviAgent.indexOf('trident/') > 0 || naviAgent.indexOf('edge/') > 0) { ieBrowser = true; } if(ieBrowser === false){ $('.slick-headerrow').css('overflow-x','auto'); $('.slick-header').css('overflow-x','auto'); } // horizontal_scroll_in_histogram_area // 그리드 이벤트 연결 this._bindEvent(this._grid, gridModel); } // function - grid /** * 그리드 코어 오브젝트 반환 */ public getGridCore() { return this._grid; } // function - getGridCore /** * 그리드의 jQuery Object 반환 * @returns {JQuery} */ public getGridJQueryObject() { return $(`#${this._GRID_ID}`); } // function - getGridJQueryObject /** * 그리드 실행 */ public execGrid() { this._grid.init(); } // function - execGrid /** * 그리드 제거 함수 */ public destroy() { if (this._grid) { this._grid.invalidate(); this._grid.destroy(); } this._grid = null; this._option = null; this._gridModel = null; } // function - destroy /** * 검색 * @param {string} searchText */ public search(searchText: string = '') { try { this._gridModel.search(searchText); } catch (e) { // 오류 로그 출력 console.error(e); } } // function - search // ------------------------------------------------------------------------------------------------------------------- // 레아아웃 관련 // ------------------------------------------------------------------------------------------------------------------- // noinspection JSUnusedGlobalSymbols /** * 그리드 리사이징 * - 윈도우 리사이징은 이벤트가 걸려 있지만, 그리드 엘리먼트의 크기를 변경해서 그리드 컴포넌트의 크기가 변경 되는 경우에는 resize() 함수를 통해서 * resizeCanvas() 를 호출해야한다 * @param scope */ public resize(scope: any = null): void { const fnScope: any = scope ? scope : this; // 그리드 resizeCanvas() 호출 fnScope._grid.resizeCanvas(); } // ------------------------------------------------------------------------------------------------------------------- // 선택 관련 // ------------------------------------------------------------------------------------------------------------------- // noinspection JSUnusedGlobalSymbols /** * 데이터뷰에서 선택된 로우 데이터 전체 목록 * @param scope * @returns {any[]} */ public getSelectedRows(scope: any = null): any[] { const fnScope: any = scope === null ? this : scope; // let rows: any[] = // fnScope._grid.getSelectedRows() // .map(rowIndex => fnScope.dataView.getItem(rowIndex)); const rows: any[] = fnScope._grid.getSelectedRows().map(rowIndex => fnScope._gridModel.data[rowIndex]); return _.cloneDeep(rows); } // function - getSelectedRows // noinspection JSUnusedGlobalSymbols /** * * 컬럼 선택 * @param {string} id -- UUID * @param {boolean|string} isSelectOrToggle * @param {string} type 컬럼 타입 * @param {{ isShiftKeyPressed?: boolean, isCtrlKeyPressed?: boolean, batchCount:number }} opts 부가정보 */ public selectColumn(id: string, isSelectOrToggle: boolean | string, type?: string, opts?: { isShiftKeyPressed?: boolean, isCtrlKeyPressed?: boolean, batchCount?:number }): void { (opts) || (opts = {}); // get column index with column id const columnIdx = this._grid.getColumnIndex(id); let isSelect: boolean; if ('string' === typeof isSelectOrToggle && 'TOGGLE' === isSelectOrToggle) { isSelect = (0 === this._selectColumnIds.filter(item => item === id).length); } else { isSelect = isSelectOrToggle as boolean; } // 선택 컬럼 목록 변경 this._selectColumnIds = this._selectColumnIds.filter(item => item !== id); (isSelect) && (this._selectColumnIds.push(id)); // 이벤트 발생 (this._grid.getColumns()[columnIdx]) && (this._grid.getColumns()[columnIdx]['select'] = isSelect); const selectedColumnData = { id: id, isSelect: isSelect, selectColumnIds: this._selectColumnIds, shiftKey: opts.isShiftKeyPressed, ctrlKey: opts.isCtrlKeyPressed, batchCount: opts.batchCount }; (type) && (selectedColumnData['type'] = type); // 타입이 있을때만 같이 보냄 this.selectedHeaderEvent.emit(selectedColumnData); // 스타일 업데이트 this._grid.invalidate(); this._grid.render(); } // function - selectColumn // noinspection JSUnusedGlobalSymbols /** * 컬럼 전체 선택 */ public columnAllSelection(): void { const cntTotalCols:number = this._grid.getColumns().length; this._grid.getColumns().forEach(item => this.selectColumn(item.id, true, null, { batchCount : cntTotalCols } )); } // function - columnAllSelection // noinspection JSUnusedGlobalSymbols /** * 컬럼 전체 선택 해제 */ public columnAllUnSelection(): void { const cntTotalCols:number = this._grid.getColumns().length; this._grid.getColumns().forEach(item => this.selectColumn(item.id, false, null, { batchCount : cntTotalCols } )); } // function - columnAllUnSelection // noinspection JSUnusedGlobalSymbols /** * 컬럼 선택 * @param {string} id */ public columnSelection(id: string): void { this.selectColumn(id, true); } // function - columnSelection // noinspection JSUnusedGlobalSymbols /** * 컬럼 선택 해제 * @param {string} id */ public columnUnSelection( id: string): void { this.selectColumn(id, false); } // function - columnUnSelection // noinspection JSUnusedGlobalSymbols /** * 컬럼 선택 변경 * @param {string} id */ public columnSelectionToggle(id: string): void { this.selectColumn(id, 'TOGGLE'); } // function - columnSelectionToggle // noinspection JSUnusedGlobalSymbols /** * 로우 전체 선택 * @param scope */ public rowAllSelection(scope: any = null): void { const fnScope: any = scope === null ? this : scope; const rRows: any[] = []; // 그리드에 보여지고 있는 로우의 숫자 // const gridRowLength = fnScope.dataView.getLength(); const gridRowLength = fnScope._gridModel.data.length; for (let index: number = 0; index < gridRowLength; index += 1) { rRows.push(index); } fnScope._grid.setSelectedRows(rRows); } // noinspection JSUnusedGlobalSymbols /** * 로우 선택 * @param index */ public rowSelection(index): void { // console.log('index', index); this._selectedRows = index; if (this._gridSelectionModelType === 'cell') { this.rowAllUnSelection(); } this._gridSelectionModelType = 'row'; this._grid.setSelectedRows(index); } // noinspection JSUnusedGlobalSymbols /** * 로우 전체 선택해제 * @param scope */ public rowAllUnSelection(scope: any = null): void { const fnScope: any = scope === null ? this : scope; fnScope._grid.setSelectedRows([]); this._selectedRows = []; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 그리드 생성 * @param {header[]} headers * @param {ScrollLoadingGridModel} gridModel * @private */ private _generateGrid(headers: Header[], gridModel: ScrollLoadingGridModel) { // 그리드 생성 const grid = new Slick.Grid(`#${this._GRID_ID}`, gridModel.data, headers, this._option); // 툴팁 플러그인 추가 const autoTooltips = new Slick.AutoTooltips({ enableForHeaderCells: true }); grid.registerPlugin(autoTooltips); // 자동 컬럼 리사이징 플러그인 추가 const autoSize = new Slick.AutoColumnSize(true); grid.registerPlugin(autoSize); // 컬럼 그룹화 플러그인 기능 활성화 if (true === this._option.columnGroup) { const plugin: any = new Slick.ColumnGroup(); grid.registerPlugin(plugin); } // 그리드 로우 선택 기능 활성화 grid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: false })); if (this._option.enableHeaderMenu) { // Header menu plugin const headerButtonsPlugin = new Slick.Plugins.HeaderButtons(); headerButtonsPlugin.onCommand.subscribe((e, args) => { const contextMenuParam = { columnName: args.button.command, index: args.button.index, left: e.pageX, top: e.pageY, columnType: args.button.type }; if (args.button.timestampStyle){ // only if column is timestamp type contextMenuParam['timestampStyle'] = args.button.timestampStyle; } this.onContextMenuClick.emit(contextMenuParam); grid.invalidate(); }); grid.registerPlugin(headerButtonsPlugin); } grid.getContainerNode().querySelector('.slick-header').addEventListener('scroll', (_event)=>{ if(grid.getContainerNode().querySelector('.slick-viewport').scrollLeft !== grid.getContainerNode().querySelector('.slick-header').scrollLeft) grid.getContainerNode().querySelector('.slick-viewport').scrollLeft = grid.getContainerNode().querySelector('.slick-header').scrollLeft; }); if (this.isCellExternalCopyManagerActivate()) { if (false === this._option.enableCellNavigation) { this._option.enableCellNavigation = true; } // 셀 드래그 옵션 초기화 this.initCellExternalCopyManager(grid); } else { // 그리드 로우 선택 기능 활성화 grid.setSelectionModel( new Slick.RowSelectionModel({ selectActiveRow: false }) ); } return grid; } // function - _generateGrid /** * Grid horizaltal scroll timer * @param {number} viewPortLeftPx * @private */ private fixGridScroll(viewPortLeftPx: number): void { if(this._gridTimer) {clearTimeout(this._gridTimer);} this._gridTimer = setTimeout(() => {this._currentScrollLeft = viewPortLeftPx;this._grid.invalidate();this._grid.render();}, 400); } /** * Grid onScroll 이벤트 발생 * @private */ private allContextMenuClose(): void { this.onGridContextCloseEvent.emit(); } /** * 그리드 이벤트 연결 * @param grid * @param {ScrollLoadingGridModel} gridModel * @private */ private _bindEvent(grid, gridModel: ScrollLoadingGridModel) { // 그리드 스크롤 이벤트 정의 grid.onViewportChanged.subscribe(() => { const viewPort = grid.getViewport(); gridModel.ensureData(viewPort.top, viewPort.bottom); const viewPortLeftPx: number = viewPort.leftPx; if(this._currentScrollLeft !== viewPortLeftPx) { this.fixGridScroll(viewPortLeftPx) } }); // 그리드 스크롤 이벤트 grid.onScroll.subscribe((_e: any, _args:any) => { this.allContextMenuClose(); }); // 로더 이벤트 정의 gridModel.onDataLoading.subscribe(() => { if (!this._loadingIndicator) { this._loadingIndicator = this.$('<span class=\'loading-indicator\'><label>Buffering...</label></span>').appendTo(document.body); const $grid = this.$(`#${this._GRID_ID}`); this._loadingIndicator .css('position', 'absolute') .css('top', $grid.position().top + $grid.height() / 2 - this._loadingIndicator.height() / 2) .css('left', $grid.position().left + $grid.width() / 2 - this._loadingIndicator.width() / 2); } this._loadingIndicator.show(); }); gridModel.onDataLoaded.subscribe((_e, args) => { // 데이터 업데이트 grid.setData(gridModel.data); if (0 === args.from) { grid.invalidate(); } else { for (let idx = args.from, nMax = args.to; idx <= nMax; idx++) { grid.invalidateRow(idx); } } grid.updateRowCount(); grid.render(); (this._loadingIndicator) && (this._loadingIndicator.fadeOut()); }); // load the first page grid.onViewportChanged.notify(); // 로더 이벤트 정의 - more complete gridModel.onMoreDataComplete.subscribe(() => { this.moreEventAfterSelectRow(); }); // ----------------------------------------------------------------------------------------------------------------- // onClick // - 클릭 이벤트 // ----------------------------------------------------------------------------------------------------------------- if (this._option.dualSelectionActivate) { grid.onClick.subscribe((event, args) => { if (!this._clickEnabled) { return; } setTimeout(() => this._clickEnabled = true, 300); this._clickEnabled = false; //noinspection JSValidateJSDoc /** * 1. 선택된 로우 데이터 * 2. 선택 여부 * 3. 이벤트 오브젝트 * 4. 에러 여부 * * @type {{row: any; selected: any; event: any; error: boolean}} */ const result = { event, row: null, selected: null, error: false }; try { // 로우 인덱스 값 const rowIndex: number = args.row; // 로우 인덱스로 로우 데이터 추출 // const row: any = scope.dataView.getItem(rowIndex); const row: any = this._gridModel.data[rowIndex]; // 로우 데이터가 없으면 if (row === this._ROW_EMPTY) { //noinspection ExceptionCaughtLocallyJS throw Error('Row is empty.'); } if (this._option.dualSelectionActivate) { if (args.cell === 0) { if (this._gridSelectionModelType === 'cell') { this._gridSelectionModelType = 'row'; // 전체 선택 해제 this.rowAllUnSelection(); } // 그리드 로우 선택 기능 활성화 this._initRowSelectionModel(this); if (this._option.enableMultiSelectionWithCtrlAndShift) { this._rowClickWithCtrlShiftOption(this, row, result, rowIndex); } else { this._onClickRowSelection(this, row, result, rowIndex); } } else { this._gridSelectionModelType = 'cell'; // 컬럼 전체 선택 해제 this.columnAllUnSelection(); // 전체 선택 해제 this.rowAllUnSelection(); this.initCellExternalCopyManager(this._grid); } } else { if (this._option.enableMultiSelectionWithCtrlAndShift) { this._rowClickWithCtrlShiftOption(this, row, result, rowIndex); } else { this._onClickRowSelection(this, row, result, rowIndex); } } result.row = row; this._grid.invalidate(); this._grid.render(); } catch (e) { // 에러 발생 여부 result.error = true; // 에러 정보 출력 console.error(e); } finally { // 클릭 이벤트 발생 this.selectedEvent.emit(result); } }); } // ----------------------------------------------------------------------------------------------------------------- // onHeaderClick // - 헤더 클릭 이벤트 // ----------------------------------------------------------------------------------------------------------------- if (this._option.enableHeaderClick) { grid.onHeaderClick.subscribe((event, args) => { if (this._columnResized) { this._columnResized = false; return; } // cell 이 선택되어있다면 reset if (this._gridSelectionModelType === 'cell') { // 전체 선택 해제 this.rowAllUnSelection(); this._initRowSelectionModel(this); } if (this._option.enableMultiSelectionWithCtrlAndShift && event.metaKey === false && event.ctrlKey === false && event.shiftKey === false) { this.columnAllUnSelection(); } // Seq header 선택 block if (args.column.name === '') { return; } if (args.column.columnType === 'MAP' || args.column.columnType === 'ARRAY') { this.selectColumn( args.column.id, 'TOGGLE', args.column.columnType, { isShiftKeyPressed: event.shiftKey, isCtrlKeyPressed: (event.metaKey || event.ctrlKey) } ); } else { this.selectColumn( args.column.id, 'TOGGLE', null, { isShiftKeyPressed: event.shiftKey, isCtrlKeyPressed: (event.metaKey || event.ctrlKey) } ); } this._columnResized = false; }); } // ----------------------------------------------------------------------------------------------------------------- // onHeaderRowCellRendered // - 헤더 아래 컬럼이 render 했을때 // ----------------------------------------------------------------------------------------------------------------- if (this._option.showHeaderRow) { if (this._option.headerRowHeight !== 25) { $('.slick-viewport').css('top', this._option.headerRowHeight + 30 + 'px'); } grid.onHeaderRowCellRendered.subscribe((_event, args) => { this.onHeaderRowCellRendered.emit(args); }); } // ----------------------------------------------------------------------------------------------------------------- // onHeaderRowCellRendered // - 헤더 아래 컬럼이 render 했을때 // ----------------------------------------------------------------------------------------------------------------- grid.onColumnsResized.subscribe(() => { for (let i = 0, totI = this._grid.getColumns().length; i < totI; i++) { const column = this._grid.getColumns()[i]; this._columnResized = true; // Check if column width has changed if (column.width !== column.previousWidth) { this.onColumnResize.emit({ idx: i, field : column.field,name: column.name, uuid : column.id, width: column.width }); setTimeout(() => { this._columnResized = false; }, 300); } } }); // ----------------------------------------------------------------------------------------------------------------- // 윈도우 리사이징에 대한 이벤트 처리 // ----------------------------------------------------------------------------------------------------------------- $(window).resize(() => { setTimeout(() => { if (typeof this._grid !== 'undefined') { this.resize(); } }, 500); }); } // function - _bindEvent /** * MORE 이벤트 > 로우 선택 표시 * @private */ private moreEventAfterSelectRow(): void { if(this._gridSelectionModelType !== 'row') return; this._grid.setSelectedRows(this._selectedRows); } /** * 클릭 이벤트 > 로우 선택 표시 * @param scope * @param row * @param {{event: any, row: any, selected: any, error: boolean}} result * @param {number} rowIndex * @private */ private _onClickRowSelection(scope: any, row: any, result: { event: any; row: any; selected: any; error: boolean }, rowIndex: number): void { const idProperty: string = ScrollLoadingGridComponent.ID_PROPERTY; result.selected = !(scope.getSelectedRows().some(selectedRow => selectedRow[idProperty] === row[idProperty])); if (result.selected) { if (scope._option.multiSelect === false) { scope._grid.setSelectedRows([rowIndex]); } else { const selectedRows: any[] = scope._grid.getSelectedRows(); selectedRows.push(rowIndex); scope._grid.setSelectedRows(selectedRows); } } else { let selectedRows: any[] = scope._grid.getSelectedRows(); selectedRows = selectedRows.filter(selectedRowIndex => String(selectedRowIndex) !== String(rowIndex)); scope._grid.setSelectedRows(selectedRows); } } // function - _onClickRowSelection /** * 클릭 이벤트 > 로우 선택 표시 * @param scope * @param row * @param {{event: any, row: any, selected: any, error: boolean}} result * @param {number} rowIndex * @private */ private _rowClickWithCtrlShiftOption(scope: any, row: any, result: { event: any; row: any; selected: any; error: boolean }, rowIndex: number): void { const idProperty: string = ScrollLoadingGridComponent.ID_PROPERTY; const selectedList: any[] = scope.getSelectedRows(); let currentSelected: boolean = false; if(selectedList==null || selectedList.length === 0) { result.selected = true; }else{ if(row.hasOwnProperty(idProperty)) { for(let i: number = 0, nMax = selectedList.length; i < nMax; i = i + 1) { if(selectedList[i] === undefined) continue; if(selectedList[i].hasOwnProperty(idProperty) === false) continue; if(selectedList[i][idProperty] === row[idProperty]) { currentSelected = true; break; } } } result.selected = !currentSelected; } const isDisableOptionKey: boolean = ( result.event.metaKey === false && result.event.ctrlKey === false && result.event.shiftKey === false ); let selectedRows: any[] = []; if (result.selected) { if (scope._option.multiSelect) { if (isDisableOptionKey) { selectedRows = scope._grid.getSelectedRows(); selectedRows.push(rowIndex); } } else { if (!isDisableOptionKey) { selectedRows = scope._grid.getSelectedRows(); } selectedRows.push(rowIndex); } scope._grid.setSelectedRows(selectedRows); } else { if (isDisableOptionKey) { if (scope._grid.getSelectedRows().indexOf(row[idProperty] - 1) > -1) { scope._grid.setSelectedRows([row[idProperty] - 1]); } } else { selectedRows = scope._grid.getSelectedRows().filter(selectedRowIndex => String(selectedRowIndex) !== String(rowIndex)); scope._grid.setSelectedRows(selectedRows); } } } // function - _rowClickWithCtrlShiftOption // noinspection JSMethodCanBeStatic /** * Row 선택 모델 초기화 * @param scope * @private */ private _initRowSelectionModel(scope) { scope._grid.setSelectionModel( new Slick.RowSelectionModel({ selectActiveRow: false }) ); } // function - _initRowSelectionModel /** * 그리드 유니크 아이디 생성 * @returns {string} * @private */ private _createGridUniqueId(): string { const date: Date = new Date(); const timestamp: string = date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate().toString(); return 'myGrid' + '_' + timestamp + '_' + this._generateUUID(); } // function - _createGridUniqueId /** * UUID 생성 * @returns {string} * @private */ private _generateUUID(): string { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const d = new Date().getTime(); const r = (d + Math.random() * 16) % 16 | 0; // d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); } // function - _generateUUID /** * 셀 드래그 옵션 초기화 * @param grid */ private initCellExternalCopyManager(grid): void { grid.setSelectionModel( new Slick.CellSelectionModel({ selectActiveRow: false }) ); const cellCopyManager = new Slick.CellExternalCopyManager(); cellCopyManager.init(grid); } /** * 셀 복사 붙여넣기 기능 활성화 여부 검사 * @returns {boolean} */ private isCellExternalCopyManagerActivate(): boolean { return true === this._option.cellExternalCopyManagerActivate; } }
the_stack
import { strict as assert } from "assert"; import got, { Response as GotResponse } from "got"; import { customGotRetryfunc, mtime, mtimeDiffSeconds, log } from "@opstrace/utils"; // High-level overview of what this module is adding on top of // jwt({ // secret: jwksRsa.expressJwtSecret({ // cache: true, // rateLimit: true, // jwksRequestsPerMinute: 5, // jwksUri: JWKS_URL, // }), // // - A custom JWKS HTTP endpoint fetch function using the got() HTTP client // with carefully chosen retrying parameters and logging // - A use-stale-item-if-refresh-failed technique for making the cache more // usefule and robust. // - A prepopulate-upon-app-start technique to make the first login more // robust and fast (minimize hot path impact) // This bypasses the cache mechanism in jwks-rksa / adds to it using the // assumption that public keys are practically never rotated. I don't think // that the cache built into jwks-rksa has the following important // functionality: if the cache is stale and fetching new data fails: instead of // erroring out the operation simply try to use the 'last known good key set', // even if that's technically 'outdated', based on the cache configuration. The // probability for that "stale" cache item to contain the correct public key is // practically 100 %. Another property that jwks-rsa does not provide is // 'prepopulation' before the first request, at least it's not clear how to do // that. let LAST_JWKS_POTENTIALLY_STALE: object; let LAST_JWKS_SET_TIME: bigint; let FIRST_JWKS_FROM_PREPOPULATE_CALL: object | undefined; // JWKS request-adjusted timeout constants. Paradigm: fail fast to allow // for a quick retry to potentially heal what went wrong (L4 round-robin // load balancing for example might result in a different network path // between attempts, we want to make use of that). const GOT_JWKS_HTTP_TIMEOUT_SETTINGS = { // Rely on this to be between data centers (not involving a // consumer-grade Internet conn). If a TCP connect() takes longer then // ~5 seconds then most certainly there is a networking issue. Use value // slightly larger than 3 s, initial TCP retransmit timeout. connect: 3400, // After TCP-connect, this controls the max time the TLS handshake is // allowed to take. secureConnect: 2000, // After TLS over TCP ist established, require the few request bytes to // (just a GET w/o body) to be written real quick. send: 1000, // After having written the request, expect response _headers_ to // arrive within that time (not the complete response). response: 2500, // global timeout, supposedly until final response byte arrived. request: 8500 }; // From the jwks-rsa docs: "Even if caching is enabled the library will call // the JWKS endpoint if the kid is not available in the cache, because a key // rotation could have taken place." // Future: ideally, never fetch this in the hot path unless it is known that // the required key ID is not in the cache. Trigger a refresh every now and // then in the hot path, but don't wait for the result. That however requires // an override for the case where `kid` is not in the current JWKS in that case // we have to get a fresh key set, to see if rotation just took place. // Choose high-level retrying parameters. Note(JP): remember that this retrying // machinery may be performed as part of processing an incoming HTTP request, // i.e. we should not retry for longer than a well-chosen upper bound. Maybe ~1 // minute. Ideally less than 30 seconds or so. Also note that retries are done // automatically for a range of transient issues: ETIMEDOUT ECONNRESET // EADDRINUSE ECONNREFUSED EPIPE ENOTFOUND ENETUNREACH EAI_AGAIN const GOT_JWKS_RETRY_OBJECT = { limit: 3, calculateDelay: customGotRetryfunc, statusCodes: [408, 413, 429, 500, 502, 503, 504, 521, 522, 524], // do not retry for longer than 60 seconds maxRetryAfter: 45 * 1000 }; const GOT_JWKS_OPTIONS = { retry: GOT_JWKS_RETRY_OBJECT, timeout: GOT_JWKS_HTTP_TIMEOUT_SETTINGS, throwHttpErrors: false }; /** * Set newly fetched JWKS object. Rely on this being an atomic operation in the * runtime. Return the same object for convenience. */ function rememberNewJWKS(j: object): object { LAST_JWKS_POTENTIALLY_STALE = j; LAST_JWKS_SET_TIME = mtime(); log.info( "JWKS fetcher: got fresh key set, stored as LAST_JWKS_POTENTIALLY_STALE" ); return j; } function getPotantiallyStaleJWKS() { assert(LAST_JWKS_SET_TIME !== undefined); log.info( `JWKS fetcher: use potentially stale JWKS. Age: ${mtimeDiffSeconds( LAST_JWKS_SET_TIME ).toFixed(2)} ` ); return LAST_JWKS_POTENTIALLY_STALE; } export async function prepopulate(url: string) { FIRST_JWKS_FROM_PREPOPULATE_CALL = await fetch(url); log.info("JWKS prepopulation: done"); } /** Start prepopulate() execution. Also return promise, but build this function * so that it is fine to not `await` this promise, i.e. to let this run as * 'zombie' * * - is expected to not throw an error of any kind (see over-generalized err * handler) * * - is expected to do no harm: is expected to complete within an upper bound * of time, determined by timeout constants and retrying machinery * * - if it succeeds before the actual login request great, job done, the first * login request will likely use the cached JWKS key set. * * - if it fails before the actual login request: also OK, the JWKS is then * attempted to be fetched during login request processing. */ export async function prepopulateZombie(url: string) { try { await prepopulate(url); } catch (err: any) { log.warning(`non-fatal: JWKS preopulation failed: ${err}`); } } export async function fetch(url: string) { if (FIRST_JWKS_FROM_PREPOPULATE_CALL) { log.info( "JWKS fetcher: first call after prepopulate, return FIRST_JWKS_FROM_PREPOPULATE_CALL" ); // Important: reset to `undefined` so that this really is only used in the // _first_ call to jwksFetcher() that is _not_ from within prepopulate() const s = FIRST_JWKS_FROM_PREPOPULATE_CALL; FIRST_JWKS_FROM_PREPOPULATE_CALL = undefined; return s; } // Perform HTTP request -- this uses retrying (and logging), see above for // the corresponding parameters. log.info(`JWKS fetcher: start GET machinery with retrying. url: ${url}`); let resp: GotResponse<string> | undefined; const t0 = mtime(); try { resp = await got(url, GOT_JWKS_OPTIONS); } catch (err: any) { log.warning( `JWKS fetcher: giving up HTTP GET after retrying, last error: ${err}` ); } const dur = mtimeDiffSeconds(t0); log.info(`JWKS fetcher: got() call duration: ${dur.toFixed(3)} s`); if (resp === undefined) { if (LAST_JWKS_POTENTIALLY_STALE !== undefined) { return getPotantiallyStaleJWKS(); } throw new Error( `JWKS fetcher: HTTP GET failed and LAST_JWKS_POTENTIALLY_STALE not set (${Date.now()})` ); } // after retrying machinery we might still end up with e.g. a 504 response // as last response, not yet explicitly treated by code although the // JSON deser handler will catch that // TODO if (resp.code !== 200) { ... getPotantiallyStaleJWKS() ... } if (resp.statusCode !== 200) { log.warning( `JWKS fetcher: giving up HTTP GET, last response status code: ${resp.statusCode}` ); if (LAST_JWKS_POTENTIALLY_STALE !== undefined) { return getPotantiallyStaleJWKS(); } // Note(JP): by adding `Date.now()` to this error message I found that the // jwks-rsa cache would cache errors, too. Doh! This really undermines.. // see https://github.com/auth0/node-jwks-rsa/issues/257 throw new Error( `JWKS fetcher: HTTP GET failed and LAST_JWKS_POTENTIALLY_STALE not set (${Date.now()})` ); } let newKeySet: object | undefined; try { newKeySet = JSON.parse(resp.body); } catch (err: any) { log.warning(`JWKS fetcher: JSON deserialization failed: ${err}`); } if (newKeySet !== undefined) { return rememberNewJWKS(newKeySet); } if (LAST_JWKS_POTENTIALLY_STALE !== undefined) { return getPotantiallyStaleJWKS(); } throw new Error( `JWKS fetcher: request succeeded, deserialization failed, LAST_JWKS_POTENTIALLY_STALE not set (${Date.now()})` ); } // const DUMMY_JWKS = { // keys: [ // { // kty: "RSA", // kid: "cc34c0a0-bd5a-4a3c-a50d-a2a7db7643df", // use: "sig", // n: "pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w", // e: "AQAB", // d: "ksDmucdMJXkFGZxiomNHnroOZxe8AmDLDGO1vhs-POa5PZM7mtUPonxwjVmthmpbZzla-kg55OFfO7YcXhg-Hm2OWTKwm73_rLh3JavaHjvBqsVKuorX3V3RYkSro6HyYIzFJ1Ek7sLxbjDRcDOj4ievSX0oN9l-JZhaDYlPlci5uJsoqro_YrE0PRRWVhtGynd-_aWgQv1YzkfZuMD-hJtDi1Im2humOWxA4eZrFs9eG-whXcOvaSwO4sSGbS99ecQZHM2TcdXeAs1PvjVgQ_dKnZlGN3lTWoWfQP55Z7Tgt8Nf1q4ZAKd-NlMe-7iqCFfsnFwXjSiaOa2CRGZn-Q", // p: "4A5nU4ahEww7B65yuzmGeCUUi8ikWzv1C81pSyUKvKzu8CX41hp9J6oRaLGesKImYiuVQK47FhZ--wwfpRwHvSxtNU9qXb8ewo-BvadyO1eVrIk4tNV543QlSe7pQAoJGkxCia5rfznAE3InKF4JvIlchyqs0RQ8wx7lULqwnn0", // q: "ven83GM6SfrmO-TBHbjTk6JhP_3CMsIvmSdo4KrbQNvp4vHO3w1_0zJ3URkmkYGhz2tgPlfd7v1l2I6QkIh4Bumdj6FyFZEBpxjE4MpfdNVcNINvVj87cLyTRmIcaGxmfylY7QErP8GFA-k4UoH_eQmGKGK44TRzYj5hZYGWIC8", // dp: "lmmU_AG5SGxBhJqb8wxfNXDPJjf__i92BgJT2Vp4pskBbr5PGoyV0HbfUQVMnw977RONEurkR6O6gxZUeCclGt4kQlGZ-m0_XSWx13v9t9DIbheAtgVJ2mQyVDvK4m7aRYlEceFh0PsX8vYDS5o1txgPwb3oXkPTtrmbAGMUBpE", // dq: "mxRTU3QDyR2EnCv0Nl0TCF90oliJGAHR9HJmBe__EjuCBbwHfcT8OG3hWOv8vpzokQPRl5cQt3NckzX3fs6xlJN4Ai2Hh2zduKFVQ2p-AF2p6Yfahscjtq-GY9cB85NxLy2IXCC0PF--Sq9LOrTE9QV988SJy_yUrAjcZ5MmECk", // qi: "ldHXIrEmMZVaNwGzDF9WG8sHj2mOZmQpw9yrjLK9hAsmsNr5LTyqWAqJIYZSwPTYWhY4nu2O0EY9G9uYiqewXfCKw_UngrJt8Xwfq1Zruz0YY869zPN4GiE9-9rzdZB33RBw8kIOquY3MK74FMwCihYx_LiU2YTHkaoJ3ncvtvg" // } // ] // };
the_stack
import {assert} from 'chai'; import createReduxStore from '../../main/createReduxStore'; import {present, setDifficulty, guess} from './index'; import {Store, GameName} from '../../types'; import * as PianoGame from '../../models/PianoGame'; import {spy} from 'sinon'; // tslint:disable:max-line-length describe('gameActions', () => { let store: Store; const gameName: GameName = 'piano-game'; function getGameState(): PianoGame.State { return store.getState().games.pianoGame; } function getIncorrectChoice(): PianoGame.Guess { const state = getGameState(); return state.choices.get(0) === state.correctChoice ? state.choices.get(0) : state.choices.get(1); } beforeEach(() => { store = createReduxStore(); }); describe('present', () => { it('should present a game and synchronously increment a counter', () => { const initialPresentCount = 0; assert.strictEqual(getGameState().presentCount, initialPresentCount); const promise = store.dispatch(present(gameName)); assert.strictEqual(getGameState().presentCount, initialPresentCount + 1); return promise.then(() => { assert.strictEqual(getGameState().presentCount, initialPresentCount + 1); }); }); it('should present a game, disable input during the process, and enable it afterwards', () => { assert.strictEqual(store.getState().games.isInputEnabled, true); const promise = store.dispatch(present(gameName)); assert.strictEqual(store.getState().games.isInputEnabled, false); return promise.then(() => { assert.strictEqual(store.getState().games.isInputEnabled, true); }); }); it('should present a game and force refresh it', () => { const originalGameState = getGameState(); return store.dispatch(present(gameName, true)) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( originalGameState.refreshChoicesCount, updatedGameState.refreshChoicesCount - 1, 'force refreshing a game should refresh the choices' ); assert.strictEqual( originalGameState.refreshCorrectChoiceCount, updatedGameState.refreshCorrectChoiceCount - 1, 'force refreshing a game should refresh the correct choice' ); }); }); it('should present a game and not refresh the correct choice if the game has had no correct guesses and it is not forced', () => { const originalGameState = getGameState(); assert.strictEqual( !originalGameState.shouldRefreshChoices && !originalGameState.shouldRefreshCorrectChoice, true, 'a game in its original state should not have any flags set to refresh the choices' ); return store.dispatch(present(gameName, false)) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( originalGameState.refreshChoicesCount, updatedGameState.refreshChoicesCount, 'non-force refreshing a game that has no flags set to refresh it should result in no changes to the choices' ); assert.strictEqual( originalGameState.refreshCorrectChoiceCount, updatedGameState.refreshCorrectChoiceCount, 'non-force refreshing a game that has no flags set to refresh it should result in no changes to the correct choice' ); }); }); }); describe('setDifficulty', () => { it('should set the difficulty of the game and fully refresh it', () => { const newLevel = 2; const newStep = 2; const originalGameState = getGameState(); assert.notStrictEqual( originalGameState.level, newLevel ); assert.notStrictEqual( originalGameState.step, newStep ); return store.dispatch(setDifficulty(gameName, newLevel, newStep)) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( updatedGameState.level, newLevel, 'the level should be updated' ); assert.strictEqual( updatedGameState.step, newStep, 'the step should be updated' ); assert.strictEqual( originalGameState.refreshChoicesCount, updatedGameState.refreshChoicesCount - 1, 'setting the difficulty of a game should refresh the choices' ); assert.strictEqual( originalGameState.refreshCorrectChoiceCount, updatedGameState.refreshCorrectChoiceCount - 1, 'setting the difficulty of a game should refresh the correct choice' ); }); }); }); describe('guess', () => { it('should make a correct guess on a game and update the game guess state values', (): Promise<void> => { const originalGameState = getGameState(); const correctChoice = originalGameState.correctChoice; const promise = store.dispatch(guess(gameName, correctChoice)); const updatedGameState = getGameState(); assert.strictEqual(updatedGameState.lastGuess, correctChoice); assert.strictEqual(updatedGameState.wasLastGuessCorrect, true); assert.strictEqual(updatedGameState.guessCount, originalGameState.guessCount + 1); assert.strictEqual(updatedGameState.guessCountForCurrentCorrectChoice, 1); assert.strictEqual(updatedGameState.shouldRefreshCorrectChoice, true); return promise.then(() => { const finalGameState = getGameState(); assert.strictEqual(finalGameState.guessCountForCurrentCorrectChoice, 0, 'the correct choice count should be reset after a correct guess completes'); }); }); it('should make an incorrect guess on a game and update the game guess state values', (): Promise<void> => { const originalGameState = getGameState(); const incorrectChoice = getIncorrectChoice(); const promise = store.dispatch(guess(gameName, incorrectChoice)); const updatedGameState = getGameState(); assert.strictEqual(updatedGameState.lastGuess, incorrectChoice); assert.strictEqual(updatedGameState.wasLastGuessCorrect, false); assert.strictEqual(updatedGameState.guessCount, originalGameState.guessCount + 1); assert.strictEqual(updatedGameState.guessCountForCurrentCorrectChoice, 1); assert.strictEqual(updatedGameState.shouldRefreshCorrectChoice, false); return promise.then(() => { const finalGameState = getGameState(); assert.strictEqual(finalGameState.guessCountForCurrentCorrectChoice, 1, 'the correct choice count should not be reset after an incorrect guess completes'); }); }); it('should make a correct guess on a game at the final step of its level and advance to the next level', (): Promise<void> => { const originalLevel = 1; store.dispatch(setDifficulty(gameName, originalLevel, getGameState().stepCounts.get(originalLevel))); const originalGameState = getGameState(); return store.dispatch(guess(gameName, originalGameState.correctChoice)) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( originalGameState.level, updatedGameState.level - 1, 'making a correct guess on a game at the final step of the level should increment the level' ); assert.strictEqual( updatedGameState.step, 1, 'incrementing the level should set the step to 1' ); }); }); it('should make an incorrect guess on a game at the first step of its level and fall back a level', (): Promise<void> => { store.dispatch(setDifficulty(gameName, 2, 1)); const originalGameState = getGameState(); return store.dispatch(guess(gameName, getIncorrectChoice())) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( originalGameState.level, updatedGameState.level + 1, 'making an incorrect guess on a game at the first step of the level should decrement the level' ); assert.strictEqual( updatedGameState.step, updatedGameState.stepCounts.get(updatedGameState.level), 'decrementing the level should set the step to its new maximum' ); }); }); it('should make a correct guess on a game and renew it', (): Promise<void> => { const originalGameState = getGameState(); return store.dispatch(guess(gameName, originalGameState.correctChoice)) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( originalGameState.refreshChoicesCount, updatedGameState.refreshChoicesCount - 1, 'making a correct guess on a game should refresh the choices' ); assert.strictEqual( originalGameState.refreshCorrectChoiceCount, updatedGameState.refreshCorrectChoiceCount - 1, 'making a correct guess on a game should refresh the correct choice' ); }); }); it('should make an incorrect guess on a game that does not change the level and not renew it', (): Promise<void> => { store.dispatch(setDifficulty(gameName, 1, 1)); const originalGameState = getGameState(); return store.dispatch(guess(gameName, getIncorrectChoice())) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( originalGameState.refreshChoicesCount, updatedGameState.refreshChoicesCount, 'making an incorrect guess on a game that does not change the level should not refresh the choices' ); assert.strictEqual( originalGameState.refreshCorrectChoiceCount, updatedGameState.refreshCorrectChoiceCount, 'making an incorrect guess on a game that does not change the level should not refresh the correct choice' ); }); }); it('should make an incorrect guess on a game that changes the level and renews it', (): Promise<void> => { store.dispatch(setDifficulty(gameName, 2, 1)); const originalGameState = getGameState(); return store.dispatch(guess(gameName, getIncorrectChoice())) .then(() => { const updatedGameState = getGameState(); assert.strictEqual( originalGameState.refreshChoicesCount, updatedGameState.refreshChoicesCount - 1, 'making an incorrect guess on a game that changes the level should refresh the choices' ); // TODO we could test refreshing the correct choice // there are two conditions: // if the correct choice is still in the new choices, do not refresh it. // if the correct choice is not in the new choices, refresh it. }); }); it('should make a correct guess on a game, immediately disable input, and re-enable it when the next choices are presented', (): Promise<void> => { const promise = store.dispatch(guess(gameName, getGameState().correctChoice)); assert.strictEqual( store.getState().games.isInputEnabled, false, 'input should be disabled directly after a correct guess' ); return promise.then(() => { assert.strictEqual( store.getState().games.isInputEnabled, true, 'input should be enabled after the game finishes a correct guess' ); }); }); it('should make an incorrect guess on a game and not disable input', (): Promise<void> => { const promise = store.dispatch(guess(gameName, getIncorrectChoice())); assert.strictEqual( store.getState().games.isInputEnabled, true, 'input should remain enabled directly after an incorrect guess' ); return promise.then(() => { assert.strictEqual( store.getState().games.isInputEnabled, true, 'input should still be enabled after an incorrect guess on a game' ); }); }); it('should make a correct guess on a game and use the provided functions', (): Promise<void> => { const getDelaySpy = spy(() => 1); const onCompleteSpy = spy(); return store.dispatch(guess(gameName, getGameState().correctChoice, getDelaySpy, onCompleteSpy)) .then(() => { assert(getDelaySpy.calledOnce); assert(getDelaySpy.calledWithExactly(true, gameName)); assert(onCompleteSpy.calledOnce); assert(onCompleteSpy.calledWith(true, gameName)); // dispatch is the 3rd arg but Redux does not pass the same `store.dispatch` function identity to middleware assert.typeOf(onCompleteSpy.firstCall.args[2], 'function'); }); }); it('should make an incorrect guess on a game and use the provided functions', (): Promise<void> => { const getDelaySpy = spy(() => 1); const onCompleteSpy = spy(); return store.dispatch(guess(gameName, getIncorrectChoice(), getDelaySpy, onCompleteSpy)) .then(() => { assert(getDelaySpy.calledOnce); assert(getDelaySpy.calledWithExactly(false, gameName)); assert(onCompleteSpy.calledOnce); assert(onCompleteSpy.calledWith(false, gameName)); // dispatch is the 3rd arg but Redux does not pass the same `store.dispatch` function identity to middleware assert.typeOf(onCompleteSpy.firstCall.args[2], 'function'); }); }); }); });
the_stack
'use strict'; import * as crypto from 'crypto'; import * as vscode from 'vscode'; import { Repository } from '../api/api'; import { GitApiImpl } from '../api/api1'; import { IComment, IReviewThread, Reaction } from '../common/comment'; import { DiffHunk, parseDiffHunk } from '../common/diffHunk'; import { Resource } from '../common/resources'; import * as Common from '../common/timelineEvent'; import { uniqBy } from '../common/utils'; import { OctokitCommon } from './common'; import { AuthProvider } from './credentials'; import { PullRequestDefaults, SETTINGS_NAMESPACE } from './folderRepositoryManager'; import { GitHubRepository, ViewerPermission } from './githubRepository'; import * as GraphQL from './graphql'; import { IAccount, IGitHubRef, ILabel, IMilestone, Issue, ISuggestedReviewer, PullRequest, PullRequestMergeability, ReviewState, User, } from './interface'; import { IssueModel } from './issueModel'; import { GHPRComment, GHPRCommentThread } from './prComment'; export interface CommentReactionHandler { toggleReaction(comment: vscode.Comment, reaction: vscode.CommentReaction): Promise<void>; } export type ParsedIssue = { owner: string | undefined; name: string | undefined; issueNumber: number; commentNumber?: number; }; export function threadRange(startLine: number, endLine: number, endCharacter?: number): vscode.Range { if ((startLine !== endLine) && (endCharacter === undefined)) { endCharacter = 300; // 300 is a "large" number that will select a lot of the line since don't know anything about the line length } else if (!endCharacter) { endCharacter = 0; } return new vscode.Range(startLine, 0, endLine, endCharacter); } export function createVSCodeCommentThreadForReviewThread( uri: vscode.Uri, range: vscode.Range, thread: IReviewThread, commentController: vscode.CommentController, currentUser: string ): GHPRCommentThread { const vscodeThread = commentController.createCommentThread(uri, range, []); (vscodeThread as GHPRCommentThread).gitHubThreadId = thread.id; vscodeThread.comments = thread.comments.map(comment => new GHPRComment(comment, vscodeThread as GHPRCommentThread)); vscodeThread.state = isResolvedToResolvedState(thread.isResolved); if (thread.viewerCanResolve && !thread.isResolved) { vscodeThread.contextValue = 'canResolve'; } else if (thread.viewerCanUnresolve && thread.isResolved) { vscodeThread.contextValue = 'canUnresolve'; } updateCommentThreadLabel(vscodeThread as GHPRCommentThread); vscodeThread.collapsibleState = getCommentCollapsibleState(thread, undefined, currentUser); return vscodeThread as GHPRCommentThread; } function isResolvedToResolvedState(isResolved: boolean) { return isResolved ? vscode.CommentThreadState.Resolved : vscode.CommentThreadState.Unresolved; } export const COMMENT_EXPAND_STATE_SETTING = 'commentExpandState'; export const COMMENT_EXPAND_STATE_COLLAPSE_VALUE = 'collapseAll'; export const COMMENT_EXPAND_STATE_EXPAND_VALUE = 'expandUnresolved'; export function getCommentCollapsibleState(thread: IReviewThread, expand?: boolean, currentUser?: string) { if (thread.isResolved || (currentUser && thread.comments[thread.comments.length - 1].user?.login === currentUser)) { return vscode.CommentThreadCollapsibleState.Collapsed; } if (expand === undefined) { const config = vscode.workspace.getConfiguration(SETTINGS_NAMESPACE)?.get(COMMENT_EXPAND_STATE_SETTING); expand = config === COMMENT_EXPAND_STATE_EXPAND_VALUE; } return expand ? vscode.CommentThreadCollapsibleState.Expanded : vscode.CommentThreadCollapsibleState.Collapsed; } export function updateThreadWithRange(vscodeThread: GHPRCommentThread, reviewThread: IReviewThread, expand?: boolean) { const editors = vscode.window.visibleTextEditors; for (let editor of editors) { if (editor.document.uri.toString() === vscodeThread.uri.toString()) { const endLine = editor.document.lineAt(vscodeThread.range.end.line); const range = new vscode.Range(vscodeThread.range.start.line, 0, vscodeThread.range.end.line, endLine.text.length); updateThread(vscodeThread, reviewThread, expand, range); break; } } } export function updateThread(vscodeThread: GHPRCommentThread, reviewThread: IReviewThread, expand?: boolean, range?: vscode.Range) { if (reviewThread.viewerCanResolve && !reviewThread.isResolved) { vscodeThread.contextValue = 'canResolve'; } else if (reviewThread.viewerCanUnresolve && reviewThread.isResolved) { vscodeThread.contextValue = 'canUnresolve'; } const newResolvedState = isResolvedToResolvedState(reviewThread.isResolved); if (vscodeThread.state !== newResolvedState) { vscodeThread.state = newResolvedState; } vscodeThread.collapsibleState = getCommentCollapsibleState(reviewThread, expand); if (range) { vscodeThread.range = range; } vscodeThread.comments = reviewThread.comments.map(c => new GHPRComment(c, vscodeThread)); updateCommentThreadLabel(vscodeThread); } export function updateCommentThreadLabel(thread: GHPRCommentThread) { if (thread.state === vscode.CommentThreadState.Resolved) { thread.label = 'Marked as resolved'; return; } if (thread.comments.length) { const participantsList = uniqBy(thread.comments as vscode.Comment[], comment => comment.author.name) .map(comment => `@${comment.author.name}`) .join(', '); thread.label = `Participants: ${participantsList}`; } else { thread.label = 'Start discussion'; } } export function generateCommentReactions(reactions: Reaction[] | undefined) { return getReactionGroup().map(reaction => { if (!reactions) { return { label: reaction.label, authorHasReacted: false, count: 0, iconPath: reaction.icon || '' }; } const matchedReaction = reactions.find(re => re.label === reaction.label); if (matchedReaction) { return { label: matchedReaction.label, authorHasReacted: matchedReaction.viewerHasReacted, count: matchedReaction.count, iconPath: reaction.icon || '', }; } else { return { label: reaction.label, authorHasReacted: false, count: 0, iconPath: reaction.icon || '' }; } }); } export function updateCommentReactions(comment: vscode.Comment, reactions: Reaction[] | undefined) { comment.reactions = generateCommentReactions(reactions); } export function updateCommentReviewState(thread: GHPRCommentThread, newDraftMode: boolean) { if (newDraftMode) { return; } thread.comments = thread.comments.map(comment => { if (comment instanceof GHPRComment) { comment._rawComment.isDraft = false; } comment.label = undefined; return comment; }); } export function convertRESTUserToAccount( user: OctokitCommon.PullsListResponseItemUser, githubRepository: GitHubRepository, ): IAccount { return { login: user.login, url: user.html_url, avatarUrl: getAvatarWithEnterpriseFallback(user.avatar_url, user.gravatar_id ?? undefined, githubRepository.remote.authProviderId), }; } export function convertRESTHeadToIGitHubRef(head: OctokitCommon.PullsListResponseItemHead) { return { label: head.label, ref: head.ref, sha: head.sha, repo: { cloneUrl: head.repo.clone_url, owner: head.repo.owner!.login, name: head.repo.name }, }; } export function convertRESTPullRequestToRawPullRequest( pullRequest: | OctokitCommon.PullsCreateResponseData | OctokitCommon.PullsGetResponseData | OctokitCommon.PullsListResponseItem, githubRepository: GitHubRepository, ): PullRequest { const { number, body, title, html_url, user, state, assignees, created_at, updated_at, head, base, labels, node_id, id, draft, } = pullRequest; const item: PullRequest = { id, graphNodeId: node_id, number, body: body ?? '', title, url: html_url, user: convertRESTUserToAccount(user!, githubRepository), state, merged: (pullRequest as OctokitCommon.PullsGetResponseData).merged || false, assignees: assignees ? assignees.map(assignee => convertRESTUserToAccount(assignee!, githubRepository)) : undefined, createdAt: created_at, updatedAt: updated_at, head: convertRESTHeadToIGitHubRef(head), base: convertRESTHeadToIGitHubRef(base), mergeable: (pullRequest as OctokitCommon.PullsGetResponseData).mergeable ? PullRequestMergeability.Mergeable : PullRequestMergeability.NotMergeable, labels: labels.map<ILabel>(l => ({ name: '', color: '', ...l })), isDraft: draft, suggestedReviewers: [], // suggested reviewers only available through GraphQL API }; return item; } export function convertRESTIssueToRawPullRequest( pullRequest: OctokitCommon.IssuesCreateResponseData, githubRepository: GitHubRepository, ): PullRequest { const { number, body, title, html_url, user, state, assignees, created_at, updated_at, labels, node_id, id, } = pullRequest; const item: PullRequest = { id, graphNodeId: node_id, number, body: body ?? '', title, url: html_url, user: convertRESTUserToAccount(user!, githubRepository), state, assignees: assignees ? assignees.map(assignee => convertRESTUserToAccount(assignee!, githubRepository)) : undefined, createdAt: created_at, updatedAt: updated_at, labels: labels.map<ILabel>(l => typeof l === 'string' ? { name: l, color: '' } : { name: l.name ?? '', color: l.color ?? '' }, ), suggestedReviewers: [], // suggested reviewers only available through GraphQL API }; return item; } export function convertRESTReviewEvent( review: OctokitCommon.PullsCreateReviewResponseData, githubRepository: GitHubRepository, ): Common.ReviewEvent { return { event: Common.EventType.Reviewed, comments: [], submittedAt: (review as any).submitted_at, // TODO fix typings upstream body: review.body, bodyHTML: review.body, htmlUrl: review.html_url, user: convertRESTUserToAccount(review.user!, githubRepository), authorAssociation: review.user!.type, state: review.state as 'COMMENTED' | 'APPROVED' | 'CHANGES_REQUESTED' | 'PENDING', id: review.id, }; } export function parseCommentDiffHunk(comment: IComment): DiffHunk[] { const diffHunks: DiffHunk[] = []; const diffHunkReader = parseDiffHunk(comment.diffHunk); let diffHunkIter = diffHunkReader.next(); while (!diffHunkIter.done) { const diffHunk = diffHunkIter.value; diffHunks.push(diffHunk); diffHunkIter = diffHunkReader.next(); } return diffHunks; } export function convertPullRequestsGetCommentsResponseItemToComment( comment: OctokitCommon.PullsCreateReviewCommentResponseData, githubRepository: GitHubRepository, ): IComment { const ret: IComment = { url: comment.url, id: comment.id, pullRequestReviewId: comment.pull_request_review_id ?? undefined, diffHunk: comment.diff_hunk, path: comment.path, position: comment.position, commitId: comment.commit_id, originalPosition: comment.original_position, originalCommitId: comment.original_commit_id, user: convertRESTUserToAccount(comment.user!, githubRepository), body: comment.body, createdAt: comment.created_at, htmlUrl: comment.html_url, inReplyToId: comment.in_reply_to_id, graphNodeId: comment.node_id, }; const diffHunks = parseCommentDiffHunk(ret); ret.diffHunks = diffHunks; return ret; } export function convertGraphQLEventType(text: string) { switch (text) { case 'PullRequestCommit': return Common.EventType.Committed; case 'LabeledEvent': return Common.EventType.Labeled; case 'MilestonedEvent': return Common.EventType.Milestoned; case 'AssignedEvent': return Common.EventType.Assigned; case 'HeadRefDeletedEvent': return Common.EventType.HeadRefDeleted; case 'IssueComment': return Common.EventType.Commented; case 'PullRequestReview': return Common.EventType.Reviewed; case 'MergedEvent': return Common.EventType.Merged; default: return Common.EventType.Other; } } export function parseGraphQLReviewThread(thread: GraphQL.ReviewThread): IReviewThread { return { id: thread.id, isResolved: thread.isResolved, viewerCanResolve: thread.viewerCanResolve, viewerCanUnresolve: thread.viewerCanUnresolve, path: thread.path, startLine: thread.startLine ?? thread.line, endLine: thread.line, originalStartLine: thread.originalStartLine ?? thread.originalLine, originalEndLine: thread.originalLine, diffSide: thread.diffSide, isOutdated: thread.isOutdated, comments: thread.comments.nodes.map(comment => parseGraphQLComment(comment, thread.isResolved)), }; } export function parseGraphQLComment(comment: GraphQL.ReviewComment, isResolved: boolean): IComment { const c: IComment = { id: comment.databaseId, url: comment.url, body: comment.body, bodyHTML: comment.bodyHTML, path: comment.path, canEdit: comment.viewerCanDelete, canDelete: comment.viewerCanDelete, pullRequestReviewId: comment.pullRequestReview && comment.pullRequestReview.databaseId, diffHunk: comment.diffHunk, position: comment.position, commitId: comment.commit.oid, originalPosition: comment.originalPosition, originalCommitId: comment.originalCommit && comment.originalCommit.oid, user: comment.author, createdAt: comment.createdAt, htmlUrl: comment.url, graphNodeId: comment.id, isDraft: comment.state === 'PENDING', inReplyToId: comment.replyTo && comment.replyTo.databaseId, reactions: parseGraphQLReaction(comment.reactionGroups), isResolved, }; const diffHunks = parseCommentDiffHunk(c); c.diffHunks = diffHunks; return c; } export function parseGraphQlIssueComment(comment: GraphQL.IssueComment): IComment { return { id: comment.databaseId, url: comment.url, body: comment.body, bodyHTML: comment.bodyHTML, canEdit: comment.viewerCanDelete, canDelete: comment.viewerCanDelete, user: comment.author, createdAt: comment.createdAt, htmlUrl: comment.url, graphNodeId: comment.id, diffHunk: '', }; } export function parseGraphQLReaction(reactionGroups: GraphQL.ReactionGroup[]): Reaction[] { const reactionContentEmojiMapping = getReactionGroup().reduce((prev, curr) => { prev[curr.title] = curr; return prev; }, {} as { [key: string]: { title: string; label: string; icon?: vscode.Uri } }); const reactions = reactionGroups .filter(group => group.users.totalCount > 0) .map(group => { const reaction: Reaction = { label: reactionContentEmojiMapping[group.content].label, count: group.users.totalCount, icon: reactionContentEmojiMapping[group.content].icon, viewerHasReacted: group.viewerHasReacted, }; return reaction; }); return reactions; } function parseRef(refName: string, oid: string, repository?: GraphQL.RefRepository): IGitHubRef | undefined { if (!repository) { return undefined; } return { label: `${repository.owner.login}:${refName}`, ref: refName, sha: oid, repo: { cloneUrl: repository.url, owner: repository.owner.login, name: refName }, }; } function parseAuthor( author: { login: string; url: string; avatarUrl: string; email?: string } | null, githubRepository: GitHubRepository, ): IAccount { if (author) { return { login: author.login, url: author.url, avatarUrl: getAvatarWithEnterpriseFallback(author.avatarUrl, undefined, githubRepository.remote.authProviderId), email: author.email }; } else { return { login: '', url: '', }; } } export function parseMilestone( milestone: { title: string; dueOn?: string; createdAt: string; id: string } | undefined, ): IMilestone | undefined { if (!milestone) { return undefined; } return { title: milestone.title, dueOn: milestone.dueOn, createdAt: milestone.createdAt, id: milestone.id, }; } export function parseMergeability(mergeability: 'UNKNOWN' | 'MERGEABLE' | 'CONFLICTING', mergeStateStatus: 'BEHIND' | 'BLOCKED' | 'CLEAN' | 'DIRTY' | 'HAS_HOOKS' | 'UNKNOWN' | 'UNSTABLE'): PullRequestMergeability { let parsed: PullRequestMergeability; switch (mergeability) { case 'UNKNOWN': parsed = PullRequestMergeability.Unknown; break; case 'MERGEABLE': parsed = PullRequestMergeability.Mergeable; break; case 'CONFLICTING': parsed = PullRequestMergeability.Conflict; break; } if ((parsed !== PullRequestMergeability.Conflict) && (mergeStateStatus === 'BLOCKED')) { parsed = PullRequestMergeability.NotMergeable; } return parsed; } export function parseGraphQLPullRequest( graphQLPullRequest: GraphQL.PullRequest, githubRepository: GitHubRepository, ): PullRequest { return { id: graphQLPullRequest.databaseId, graphNodeId: graphQLPullRequest.id, url: graphQLPullRequest.url, number: graphQLPullRequest.number, state: graphQLPullRequest.state, body: graphQLPullRequest.body, bodyHTML: graphQLPullRequest.bodyHTML, title: graphQLPullRequest.title, createdAt: graphQLPullRequest.createdAt, updatedAt: graphQLPullRequest.updatedAt, isRemoteHeadDeleted: !graphQLPullRequest.headRef, head: parseRef(graphQLPullRequest.headRef?.name ?? graphQLPullRequest.headRefName, graphQLPullRequest.headRefOid, graphQLPullRequest.headRepository), isRemoteBaseDeleted: !graphQLPullRequest.baseRef, base: parseRef(graphQLPullRequest.baseRef?.name ?? graphQLPullRequest.baseRefName, graphQLPullRequest.baseRefOid, graphQLPullRequest.baseRepository), user: parseAuthor(graphQLPullRequest.author, githubRepository), merged: graphQLPullRequest.merged, mergeable: parseMergeability(graphQLPullRequest.mergeable, graphQLPullRequest.mergeStateStatus), labels: graphQLPullRequest.labels.nodes, isDraft: graphQLPullRequest.isDraft, suggestedReviewers: parseSuggestedReviewers(graphQLPullRequest.suggestedReviewers), comments: parseComments(graphQLPullRequest.comments?.nodes, githubRepository), milestone: parseMilestone(graphQLPullRequest.milestone), assignees: graphQLPullRequest.assignees?.nodes.map(assignee => parseAuthor(assignee, githubRepository)), }; } function parseComments(comments: GraphQL.AbbreviatedIssueComment[] | undefined, githubRepository: GitHubRepository) { if (!comments) { return; } const parsedComments: { author: IAccount; body: string; databaseId: number; }[] = []; for (const comment of comments) { parsedComments.push({ author: parseAuthor(comment.author, githubRepository), body: comment.body, databaseId: comment.databaseId, }); } return parsedComments; } export function parseGraphQLIssue(issue: GraphQL.PullRequest, githubRepository: GitHubRepository): Issue { return { id: issue.databaseId, graphNodeId: issue.id, url: issue.url, number: issue.number, state: issue.state, body: issue.body, bodyHTML: issue.bodyHTML, title: issue.title, createdAt: issue.createdAt, updatedAt: issue.updatedAt, assignees: issue.assignees?.nodes.map(assignee => parseAuthor(assignee, githubRepository)), user: parseAuthor(issue.author, githubRepository), labels: issue.labels.nodes, repositoryName: issue.repository?.name, repositoryOwner: issue.repository?.owner.login, repositoryUrl: issue.repository?.url, }; } export function parseGraphQLIssuesRequest( pullRequest: GraphQL.PullRequest, githubRepository: GitHubRepository, ): PullRequest { const graphQLPullRequest = pullRequest; return { id: graphQLPullRequest.databaseId, graphNodeId: graphQLPullRequest.id, url: graphQLPullRequest.url, number: graphQLPullRequest.number, state: graphQLPullRequest.state, body: graphQLPullRequest.body, bodyHTML: graphQLPullRequest.bodyHTML, title: graphQLPullRequest.title, createdAt: graphQLPullRequest.createdAt, updatedAt: graphQLPullRequest.updatedAt, isRemoteHeadDeleted: !graphQLPullRequest.headRef, head: parseRef(graphQLPullRequest.headRef?.name ?? graphQLPullRequest.headRefName, graphQLPullRequest.headRefOid, graphQLPullRequest.headRepository), isRemoteBaseDeleted: !graphQLPullRequest.baseRef, base: parseRef(graphQLPullRequest.baseRef?.name ?? graphQLPullRequest.baseRefName, graphQLPullRequest.baseRefOid, graphQLPullRequest.baseRepository), user: parseAuthor(graphQLPullRequest.author, githubRepository), merged: graphQLPullRequest.merged, mergeable: parseMergeability(graphQLPullRequest.mergeable, pullRequest.mergeStateStatus), labels: graphQLPullRequest.labels.nodes, isDraft: graphQLPullRequest.isDraft, suggestedReviewers: parseSuggestedReviewers(graphQLPullRequest.suggestedReviewers), milestone: parseMilestone(graphQLPullRequest.milestone), }; } function parseSuggestedReviewers( suggestedReviewers: GraphQL.SuggestedReviewerResponse[] | undefined, ): ISuggestedReviewer[] { if (!suggestedReviewers) { return []; } const ret: ISuggestedReviewer[] = suggestedReviewers.map(suggestedReviewer => { return { login: suggestedReviewer.reviewer.login, avatarUrl: suggestedReviewer.reviewer.avatarUrl, name: suggestedReviewer.reviewer.name, url: suggestedReviewer.reviewer.url, isAuthor: suggestedReviewer.isAuthor, isCommenter: suggestedReviewer.isCommenter, }; }); return ret.sort(loginComparator); } /** * Used for case insensitive sort by login */ export function loginComparator(a: IAccount, b: IAccount) { // sensitivity: 'accent' allows case insensitive comparison return a.login.localeCompare(b.login, 'en', { sensitivity: 'accent' }); } export function parseGraphQLReviewEvent( review: GraphQL.SubmittedReview, githubRepository: GitHubRepository, ): Common.ReviewEvent { return { event: Common.EventType.Reviewed, comments: review.comments.nodes.map(comment => parseGraphQLComment(comment, false)).filter(c => !c.inReplyToId), submittedAt: review.submittedAt, body: review.body, bodyHTML: review.bodyHTML, htmlUrl: review.url, user: parseAuthor(review.author, githubRepository), authorAssociation: review.authorAssociation, state: review.state, id: review.databaseId, }; } export function parseGraphQLTimelineEvents( events: ( | GraphQL.MergedEvent | GraphQL.Review | GraphQL.IssueComment | GraphQL.Commit | GraphQL.AssignedEvent | GraphQL.HeadRefDeletedEvent )[], githubRepository: GitHubRepository, ): Common.TimelineEvent[] { const normalizedEvents: Common.TimelineEvent[] = []; events.forEach(event => { const type = convertGraphQLEventType(event.__typename); switch (type) { case Common.EventType.Commented: const commentEvent = event as GraphQL.IssueComment; normalizedEvents.push({ htmlUrl: commentEvent.url, body: commentEvent.body, bodyHTML: commentEvent.bodyHTML, user: parseAuthor(commentEvent.author, githubRepository), event: type, canEdit: commentEvent.viewerCanUpdate, canDelete: commentEvent.viewerCanDelete, id: commentEvent.databaseId, graphNodeId: commentEvent.id, createdAt: commentEvent.createdAt, }); return; case Common.EventType.Reviewed: const reviewEvent = event as GraphQL.Review; normalizedEvents.push({ event: type, comments: [], submittedAt: reviewEvent.submittedAt, body: reviewEvent.body, bodyHTML: reviewEvent.bodyHTML, htmlUrl: reviewEvent.url, user: parseAuthor(reviewEvent.author, githubRepository), authorAssociation: reviewEvent.authorAssociation, state: reviewEvent.state, id: reviewEvent.databaseId, }); return; case Common.EventType.Committed: const commitEv = event as GraphQL.Commit; normalizedEvents.push({ id: commitEv.id, event: type, sha: commitEv.commit.oid, author: commitEv.commit.author.user ? parseAuthor(commitEv.commit.author.user, githubRepository) : { login: commitEv.commit.committer.name }, htmlUrl: commitEv.url, message: commitEv.commit.message, authoredDate: new Date(commitEv.commit.authoredDate), } as Common.CommitEvent); // TODO remove cast return; case Common.EventType.Merged: const mergeEv = event as GraphQL.MergedEvent; normalizedEvents.push({ id: mergeEv.id, event: type, user: parseAuthor(mergeEv.actor, githubRepository), createdAt: mergeEv.createdAt, mergeRef: mergeEv.mergeRef.name, sha: mergeEv.commit.oid, commitUrl: mergeEv.commit.commitUrl, url: mergeEv.url, graphNodeId: mergeEv.id, }); return; case Common.EventType.Assigned: const assignEv = event as GraphQL.AssignedEvent; normalizedEvents.push({ id: assignEv.databaseId, event: type, user: assignEv.user, actor: assignEv.actor, }); return; case Common.EventType.HeadRefDeleted: const deletedEv = event as GraphQL.HeadRefDeletedEvent; normalizedEvents.push({ id: deletedEv.id, event: type, actor: deletedEv.actor, createdAt: deletedEv.createdAt, headRef: deletedEv.headRefName, }); return; default: break; } }); return normalizedEvents; } export function parseGraphQLUser(user: GraphQL.UserResponse, githubRepository: GitHubRepository): User { return { login: user.user.login, name: user.user.name, avatarUrl: user.user.avatarUrl ? getAvatarWithEnterpriseFallback(user.user.avatarUrl, undefined, githubRepository.remote.authProviderId) : undefined, url: user.user.url, bio: user.user.bio, company: user.user.company, location: user.user.location, commitContributions: parseGraphQLCommitContributions(user.user.contributionsCollection), }; } function parseGraphQLCommitContributions( commitComments: GraphQL.ContributionsCollection, ): { createdAt: Date; repoNameWithOwner: string }[] { const items: { createdAt: Date; repoNameWithOwner: string }[] = []; commitComments.commitContributionsByRepository.forEach(repoCommits => { repoCommits.contributions.nodes.forEach(commit => { items.push({ createdAt: new Date(commit.occurredAt), repoNameWithOwner: repoCommits.repository.nameWithOwner, }); }); }); return items; } export function getReactionGroup(): { title: string; label: string; icon?: vscode.Uri }[] { const ret = [ { title: 'THUMBS_UP', label: '👍', icon: Resource.icons.reactions.THUMBS_UP, }, { title: 'THUMBS_DOWN', label: '👎', icon: Resource.icons.reactions.THUMBS_DOWN, }, { title: 'LAUGH', label: '😄', icon: Resource.icons.reactions.LAUGH, }, { title: 'HOORAY', label: '🎉', icon: Resource.icons.reactions.HOORAY, }, { title: 'CONFUSED', label: '😕', icon: Resource.icons.reactions.CONFUSED, }, { title: 'HEART', label: '❤️', icon: Resource.icons.reactions.HEART, }, { title: 'ROCKET', label: '🚀', icon: Resource.icons.reactions.ROCKET, }, { title: 'EYES', label: '👀', icon: Resource.icons.reactions.EYES, }, ]; return ret; } export function getRelatedUsersFromTimelineEvents( timelineEvents: Common.TimelineEvent[], ): { login: string; name: string }[] { const ret: { login: string; name: string }[] = []; timelineEvents.forEach(event => { if (Common.isCommitEvent(event)) { ret.push({ login: event.author.login, name: event.author.name || '', }); } if (Common.isReviewEvent(event)) { ret.push({ login: event.user.login, name: event.user.name ?? event.user.login, }); } if (Common.isCommentEvent(event)) { ret.push({ login: event.user.login, name: event.user.name ?? event.user.login, }); } }); return ret; } export function parseGraphQLViewerPermission( viewerPermissionResponse: GraphQL.ViewerPermissionResponse, ): ViewerPermission { if (viewerPermissionResponse && viewerPermissionResponse.repository.viewerPermission) { if ( (Object.values(ViewerPermission) as string[]).includes(viewerPermissionResponse.repository.viewerPermission) ) { return viewerPermissionResponse.repository.viewerPermission as ViewerPermission; } } return ViewerPermission.Unknown; } export function isFileInRepo(repository: Repository, file: vscode.Uri): boolean { return file.path.toLowerCase() === repository.rootUri.path.toLowerCase() || (file.path.toLowerCase().startsWith(repository.rootUri.path.toLowerCase()) && file.path.substring(repository.rootUri.path.length).startsWith('/')); } export function getRepositoryForFile(gitAPI: GitApiImpl, file: vscode.Uri): Repository | undefined { for (const repository of gitAPI.repositories) { if (isFileInRepo(repository, file)) { return repository; } } return undefined; } /** * Create a list of reviewers composed of people who have already left reviews on the PR, and * those that have had a review requested of them. If a reviewer has left multiple reviews, the * state should be the state of their most recent review, or 'REQUESTED' if they have an outstanding * review request. * @param requestedReviewers The list of reviewers that are requested for this pull request * @param timelineEvents All timeline events for the pull request * @param author The author of the pull request */ export function parseReviewers( requestedReviewers: IAccount[], timelineEvents: Common.TimelineEvent[], author: IAccount, ): ReviewState[] { const reviewEvents = timelineEvents.filter(Common.isReviewEvent).filter(event => event.state !== 'PENDING'); let reviewers: ReviewState[] = []; const seen = new Map<string, boolean>(); // Do not show the author in the reviewer list seen.set(author.login, true); for (let i = reviewEvents.length - 1; i >= 0; i--) { const reviewer = reviewEvents[i].user; if (!seen.get(reviewer.login)) { seen.set(reviewer.login, true); reviewers.push({ reviewer: reviewer, state: reviewEvents[i].state, }); } } requestedReviewers.forEach(request => { if (!seen.get(request.login)) { reviewers.push({ reviewer: request, state: 'REQUESTED', }); } else { const reviewer = reviewers.find(r => r.reviewer.login === request.login); reviewer!.state = 'REQUESTED'; } }); // Put completed reviews before review requests and alphabetize each section reviewers = reviewers.sort((a, b) => { if (a.state === 'REQUESTED' && b.state !== 'REQUESTED') { return 1; } if (b.state === 'REQUESTED' && a.state !== 'REQUESTED') { return -1; } return a.reviewer.login.toLowerCase() < b.reviewer.login.toLowerCase() ? -1 : 1; }); return reviewers; } export function getPRFetchQuery(repo: string, user: string, query: string): string { const filter = query.replace(/\$\{user\}/g, user); return `is:pull-request ${filter} type:pr repo:${repo}`; } export function isInCodespaces(): boolean { return vscode.env.remoteName === 'codespaces' && vscode.env.uiKind === vscode.UIKind.Web; } export function getEnterpriseUri(): vscode.Uri | undefined { const config: string = vscode.workspace.getConfiguration('github-enterprise').get<string>('uri', ''); if (config) { return vscode.Uri.parse(config, true); } } export function hasEnterpriseUri(): boolean { return !!getEnterpriseUri(); } export function generateGravatarUrl(gravatarId: string | undefined, size: number = 200): string | undefined { return !!gravatarId ? `https://www.gravatar.com/avatar/${gravatarId}?s=${size}&d=retro` : undefined; } export function getAvatarWithEnterpriseFallback(avatarUrl: string, email: string | undefined, authProviderId: AuthProvider): string | undefined { return authProviderId === AuthProvider.github ? avatarUrl : (email ? generateGravatarUrl( crypto.createHash('md5').update(email?.trim()?.toLowerCase()).digest('hex')) : undefined); } export function getPullsUrl(repo: GitHubRepository) { return vscode.Uri.parse(`https://${repo.remote.host}/${repo.remote.owner}/${repo.remote.repositoryName}/pulls`); } export function getIssuesUrl(repo: GitHubRepository) { return vscode.Uri.parse(`https://${repo.remote.host}/${repo.remote.owner}/${repo.remote.repositoryName}/issues`); } export function sanitizeIssueTitle(title: string): string { const regex = /[~^:;'".,~#?%*[\]@\\{}()]|\/\//g; return title.replace(regex, '').trim().replace(/\s+/g, '-'); } const VARIABLE_PATTERN = /\$\{(.*?)\}/g; export async function variableSubstitution( value: string, issueModel?: IssueModel, defaults?: PullRequestDefaults, user?: string, ): Promise<string> { return value.replace(VARIABLE_PATTERN, (match: string, variable: string) => { switch (variable) { case 'user': return user ? user : match; case 'issueNumber': return issueModel ? `${issueModel.number}` : match; case 'issueNumberLabel': return issueModel ? `${getIssueNumberLabel(issueModel, defaults)}` : match; case 'issueTitle': return issueModel ? issueModel.title : match; case 'repository': return defaults ? defaults.repo : match; case 'owner': return defaults ? defaults.owner : match; case 'sanitizedIssueTitle': return issueModel ? sanitizeIssueTitle(issueModel.title) : match; // check what characters are permitted case 'sanitizedLowercaseIssueTitle': return issueModel ? sanitizeIssueTitle(issueModel.title).toLowerCase() : match; default: return match; } }); } export function getIssueNumberLabel(issue: IssueModel, repo?: PullRequestDefaults) { const parsedIssue: ParsedIssue = { issueNumber: issue.number, owner: undefined, name: undefined }; if ( repo && (repo.owner.toLowerCase() !== issue.remote.owner.toLowerCase() || repo.repo.toLowerCase() !== issue.remote.repositoryName.toLowerCase()) ) { parsedIssue.owner = issue.remote.owner; parsedIssue.name = issue.remote.repositoryName; } return getIssueNumberLabelFromParsed(parsedIssue); } export function getIssueNumberLabelFromParsed(parsed: ParsedIssue) { if (!parsed.owner || !parsed.name) { return `#${parsed.issueNumber}`; } else { return `${parsed.owner}/${parsed.name}#${parsed.issueNumber}`; } }
the_stack
import { FunctionFragment, Interface, LogDescription, Result } from '@ethersproject/abi'; import { keccak256 } from '@ethersproject/keccak256'; import { defineReadOnly } from '@ethersproject/properties'; import { BPF_LOADER_PROGRAM_ID, BpfLoader, ConfirmOptions, Connection, PublicKey, Signer, SystemProgram, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_CLOCK_PUBKEY, Transaction, TransactionInstruction, Ed25519Program, } from '@solana/web3.js'; import { InvalidProgramAccountError, InvalidStorageAccountError, MissingPayerAccountError, MissingReturnDataError, } from './errors'; import { LogsParser, parseLogTopic, sendAndConfirmTransactionWithLogs, simulateTransactionWithLogs } from './logs'; import { ABI, encodeSeeds, ProgramDerivedAddress } from './utils'; /** Accounts, signers, and other parameters for calling a contract function or constructor */ export interface ContractCallOptions { payer?: Signer; accounts?: PublicKey[]; writableAccounts?: PublicKey[]; programDerivedAddresses?: ProgramDerivedAddress[]; signers?: Signer[]; sender?: PublicKey | undefined; value?: number | bigint; simulate?: boolean; ed25519sigs?: Ed25519SigCheck[], confirmOptions?: ConfirmOptions; } export interface Ed25519SigCheck { publicKey: PublicKey; message: Uint8Array; signature: Uint8Array; } /** Result of a contract function or constructor call */ export interface ContractCallResult { logs: string[]; events: LogDescription[]; computeUnitsUsed: number; } /** Result of a contract function call */ export interface ContractFunctionResult extends ContractCallResult { result: Result | null; } /** Function that maps to a function declared in the contract ABI */ export type ContractFunction = (...args: any[]) => Promise<ContractFunctionResult | any>; /** Callback function that will be called with decoded events */ export type EventListener = (event: LogDescription) => void; /** Callback function that will be called with raw log messages */ export type LogListener = (message: string) => void; /** A contract represents a Solidity contract that has been compiled with Solang to be deployed on Solana. */ export class Contract { /** Functions that map to the functions declared in the contract ABI */ readonly [name: string]: ContractFunction | any; /** Connection to use */ readonly connection: Connection; /** Account the program is located at (aka Program ID) */ readonly program: PublicKey; /** Account the program's data is stored at */ readonly storage: PublicKey; /** Application Binary Interface in JSON form */ readonly abi: ABI; /** Ethers.js interface parsed from the ABI */ readonly interface: Interface; /** Callable functions mapped to the interface */ readonly functions: Record<string, ContractFunction>; /** Payer for transactions and storage (optional) */ payer: Signer | null; /** @internal */ protected readonly logs: LogsParser; /* * Create a contract. It can either be a new contract to deploy as a Solana program, * or a reference to one already deployed. * * @param connection Connection to use * @param program Account the program is located at (aka Program ID) * @param storage Account the program's data is stored at * @param abi Application Binary Interface in JSON form * @param payer Payer for transactions and storage (optional) */ constructor(connection: Connection, program: PublicKey, storage: PublicKey, abi: ABI, payer: Signer | null = null) { this.connection = connection; this.program = program; this.storage = storage; this.abi = abi; this.interface = new Interface(abi); this.functions = {}; this.payer = payer; this.logs = new LogsParser(this); const uniqueNames: Record<string, string[]> = {}; const uniqueSignatures: Record<string, boolean> = {}; for (const [signature, fragment] of Object.entries(this.interface.functions)) { if (uniqueSignatures[signature]) { console.warn(`Duplicate ABI entry for ${JSON.stringify(signature)}`); return; } uniqueSignatures[signature] = true; const name = fragment.name; if (!uniqueNames[`%${name}`]) { uniqueNames[`%${name}`] = []; } uniqueNames[`%${name}`].push(signature); if (!this.functions[signature]) { defineReadOnly(this.functions, signature, this.buildCall(fragment, false)); } if (typeof this[signature] === 'undefined') { defineReadOnly<any, any>(this, signature, this.buildCall(fragment, true)); } } for (const uniqueName of Object.keys(uniqueNames)) { const signatures = uniqueNames[uniqueName]; if (signatures.length > 1) continue; const signature = signatures[0]; const name = uniqueName.slice(1); if (!this.functions[name]) { defineReadOnly(this.functions, name, this.functions[signature]); } if (typeof this[name] === 'undefined') { defineReadOnly(this, name, this[signature]); } } } /** * Load the contract's BPF bytecode as a Solana program. * * @param program Keypair for the account the program is located at * @param so ELF .so file produced by compiling the contract with Solang * @param payer Payer for transactions and storage (defaults to the payer provided in the constructor) */ async load(program: Signer, so: Buffer, payer?: Signer | null): Promise<void> { if (!program.publicKey.equals(this.program)) throw new InvalidProgramAccountError(); payer ||= this.payer; if (!payer) throw new MissingPayerAccountError(); await BpfLoader.load(this.connection, payer, program, so, BPF_LOADER_PROGRAM_ID); } /** * Deploy the contract to a loaded Solana program. * * @param name Name of the contract to deploy * @param constructorArgs Arguments to pass to the contract's Solidity constructor function * @param program Keypair for the account the program is located at * @param storage Keypair for the account the program's data is stored at * @param space Byte size to allocate for the storage account (this cannot be resized) * @param options Accounts, signers, and other parameters for calling the contract constructor * * @return Result of the contract constructor call */ async deploy( name: string, constructorArgs: any[], program: Signer, storage: Signer, space: number, options?: ContractCallOptions ): Promise<ContractCallResult> { if (!program.publicKey.equals(this.program)) throw new InvalidProgramAccountError(); if (!storage.publicKey.equals(this.storage)) throw new InvalidStorageAccountError(); const payer = options?.payer || this.payer; if (!payer) throw new MissingPayerAccountError(); const { accounts = [], writableAccounts = [], programDerivedAddresses = [], signers = [], sender = payer.publicKey, value = 0, simulate = false, ed25519sigs = [], confirmOptions = { commitment: 'confirmed', skipPreflight: false, preflightCommitment: 'processed', }, } = options ?? {}; const hash = keccak256(Buffer.from(name)); const seeds = programDerivedAddresses.map(({ seed }) => seed); const input = this.interface.encodeDeploy(constructorArgs); const data = Buffer.concat([ // storage account where state for this contract will be stored this.storage.toBuffer(), // msg.sender for this transaction sender.toBuffer(), // lamports to send to payable constructor encodeU64(BigInt(value)), // hash of contract name Buffer.from(hash.substr(2, 8), 'hex'), // PDA seeds encodeSeeds(seeds), // eth abi encoded constructor arguments Buffer.from(input.replace('0x', ''), 'hex'), ]); const keys = [ ...programDerivedAddresses.map(({ address }) => ({ pubkey: address, isSigner: false, isWritable: true, })), { pubkey: this.storage, isSigner: false, isWritable: true, }, { pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false, }, { pubkey: PublicKey.default, isSigner: false, isWritable: false, }, ...accounts.map((pubkey) => ({ pubkey, isSigner: false, isWritable: false, })), ...writableAccounts.map((pubkey) => ({ pubkey, isSigner: false, isWritable: true, })), ]; const lamports = await this.connection.getMinimumBalanceForRentExemption(space, confirmOptions.commitment); const transaction = new Transaction(); if (ed25519sigs.length > 0) { keys.push({ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }); ed25519sigs.forEach(({ publicKey, message, signature }, index) => { transaction.add(Ed25519Program.createInstructionWithPublicKey({ instructionIndex: index, publicKey: publicKey.toBuffer(), message, signature, })); }); } transaction.add( SystemProgram.createAccount({ fromPubkey: payer.publicKey, newAccountPubkey: storage.publicKey, lamports, space, programId: this.program, }), new TransactionInstruction({ keys, programId: this.program, data, }) ); const { logs, computeUnitsUsed } = simulate ? await simulateTransactionWithLogs(this.connection, transaction, [payer, storage, ...signers]) : await sendAndConfirmTransactionWithLogs(this.connection, transaction, [payer, storage, ...signers]); const events = this.parseLogsEvents(logs); return { logs, events, computeUnitsUsed, }; } /** * Set the payer for transactions and storage * * @param payer Payer for transactions and storage * * @return Contract itself (for method chaining) */ connect(payer: Signer): this { this.payer = payer; return this; } /** * Unset the payer for transactions and storage * * @return Contract itself (for method chaining) */ disconnect(): this { this.payer = null; return this; } /** * Add a listener for contract events * * @param listener Callback for contract events * * @return ID of the listener (pass to `removeEventListener` to stop listening) */ addEventListener(listener: EventListener): number { return this.logs.addEventListener(listener); } /** * Remove a listener for contract events * * @param listenerId ID of the listener (returned by `addEventListener`) */ async removeEventListener(listenerId: number): Promise<void> { return await this.logs.removeEventListener(listenerId); } /** * Add a listener for log messages * * @param listener Callback for log messages * * @return ID of the listener (pass to `removeLogListener` to stop listening) */ addLogListener(listener: LogListener): number { return this.logs.addLogListener(listener); } /** * Remove a listener for log messages * * @param listenerId ID of the listener (returned by `addLogListener`) */ async removeLogListener(listenerId: number): Promise<void> { return await this.logs.removeLogListener(listenerId); } /** @internal */ protected parseLogsEvents(logs: string[]): LogDescription[] { const events: LogDescription[] = []; for (const log of logs) { const eventData = parseLogTopic(log); if (eventData) { const event = this.interface.parseLog(eventData); events.push(event); } } return events; } /** @internal */ protected buildCall(fragment: FunctionFragment, returnResult: boolean): ContractFunction { return (...args: any[]) => { const options = args[args.length - 1]; if (args.length > fragment.inputs.length && typeof options === 'object') { return this.call(fragment, returnResult, args.slice(0, fragment.inputs.length), options); } else { return this.call(fragment, returnResult, args); } }; } /** @internal */ protected async call<T extends boolean>( fragment: FunctionFragment, returnResult: T, args: readonly any[], options?: ContractCallOptions ): Promise<T extends true ? any : ContractFunctionResult> { const payer = options?.payer || this.payer; if (!payer) throw new MissingPayerAccountError(); const { accounts = [], writableAccounts = [], programDerivedAddresses = [], signers = [], sender = payer.publicKey, value = 0, simulate = false, ed25519sigs = [], confirmOptions = { commitment: 'confirmed', skipPreflight: false, preflightCommitment: 'processed', }, } = options ?? {}; const seeds = programDerivedAddresses.map(({ seed }) => seed); const input = this.interface.encodeFunctionData(fragment, args); const data = Buffer.concat([ // storage account where state for this contract will be stored this.storage.toBuffer(), // msg.sender for this transaction sender.toBuffer(), // lamports to send to payable constructor encodeU64(BigInt(value)), // hash of contract name, 0 for function calls Buffer.from('00000000', 'hex'), // PDA seeds encodeSeeds(seeds), // eth abi encoded constructor arguments Buffer.from(input.replace('0x', ''), 'hex'), ]); const keys = [ ...programDerivedAddresses.map(({ address }) => ({ pubkey: address, isSigner: false, isWritable: true, })), { pubkey: this.storage, isSigner: false, isWritable: true, }, { pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false, }, { pubkey: PublicKey.default, isSigner: false, isWritable: false, }, ...accounts.map((pubkey) => ({ pubkey, isSigner: false, isWritable: false, })), ...writableAccounts.map((pubkey) => ({ pubkey, isSigner: false, isWritable: true, })), ]; const transaction = new Transaction(); if (ed25519sigs.length > 0) { keys.push({ pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }); ed25519sigs.forEach(({ publicKey, message, signature }, index) => { transaction.add(Ed25519Program.createInstructionWithPublicKey({ instructionIndex: index, publicKey: publicKey.toBuffer(), message, signature, })); }); } transaction.add( new TransactionInstruction({ keys, programId: this.program, data, }) ); // If the function is read-only, simulate the transaction to get the result const { logs, encoded, computeUnitsUsed } = simulate || fragment.stateMutability === 'view' || fragment.stateMutability === 'pure' ? await simulateTransactionWithLogs(this.connection, transaction, [payer, ...signers]) : await sendAndConfirmTransactionWithLogs( this.connection, transaction, [payer, ...signers], confirmOptions ); const events = this.parseLogsEvents(logs); const length = fragment.outputs?.length; let result: Result | null = null; if (length) { if (!encoded) throw new MissingReturnDataError(); if (length == 1) { [result] = this.interface.decodeFunctionResult(fragment, encoded); } else { result = this.interface.decodeFunctionResult(fragment, encoded); } } if (returnResult === true) return result as any; return { result, logs, events, computeUnitsUsed }; } } function encodeU64(num: bigint): Buffer { const buf = Buffer.alloc(8); buf.writeBigUInt64LE(num, 0); return buf; }
the_stack
import { DimensionDefinitionLoose, OptionEncode, OptionEncodeValue, EncodeDefaulter, OptionSourceData, DimensionName, DimensionDefinition, DataVisualDimensions, DimensionIndex, VISUAL_DIMENSIONS } from '../../util/types'; import SeriesDimensionDefine from '../SeriesDimensionDefine'; import { createHashMap, defaults, each, extend, HashMap, isObject, isString } from 'zrender/src/core/util'; import OrdinalMeta from '../OrdinalMeta'; import { createSourceFromSeriesDataOption, isSourceInstance, Source } from '../Source'; import { CtorInt32Array } from '../DataStore'; import { normalizeToArray } from '../../util/model'; import { BE_ORDINAL, guessOrdinal } from './sourceHelper'; import { createDimNameMap, ensureSourceDimNameMap, SeriesDataSchema, shouldOmitUnusedDimensions } from './SeriesDataSchema'; export interface CoordDimensionDefinition extends DimensionDefinition { dimsDef?: (DimensionName | { name: DimensionName, defaultTooltip?: boolean })[]; otherDims?: DataVisualDimensions; ordinalMeta?: OrdinalMeta; coordDim?: DimensionName; coordDimIndex?: DimensionIndex; } export type CoordDimensionDefinitionLoose = CoordDimensionDefinition['name'] | CoordDimensionDefinition; export type PrepareSeriesDataSchemaParams = { coordDimensions?: CoordDimensionDefinitionLoose[], /** * Will use `source.dimensionsDefine` if not given. */ dimensionsDefine?: DimensionDefinitionLoose[], /** * Will use `source.encodeDefine` if not given. */ encodeDefine?: HashMap<OptionEncodeValue, DimensionName> | OptionEncode, dimensionsCount?: number, /** * Make default encode if user not specified. */ encodeDefaulter?: EncodeDefaulter, generateCoord?: string, generateCoordCount?: number, /** * If be able to omit unused dimension * Used to improve the performance on high dimension data. */ canOmitUnusedDimensions?: boolean }; /** * For outside usage compat (like echarts-gl are using it). */ export function createDimensions( source: Source | OptionSourceData, opt?: PrepareSeriesDataSchemaParams ): SeriesDimensionDefine[] { return prepareSeriesDataSchema(source, opt).dimensions; } /** * This method builds the relationship between: * + "what the coord sys or series requires (see `coordDimensions`)", * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)" * + "what the data source provids (see `source`)". * * Some guess strategy will be adapted if user does not define something. * If no 'value' dimension specified, the first no-named dimension will be * named as 'value'. * * @return The results are always sorted by `storeDimIndex` asc. */ export default function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type source: Source | OptionSourceData, opt?: PrepareSeriesDataSchemaParams ): SeriesDataSchema { if (!isSourceInstance(source)) { source = createSourceFromSeriesDataOption(source as OptionSourceData); } opt = opt || {}; const sysDims = opt.coordDimensions || []; const dimsDef = opt.dimensionsDefine || source.dimensionsDefine || []; const coordDimNameMap = createHashMap<true, DimensionName>(); const resultList: SeriesDimensionDefine[] = []; const dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unsed dimensions if sharing a high dimension datastore // 30 is an experience value. const omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount); const isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine; const dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef); let encodeDef = opt.encodeDefine; if (!encodeDef && opt.encodeDefaulter) { encodeDef = opt.encodeDefaulter(source, dimCount); } const encodeDefMap = createHashMap<DimensionIndex[] | false, DimensionName>(encodeDef as any); const indicesMap = new CtorInt32Array(dimCount); for (let i = 0; i < indicesMap.length; i++) { indicesMap[i] = -1; } function getResultItem(dimIdx: number) { const idx = indicesMap[dimIdx]; if (idx < 0) { const dimDefItemRaw = dimsDef[dimIdx]; const dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : { name: dimDefItemRaw }; const resultItem = new SeriesDimensionDefine(); const userDimName = dimDefItem.name; if (userDimName != null && dataDimNameMap.get(userDimName) != null) { // Only if `series.dimensions` is defined in option // displayName, will be set, and dimension will be diplayed vertically in // tooltip by default. resultItem.name = resultItem.displayName = userDimName; } dimDefItem.type != null && (resultItem.type = dimDefItem.type); dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName); const newIdx = resultList.length; indicesMap[dimIdx] = newIdx; resultItem.storeDimIndex = dimIdx; resultList.push(resultItem); return resultItem; } return resultList[idx]; } if (!omitUnusedDimensions) { for (let i = 0; i < dimCount; i++) { getResultItem(i); } } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`. encodeDefMap.each(function (dataDimsRaw, coordDim) { const dataDims = normalizeToArray(dataDimsRaw as []).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is // `{encode: {x: -1, y: 1}}`. Should not filter anything in // this case. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) { encodeDefMap.set(coordDim, false); return; } const validDataDims = encodeDefMap.set(coordDim, []) as DimensionIndex[]; each(dataDims, function (resultDimIdxOrName, idx) { // The input resultDimIdx can be dim name or index. const resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName; if (resultDimIdx != null && resultDimIdx < dimCount) { validDataDims[idx] = resultDimIdx; applyDim(getResultItem(resultDimIdx), coordDim, idx); } }); }); // Apply templetes and default order from `sysDims`. let availDimIdx = 0; each(sysDims, function (sysDimItemRaw) { let coordDim: DimensionName; let sysDimItemDimsDef: CoordDimensionDefinition['dimsDef']; let sysDimItemOtherDims: CoordDimensionDefinition['otherDims']; let sysDimItem: CoordDimensionDefinition; if (isString(sysDimItemRaw)) { coordDim = sysDimItemRaw; sysDimItem = {} as CoordDimensionDefinition; } else { sysDimItem = sysDimItemRaw; coordDim = sysDimItem.name; const ordinalMeta = sysDimItem.ordinalMeta; sysDimItem.ordinalMeta = null; sysDimItem = extend({}, sysDimItem); sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly. sysDimItemDimsDef = sysDimItem.dimsDef; sysDimItemOtherDims = sysDimItem.otherDims; sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null; } let dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping. if (dataDims === false) { return; } dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences. if (!dataDims.length) { for (let i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) { while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) { availDimIdx++; } availDimIdx < dimCount && dataDims.push(availDimIdx++); } } // Apply templates. each(dataDims, function (resultDimIdx, coordDimIndex) { const resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source. if (isUsingSourceDimensionsDef && sysDimItem.type != null) { resultItem.type = sysDimItem.type; } applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex); if (resultItem.name == null && sysDimItemDimsDef) { let sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex]; !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = { name: sysDimItemDimsDefItem }); resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name; resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip; } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}} sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims); }); }); function applyDim(resultItem: SeriesDimensionDefine, coordDim: DimensionName, coordDimIndex: DimensionIndex) { if (VISUAL_DIMENSIONS.get(coordDim as keyof DataVisualDimensions) != null) { resultItem.otherDims[coordDim as keyof DataVisualDimensions] = coordDimIndex; } else { resultItem.coordDim = coordDim; resultItem.coordDimIndex = coordDimIndex; coordDimNameMap.set(coordDim, true); } } // Make sure the first extra dim is 'value'. const generateCoord = opt.generateCoord; let generateCoordCount = opt.generateCoordCount; const fromZero = generateCoordCount != null; generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0; const extra = generateCoord || 'value'; function ifNoNameFillWithCoordName(resultItem: SeriesDimensionDefine): void { if (resultItem.name == null) { // Duplication will be removed in the next step. resultItem.name = resultItem.coordDim; } } // Set dim `name` and other `coordDim` and other props. if (!omitUnusedDimensions) { for (let resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) { const resultItem = getResultItem(resultDimIdx); const coordDim = resultItem.coordDim; if (coordDim == null) { // TODO no need to generate coordDim for isExtraCoord? resultItem.coordDim = genCoordDimName( extra, coordDimNameMap, fromZero ); resultItem.coordDimIndex = 0; // Series specified generateCoord is using out. if (!generateCoord || generateCoordCount <= 0) { resultItem.isExtraCoord = true; } generateCoordCount--; } ifNoNameFillWithCoordName(resultItem); if (resultItem.type == null && ( guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case: // { // dataset: {source: [ // ['2001', 123], // ['2002', 456], // ... // ['The others', 987], // ]}, // series: {type: 'pie'} // } // The first colum should better be treated as a "ordinal" although it // might not able to be detected as an "ordinal" by `guessOrdinal`. || (resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null ) ) ) ) { resultItem.type = 'ordinal'; } } } else { each(resultList, resultItem => { // PENDING: guessOrdinal or let user specify type: 'ordinal' manually? ifNoNameFillWithCoordName(resultItem); }); // Sort dimensions: there are some rule that use the last dim as label, // and for some latter travel process easier. resultList.sort((item0, item1) => item0.storeDimIndex - item1.storeDimIndex); } removeDuplication(resultList); return new SeriesDataSchema({ source, dimensions: resultList, fullDimensionCount: dimCount, dimensionOmitted: omitUnusedDimensions }); } function removeDuplication(result: SeriesDimensionDefine[]) { const duplicationMap = createHashMap<number>(); for (let i = 0; i < result.length; i++) { const dim = result[i]; const dimOriginalName = dim.name; let count = duplicationMap.get(dimOriginalName) || 0; if (count > 0) { // Starts from 0. dim.name = dimOriginalName + (count - 1); } count++; duplicationMap.set(dimOriginalName, count); } } // ??? TODO // Originally detect dimCount by data[0]. Should we // optimize it to only by sysDims and dimensions and encode. // So only necessary dims will be initialized. // But // (1) custom series should be considered. where other dims // may be visited. // (2) sometimes user need to calcualte bubble size or use visualMap // on other dimensions besides coordSys needed. // So, dims that is not used by system, should be shared in data store? function getDimCount( source: Source, sysDims: CoordDimensionDefinitionLoose[], dimsDef: DimensionDefinitionLoose[], optDimCount?: number ): number { // Note that the result dimCount should not small than columns count // of data, otherwise `dataDimNameMap` checking will be incorrect. let dimCount = Math.max( source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0 ); each(sysDims, function (sysDimItem) { let sysDimItemDimsDef; if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) { dimCount = Math.max(dimCount, sysDimItemDimsDef.length); } }); return dimCount; } function genCoordDimName( name: DimensionName, map: HashMap<unknown, DimensionName>, fromZero: boolean ) { const mapData = map.data; if (fromZero || mapData.hasOwnProperty(name)) { let i = 0; while (mapData.hasOwnProperty(name + i)) { i++; } name += i; } map.set(name, true); return name; }
the_stack
import { concat } from '@ethersproject/bytes'; import blake from 'blakejs'; import { Option } from './option'; import { decodeBase16, encodeBase16 } from './Conversions'; import humanizeDuration from 'humanize-duration'; import { CLTypedAndToBytesHelper, CLTypeHelper, CLValue, PublicKey, ToBytes, U32 } from './CLValue'; import { toBytesArrayU8, toBytesBytesArray, toBytesDeployHash, toBytesString, toBytesU64, toBytesVecT, toBytesU32 } from './byterepr'; import { RuntimeArgs } from './RuntimeArgs'; // import JSBI from 'jsbi'; import { DeployUtil, Keys, URef } from './index'; import { AsymmetricKey, SignatureAlgorithm } from './Keys'; import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; import { jsonArrayMember, jsonMember, jsonObject, TypedJSON } from 'typedjson'; import { ByteArray } from 'tweetnacl-ts'; import { Result, Ok, Err } from 'ts-results'; const shortEnglishHumanizer = humanizeDuration.humanizer({ spacer: '', serialComma: false, conjunction: ' ', delimiter: ' ', language: 'shortEn', languages: { // https://docs.rs/humantime/2.0.1/humantime/fn.parse_duration.html shortEn: { d: () => 'day', h: () => 'h', m: () => 'm', s: () => 's', ms: () => 'ms' } } }); const byteArrayJsonSerializer: (bytes: Uint8Array) => string = ( bytes: Uint8Array ) => { return encodeBase16(bytes); }; const byteArrayJsonDeserializer: (str: string) => Uint8Array = ( str: string ) => { return decodeBase16(str); }; /** * Returns a humanizer duration * @param ttl in milliseconds */ export const humanizerTTL = (ttl: number) => { return shortEnglishHumanizer(ttl); }; /** * Returns duration in ms * @param ttl in humanized string */ export const dehumanizerTTL = (ttl: string): number => { const dehumanizeUnit = (s: string): number => { if (s.includes('ms')) { return Number(s.replace('ms', '')); } if (s.includes('s') && !s.includes('m')) { return Number(s.replace('s', '')) * 1000; } if (s.includes('m') && !s.includes('s')) { return Number(s.replace('m', '')) * 60 * 1000; } if (s.includes('h')) { return Number(s.replace('h', '')) * 60 * 60 * 1000; } if (s.includes('day')) { return Number(s.replace('day', '')) * 24 * 60 * 60 * 1000; } throw Error('Unsuported TTL unit'); }; return ttl .split(' ') .map(dehumanizeUnit) .reduce((acc, val) => (acc += val)); }; export class UniqAddress { publicKey: PublicKey; transferId: BigNumber; /** * Constructs UniqAddress * @param publicKey PublicKey instance * @param transferId BigNumberish value (can be also string representing number). Max U64. */ constructor(publicKey: PublicKey, transferId: BigNumberish) { if (!(publicKey instanceof PublicKey)) { throw new Error('publicKey is not an instance of PublicKey'); } const bigNum = BigNumber.from(transferId); if (bigNum.gt('18446744073709551615')) { throw new Error('transferId max value is U64'); } this.transferId = bigNum; this.publicKey = publicKey; } /** * Returns string in format "accountHex-transferIdHex" * @param ttl in humanized string */ toString(): string { return `${this.publicKey.toAccountHex()}-${this.transferId.toHexString()}`; } /** * Builds UniqAddress from string * @param value value returned from UniqAddress.toString() */ static fromString(value: string): UniqAddress { const [accountHex, transferHex] = value.split('-'); const publicKey = PublicKey.fromHex(accountHex); return new UniqAddress(publicKey, transferHex); } } @jsonObject export class DeployHeader implements ToBytes { @jsonMember({ serializer: (account: PublicKey) => { return account.toAccountHex(); }, deserializer: (hexStr: string) => { return PublicKey.fromHex(hexStr); } }) public account: PublicKey; @jsonMember({ serializer: (n: number) => new Date(n).toISOString(), deserializer: (s: string) => Date.parse(s) }) public timestamp: number; @jsonMember({ serializer: humanizerTTL, deserializer: dehumanizerTTL }) public ttl: number; @jsonMember({ constructor: Number, name: 'gas_price' }) public gasPrice: number; @jsonMember({ name: 'body_hash', serializer: byteArrayJsonSerializer, deserializer: byteArrayJsonDeserializer }) public bodyHash: Uint8Array; @jsonArrayMember(ByteArray, { serializer: (value: Uint8Array[]) => value.map(it => byteArrayJsonSerializer(it)), deserializer: (json: any) => json.map((it: string) => byteArrayJsonDeserializer(it)) }) public dependencies: Uint8Array[]; @jsonMember({ name: 'chain_name', constructor: String }) public chainName: string; /** * The header portion of a Deploy * * @param account The account within which the deploy will be run. * @param timestamp When the deploy was created. * @param ttl How long the deploy will stay valid. * @param gasPrice Price per gas unit for this deploy. * @param bodyHash Hash of the Wasm code. * @param dependencies Other deploys that have to be run before this one. * @param chainName Which chain the deploy is supposed to be run on. */ constructor( account: PublicKey, timestamp: number, ttl: number, gasPrice: number, bodyHash: Uint8Array, dependencies: Uint8Array[], chainName: string ) { this.account = account; this.timestamp = timestamp; this.ttl = ttl; this.gasPrice = gasPrice; this.bodyHash = bodyHash; this.dependencies = dependencies; this.chainName = chainName; } public toBytes(): Uint8Array { return concat([ this.account.toBytes(), toBytesU64(this.timestamp), toBytesU64(this.ttl), toBytesU64(this.gasPrice), toBytesDeployHash(this.bodyHash), toBytesVecT(this.dependencies.map(d => new DeployHash(d))), toBytesString(this.chainName) ]); } } /** * The cryptographic hash of a Deploy. */ class DeployHash implements ToBytes { constructor(private hash: Uint8Array) {} public toBytes(): Uint8Array { return toBytesDeployHash(this.hash); } } export interface DeployJson { session: Record<string, any>; approvals: { signature: string; signer: string }[]; header: DeployHeader; payment: Record<string, any>; hash: string; } /** * A struct containing a signature and the public key of the signer. */ @jsonObject export class Approval { @jsonMember({ constructor: String }) public signer: string; @jsonMember({ constructor: String }) public signature: string; } abstract class ExecutableDeployItemInternal implements ToBytes { public abstract tag: number; public abstract args: RuntimeArgs; public abstract toBytes(): Uint8Array; public getArgByName(name: string): CLValue | undefined { return this.args.args.get(name); } public setArg(name: string, value: CLValue) { this.args.args.set(name, value); } } const desRA = (arr: any) => { const raSerializer = new TypedJSON(RuntimeArgs); const value = { args: arr }; return raSerializer.parse(value); }; const serRA = (ra: RuntimeArgs) => { const raSerializer = new TypedJSON(RuntimeArgs); const json = raSerializer.toPlainJson(ra); return Object.values(json as any)[0]; }; @jsonObject export class ModuleBytes extends ExecutableDeployItemInternal { public tag = 0; @jsonMember({ name: 'module_bytes', serializer: byteArrayJsonSerializer, deserializer: byteArrayJsonDeserializer }) public moduleBytes: Uint8Array; @jsonMember({ deserializer: desRA, serializer: serRA }) public args: RuntimeArgs; constructor(moduleBytes: Uint8Array, args: RuntimeArgs) { super(); this.moduleBytes = moduleBytes; this.args = args; } public toBytes(): Uint8Array { return concat([ Uint8Array.from([this.tag]), toBytesArrayU8(this.moduleBytes), toBytesBytesArray(this.args.toBytes()) ]); } } @jsonObject export class StoredContractByHash extends ExecutableDeployItemInternal { public tag = 1; @jsonMember({ serializer: byteArrayJsonSerializer, deserializer: byteArrayJsonDeserializer }) public hash: Uint8Array; @jsonMember({ name: 'entry_point', constructor: String }) public entryPoint: string; @jsonMember({ deserializer: desRA, serializer: serRA }) public args: RuntimeArgs; constructor(hash: Uint8Array, entryPoint: string, args: RuntimeArgs) { super(); this.entryPoint = entryPoint; this.args = args; this.hash = hash; } public toBytes(): Uint8Array { return concat([ Uint8Array.from([this.tag]), toBytesBytesArray(this.hash), toBytesString(this.entryPoint), toBytesBytesArray(this.args.toBytes()) ]); } } @jsonObject export class StoredContractByName extends ExecutableDeployItemInternal { public tag = 2; @jsonMember({ constructor: String }) public name: string; @jsonMember({ name: 'entry_point', constructor: String }) public entryPoint: string; @jsonMember({ deserializer: desRA, serializer: serRA }) public args: RuntimeArgs; constructor(name: string, entryPoint: string, args: RuntimeArgs) { super(); this.name = name; this.entryPoint = entryPoint; this.args = args; } public toBytes(): Uint8Array { return concat([ Uint8Array.from([this.tag]), toBytesString(this.name), toBytesString(this.entryPoint), toBytesBytesArray(this.args.toBytes()) ]); } } @jsonObject export class StoredVersionedContractByName extends ExecutableDeployItemInternal { public tag = 4; @jsonMember({ constructor: String }) public name: string; @jsonMember({ constructor: Number, preserveNull: true }) public version: number | null; @jsonMember({ name: 'entry_point', constructor: String }) public entryPoint: string; @jsonMember({ deserializer: desRA, serializer: serRA }) public args: RuntimeArgs; constructor( name: string, version: number | null, entryPoint: string, args: RuntimeArgs ) { super(); this.name = name; this.version = version; this.entryPoint = entryPoint; this.args = args; } public toBytes(): Uint8Array { let serializedVersion; if (this.version === null) { serializedVersion = new Option(null, CLTypeHelper.u32()); } else { serializedVersion = new Option(new U32(this.version as number)); } return concat([ Uint8Array.from([this.tag]), toBytesString(this.name), serializedVersion.toBytes(), toBytesString(this.entryPoint), toBytesBytesArray(this.args.toBytes()) ]); } } @jsonObject export class StoredVersionedContractByHash extends ExecutableDeployItemInternal { public tag = 3; @jsonMember({ serializer: byteArrayJsonSerializer, deserializer: byteArrayJsonDeserializer }) public hash: Uint8Array; @jsonMember({ constructor: Number, preserveNull: true }) public version: number | null; @jsonMember({ name: 'entry_point', constructor: String }) public entryPoint: string; @jsonMember({ deserializer: desRA, serializer: serRA }) public args: RuntimeArgs; constructor( hash: Uint8Array, version: number | null, entryPoint: string, args: RuntimeArgs ) { super(); this.hash = hash; this.version = version; this.entryPoint = entryPoint; this.args = args; } public toBytes(): Uint8Array { let serializedVersion; if (this.version === null) { serializedVersion = new Option(null, CLTypeHelper.u32()); } else { serializedVersion = new Option(new U32(this.version as number)); } return concat([ Uint8Array.from([this.tag]), toBytesBytesArray(this.hash), serializedVersion.toBytes(), toBytesString(this.entryPoint), toBytesBytesArray(this.args.toBytes()) ]); } } @jsonObject export class Transfer extends ExecutableDeployItemInternal { public tag = 5; @jsonMember({ deserializer: desRA, serializer: serRA }) public args: RuntimeArgs; /** * Constructor for Transfer deploy item. * @param amount The number of motes to transfer * @param target URef of the target purse or the public key of target account. You could generate this public key from accountHex by PublicKey.fromHex * @param sourcePurse URef of the source purse. If this is omitted, the main purse of the account creating this \ * transfer will be used as the source purse * @param id user-defined transfer id */ constructor(args: RuntimeArgs) { super(); this.args = args; } public toBytes(): Uint8Array { return concat([ Uint8Array.from([this.tag]), toBytesBytesArray(this.args.toBytes()) ]); } } @jsonObject export class ExecutableDeployItem implements ToBytes { @jsonMember({ name: 'ModuleBytes', constructor: ModuleBytes }) public moduleBytes?: ModuleBytes; @jsonMember({ name: 'StoredContractByHash', constructor: StoredContractByHash }) public storedContractByHash?: StoredContractByHash; @jsonMember({ name: 'StoredContractByName', constructor: StoredContractByName }) public storedContractByName?: StoredContractByName; @jsonMember({ name: 'StoredVersionedContractByHash', constructor: StoredVersionedContractByHash }) public storedVersionedContractByHash?: StoredVersionedContractByHash; @jsonMember({ name: 'StoredVersionedContractByName', constructor: StoredVersionedContractByName }) public storedVersionedContractByName?: StoredVersionedContractByName; @jsonMember({ name: 'Transfer', constructor: Transfer }) public transfer?: Transfer; public toBytes(): Uint8Array { if (this.isModuleBytes()) { return this.moduleBytes!.toBytes(); } else if (this.isStoredContractByHash()) { return this.storedContractByHash!.toBytes(); } else if (this.isStoredContractByName()) { return this.storedContractByName!.toBytes(); } else if (this.isStoredVersionContractByHash()) { return this.storedVersionedContractByHash!.toBytes(); } else if (this.isStoredVersionContractByName()) { return this.storedVersionedContractByName!.toBytes(); } else if (this.isTransfer()) { return this.transfer!.toBytes(); } throw new Error('failed to serialize ExecutableDeployItemJsonWrapper'); } public getArgByName(name: string): CLValue | undefined { if (this.isModuleBytes()) { return this.moduleBytes!.getArgByName(name); } else if (this.isStoredContractByHash()) { return this.storedContractByHash!.getArgByName(name); } else if (this.isStoredContractByName()) { return this.storedContractByName!.getArgByName(name); } else if (this.isStoredVersionContractByHash()) { return this.storedVersionedContractByHash!.getArgByName(name); } else if (this.isStoredVersionContractByName()) { return this.storedVersionedContractByName!.getArgByName(name); } else if (this.isTransfer()) { return this.transfer!.getArgByName(name); } throw new Error('failed to serialize ExecutableDeployItemJsonWrapper'); } public setArg(name: string, value: CLValue) { if (this.isModuleBytes()) { return this.moduleBytes!.setArg(name, value); } else if (this.isStoredContractByHash()) { return this.storedContractByHash!.setArg(name, value); } else if (this.isStoredContractByName()) { return this.storedContractByName!.setArg(name, value); } else if (this.isStoredVersionContractByHash()) { return this.storedVersionedContractByHash!.setArg(name, value); } else if (this.isStoredVersionContractByName()) { return this.storedVersionedContractByName!.setArg(name, value); } else if (this.isTransfer()) { return this.transfer!.setArg(name, value); } throw new Error('failed to serialize ExecutableDeployItemJsonWrapper'); } public static fromExecutableDeployItemInternal( item: ExecutableDeployItemInternal ) { const res = new ExecutableDeployItem(); switch (item.tag) { case 0: res.moduleBytes = item as ModuleBytes; break; case 1: res.storedContractByHash = item as StoredContractByHash; break; case 2: res.storedContractByName = item as StoredContractByName; break; case 3: res.storedVersionedContractByHash = item as StoredVersionedContractByHash; break; case 4: res.storedVersionedContractByName = item as StoredVersionedContractByName; break; case 5: res.transfer = item as Transfer; break; } return res; } public static newModuleBytes( moduleBytes: Uint8Array, args: RuntimeArgs ): ExecutableDeployItem { return ExecutableDeployItem.fromExecutableDeployItemInternal( new ModuleBytes(moduleBytes, args) ); } public static newStoredContractByHash( hash: Uint8Array, entryPoint: string, args: RuntimeArgs ) { return ExecutableDeployItem.fromExecutableDeployItemInternal( new StoredContractByHash(hash, entryPoint, args) ); } public static newStoredContractByName( name: string, entryPoint: string, args: RuntimeArgs ) { return ExecutableDeployItem.fromExecutableDeployItemInternal( new StoredContractByName(name, entryPoint, args) ); } public static newStoredVersionContractByHash( hash: Uint8Array, version: number | null, entryPoint: string, args: RuntimeArgs ) { return ExecutableDeployItem.fromExecutableDeployItemInternal( new StoredVersionedContractByHash(hash, version, entryPoint, args) ); } public static newStoredVersionContractByName( name: string, version: number | null, entryPoint: string, args: RuntimeArgs ) { return ExecutableDeployItem.fromExecutableDeployItemInternal( new StoredVersionedContractByName(name, version, entryPoint, args) ); } /** * Constructor for Transfer deploy item. * @param amount The number of motes to transfer * @param target URef of the target purse or the public key of target account. You could generate this public key from accountHex by PublicKey.fromHex * @param sourcePurse URef of the source purse. If this is omitted, the main purse of the account creating this \ * transfer will be used as the source purse * @param id user-defined transfer id. This parameter is required. */ public static newTransfer( amount: BigNumberish, target: URef | PublicKey, sourcePurse: URef | null = null, id: BigNumberish ) { const runtimeArgs = RuntimeArgs.fromMap({}); runtimeArgs.insert('amount', CLValue.u512(amount)); if (sourcePurse) { runtimeArgs.insert('source', CLValue.uref(sourcePurse)); } if (target instanceof URef) { runtimeArgs.insert('target', CLValue.uref(target)); } else if (target instanceof PublicKey) { runtimeArgs.insert('target', CLValue.byteArray(target.toAccountHash())); } else { throw new Error('Please specify target'); } if (id === undefined) { throw new Error('transfer-id missing in new transfer.'); } else { runtimeArgs.insert( 'id', CLValue.option(CLTypedAndToBytesHelper.u64(id), CLTypeHelper.u64()) ); } return ExecutableDeployItem.fromExecutableDeployItemInternal( new Transfer(runtimeArgs) ); } // TODO: Abstract the logic of this and newTransfer so there won't be so much redundancy. /** * Constructor for Transfer deploy item without obligatory transfer-id. * @param amount The number of motes to transfer * @param target URef of the target purse or the public key of target account. You could generate this public key from accountHex by PublicKey.fromHex * @param sourcePurse URef of the source purse. If this is omitted, the main purse of the account creating this \ * transfer will be used as the source purse * @param id user-defined transfer id. This parameter is optional. */ public static newTransferWithOptionalTransferId( amount: BigNumberish, target: URef | PublicKey, sourcePurse?: URef | null, id?: BigNumberish ) { const runtimeArgs = RuntimeArgs.fromMap({}); runtimeArgs.insert('amount', CLValue.u512(amount)); if (sourcePurse) { runtimeArgs.insert('source', CLValue.uref(sourcePurse)); } if (target instanceof URef) { runtimeArgs.insert('target', CLValue.uref(target)); } else if (target instanceof PublicKey) { runtimeArgs.insert('target', CLValue.byteArray(target.toAccountHash())); } else { throw new Error('Please specify target'); } if (id !== undefined && id !== null) { runtimeArgs.insert( 'id', CLValue.option(CLTypedAndToBytesHelper.u64(id), CLTypeHelper.u64()) ); } else { runtimeArgs.insert('id', CLValue.option(null, CLTypeHelper.u64())); } return ExecutableDeployItem.fromExecutableDeployItemInternal( new Transfer(runtimeArgs) ); } /** * Constructor for Transfer deploy item using UniqAddress. * @param source PublicKey of source account * @param target UniqAddress of target account * @param amount The number of motes to transfer * @param paymentAmount the number of motes paying to execution engine * @param chainName Name of the chain, to avoid the `Deploy` from being accidentally or maliciously included in a different chain. * @param gasPrice Conversion rate between the cost of Wasm opcodes and the motes sent by the payment code. * @param ttl Time that the `Deploy` will remain valid for, in milliseconds. The default value is 1800000, which is 30 minutes * @param sourcePurse URef of the source purse. If this is omitted, the main purse of the account creating this \ * transfer will be used as the source purse */ public static newTransferToUniqAddress( source: PublicKey, target: UniqAddress, amount: BigNumberish, paymentAmount: BigNumberish, chainName: string, gasPrice = 1, ttl = 1800000, sourcePurse?: URef ): Deploy { const deployParams = new DeployUtil.DeployParams( source, chainName, gasPrice, ttl ); const payment = DeployUtil.standardPayment(paymentAmount); const session = DeployUtil.ExecutableDeployItem.newTransfer( amount, target.publicKey, sourcePurse, target.transferId ); return DeployUtil.makeDeploy(deployParams, session, payment); } public isModuleBytes(): boolean { return !!this.moduleBytes; } public asModuleBytes(): ModuleBytes | undefined { return this.moduleBytes; } public isStoredContractByHash(): boolean { return !!this.storedContractByHash; } public asStoredContractByHash(): StoredContractByHash | undefined { return this.storedContractByHash; } public isStoredContractByName(): boolean { return !!this.storedContractByName; } public asStoredContractByName(): StoredContractByName | undefined { return this.storedContractByName; } public isStoredVersionContractByName(): boolean { return !!this.storedVersionedContractByName; } public asStoredVersionContractByName(): | StoredVersionedContractByName | undefined { return this.storedVersionedContractByName; } public isStoredVersionContractByHash(): boolean { return !!this.storedVersionedContractByHash; } public asStoredVersionContractByHash(): | StoredVersionedContractByHash | undefined { return this.storedVersionedContractByHash; } public isTransfer() { return !!this.transfer; } public asTransfer(): Transfer | undefined { return this.transfer; } } /** * A deploy containing a smart contract along with the requester's signature(s). */ @jsonObject export class Deploy { @jsonMember({ serializer: byteArrayJsonSerializer, deserializer: byteArrayJsonDeserializer }) public hash: Uint8Array; @jsonMember({ constructor: DeployHeader }) public header: DeployHeader; @jsonMember({ constructor: ExecutableDeployItem }) public payment: ExecutableDeployItem; @jsonMember({ constructor: ExecutableDeployItem }) public session: ExecutableDeployItem; @jsonArrayMember(Approval) public approvals: Approval[]; /** * * @param hash The DeployHash identifying this Deploy * @param header The deployHeader * @param payment The ExecutableDeployItem for payment code. * @param session the ExecutableDeployItem for session code. * @param approvals An array of signature and public key of the signers, who approve this deploy */ constructor( hash: Uint8Array, header: DeployHeader, payment: ExecutableDeployItem, session: ExecutableDeployItem, approvals: Approval[] ) { this.approvals = approvals; this.session = session; this.payment = payment; this.header = header; this.hash = hash; } public isTransfer(): boolean { return this.session.isTransfer(); } public isStandardPayment(): boolean { if (this.payment.isModuleBytes()) { return this.payment.asModuleBytes()?.moduleBytes.length === 0; } return false; } } /** * Serialize deployHeader into a array of bytes * @param deployHeader */ export const serializeHeader = (deployHeader: DeployHeader): Uint8Array => { return deployHeader.toBytes(); }; /** * Serialize deployBody into a array of bytes * @param payment * @param session */ export const serializeBody = ( payment: ExecutableDeployItem, session: ExecutableDeployItem ): Uint8Array => { return concat([payment.toBytes(), session.toBytes()]); }; export const serializeApprovals = (approvals: Approval[]): Uint8Array => { const len = toBytesU32(approvals.length); const bytes = concat( approvals.map(approval => { return concat([ Uint8Array.from(Buffer.from(approval.signer, 'hex')), Uint8Array.from(Buffer.from(approval.signature, 'hex')) ]); }) ); return concat([len, bytes]); }; /** * Supported contract type */ export enum ContractType { WASM = 'WASM', Hash = 'Hash', Name = 'Name' } export class DeployParams { /** * Container for `Deploy` construction options. * @param accountPublicKey * @param chainName Name of the chain, to avoid the `Deploy` from being accidentally or maliciously included in a different chain. * @param gasPrice Conversion rate between the cost of Wasm opcodes and the motes sent by the payment code. * @param ttl Time that the `Deploy` will remain valid for, in milliseconds. The default value is 1800000, which is 30 minutes * @param dependencies Hex-encoded `Deploy` hashes of deploys which must be executed before this one. * @param timestamp If `timestamp` is empty, the current time will be used. Note that timestamp is UTC, not local. */ constructor( public accountPublicKey: PublicKey, public chainName: string, public gasPrice: number = 1, public ttl: number = 1800000, public dependencies: Uint8Array[] = [], public timestamp?: number ) { this.dependencies = dependencies.filter( d => dependencies.filter(t => encodeBase16(d) === encodeBase16(t)).length < 2 ); if (!timestamp) { this.timestamp = Date.now(); } } } /** * Makes Deploy message */ export function makeDeploy( deployParam: DeployParams, session: ExecutableDeployItem, payment: ExecutableDeployItem ): Deploy { const serializedBody = serializeBody(payment, session); const bodyHash = blake.blake2b(serializedBody, null, 32); const header: DeployHeader = new DeployHeader( deployParam.accountPublicKey, deployParam.timestamp!, deployParam.ttl, deployParam.gasPrice, bodyHash, deployParam.dependencies, deployParam.chainName ); const serializedHeader = serializeHeader(header); const deployHash = blake.blake2b(serializedHeader, null, 32); return new Deploy(deployHash, header, payment, session, []); } /** * Uses the provided key pair to sign the Deploy message * * @param deploy * @param signingKey the keyPair to sign deploy */ export const signDeploy = ( deploy: Deploy, signingKey: AsymmetricKey ): Deploy => { const approval = new Approval(); const signature = signingKey.sign(deploy.hash); approval.signer = signingKey.accountHex(); switch (signingKey.signatureAlgorithm) { case SignatureAlgorithm.Ed25519: approval.signature = Keys.Ed25519.accountHex(signature); break; case SignatureAlgorithm.Secp256K1: approval.signature = Keys.Secp256K1.accountHex(signature); break; } deploy.approvals.push(approval); return deploy; }; /** * Sets the already generated Ed25519 signature for the Deploy message * * @param deploy * @param sig the Ed25519 signature * @param publicKey the public key used to generate the Ed25519 signature */ export const setSignature = ( deploy: Deploy, sig: Uint8Array, publicKey: PublicKey ): Deploy => { const approval = new Approval(); approval.signer = publicKey.toAccountHex(); switch (publicKey.signatureAlgorithm()) { case SignatureAlgorithm.Ed25519: approval.signature = Keys.Ed25519.accountHex(sig); break; case SignatureAlgorithm.Secp256K1: approval.signature = Keys.Secp256K1.accountHex(sig); break; } deploy.approvals.push(approval); return deploy; }; /** * Standard payment code. * * @param paymentAmount the number of motes paying to execution engine */ export const standardPayment = (paymentAmount: BigNumberish) => { const paymentArgs = RuntimeArgs.fromMap({ amount: CLValue.u512(paymentAmount.toString()) }); return ExecutableDeployItem.newModuleBytes(Uint8Array.from([]), paymentArgs); }; /** * Convert the deploy object to json * * @param deploy */ export const deployToJson = (deploy: Deploy) => { const serializer = new TypedJSON(Deploy); return { deploy: serializer.toPlainJson(deploy) }; }; /** * Convert the json to deploy object * * @param json */ export const deployFromJson = (json: any) => { const serializer = new TypedJSON(Deploy); const deploy = serializer.parse(json.deploy); if (deploy !== undefined && validateDeploy(deploy).ok) { return deploy; } return undefined; }; export const addArgToDeploy = ( deploy: Deploy, name: string, value: CLValue ): Deploy => { if (deploy.approvals.length !== 0) { throw Error('Can not add argument to already signed deploy.'); } const deployParams = new DeployUtil.DeployParams( deploy.header.account, deploy.header.chainName, deploy.header.gasPrice, deploy.header.ttl, deploy.header.dependencies, deploy.header.timestamp ); const session = deploy.session; session.setArg(name, value); return makeDeploy(deployParams, session, deploy.payment); }; export const deploySizeInBytes = (deploy: Deploy): number => { const hashSize = deploy.hash.length; const bodySize = serializeBody(deploy.payment, deploy.session).length; const headerSize = serializeHeader(deploy.header).length; const approvalsSize = deploy.approvals .map(approval => { return (approval.signature.length + approval.signer.length) / 2; }) .reduce((a, b) => a + b, 0); return hashSize + headerSize + bodySize + approvalsSize; }; export const validateDeploy = (deploy: Deploy): Result<Deploy, string> => { const serializedBody = serializeBody(deploy.payment, deploy.session); const bodyHash = blake.blake2b(serializedBody, null, 32); if (!arrayEquals(deploy.header.bodyHash, bodyHash)) { return Err(`Invalid deploy: bodyHash missmatch. Expected: ${bodyHash}, got: ${deploy.header.bodyHash}.`); } const serializedHeader = serializeHeader(deploy.header); const deployHash = blake.blake2b(serializedHeader, null, 32); if (!arrayEquals(deploy.hash, deployHash)) { return Err(`Invalid deploy: hash missmatch. Expected: ${deployHash}, got: ${deploy.hash}.`); } // TODO: Verify included signatures. return Ok(deploy); }; const arrayEquals = (a: Uint8Array, b: Uint8Array): boolean => { return a.length === b.length && a.every((val, index) => val === b[index]); }; export const deployToBytes = (deploy: Deploy): Uint8Array => { return concat([ serializeHeader(deploy.header), deploy.hash, serializeBody(deploy.payment, deploy.session), serializeApprovals(deploy.approvals) ]); };
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent, HttpParameterCodec, HttpContext } from '@angular/common/http'; import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; // @ts-ignore import { ChannelDetailsDto } from '../model/channelDetailsDto'; // @ts-ignore import { ChannelSummaryDto } from '../model/channelSummaryDto'; // @ts-ignore import { ChannelsVm } from '../model/channelsVm'; // @ts-ignore import { CreateChannelCommand } from '../model/createChannelCommand'; // @ts-ignore import { GetChannelLogsVm } from '../model/getChannelLogsVm'; // @ts-ignore import { UpdateChannelCommand } from '../model/updateChannelCommand'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; @Injectable({ providedIn: 'root' }) export class ChannelService { protected basePath = 'http://localhost'; public defaultHeaders = new HttpHeaders(); public configuration = new Configuration(); public encoder: HttpParameterCodec; constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { if (typeof basePath !== 'string') { basePath = this.basePath; } this.configuration.basePath = basePath; } this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); } private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { if (typeof value === "object" && value instanceof Date === false) { httpParams = this.addToHttpParamsRecursive(httpParams, value); } else { httpParams = this.addToHttpParamsRecursive(httpParams, value, key); } return httpParams; } private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { if (value == null) { return httpParams; } if (typeof value === "object") { if (Array.isArray(value)) { (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); } else if (value instanceof Date) { if (key != null) { httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); } else { throw Error("key may not be null if value is Date"); } } else { Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( httpParams, value[k], key != null ? `${key}.${k}` : k)); } } else if (key != null) { httpParams = httpParams.append(key, value); } else { throw Error("key may not be null if value is not object or array"); } return httpParams; } /** * @param channelId * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelChannelIdGet(channelId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<ChannelSummaryDto>; public apiChannelChannelIdGet(channelId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpResponse<ChannelSummaryDto>>; public apiChannelChannelIdGet(channelId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpEvent<ChannelSummaryDto>>; public apiChannelChannelIdGet(channelId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<any> { if (channelId === null || channelId === undefined) { throw new Error('Required parameter channelId was null or undefined when calling apiChannelChannelIdGet.'); } let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'text/plain', 'application/json', 'text/json' ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.get<ChannelSummaryDto>(`${this.configuration.basePath}/api/channel/${encodeURIComponent(String(channelId))}`, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } /** * @param channelId * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelChannelIdOverviewGet(channelId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<ChannelDetailsDto>; public apiChannelChannelIdOverviewGet(channelId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpResponse<ChannelDetailsDto>>; public apiChannelChannelIdOverviewGet(channelId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpEvent<ChannelDetailsDto>>; public apiChannelChannelIdOverviewGet(channelId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<any> { if (channelId === null || channelId === undefined) { throw new Error('Required parameter channelId was null or undefined when calling apiChannelChannelIdOverviewGet.'); } let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'text/plain', 'application/json', 'text/json' ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.get<ChannelDetailsDto>(`${this.configuration.basePath}/api/channel/${encodeURIComponent(String(channelId))}/overview`, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } /** * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelExportGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>; public apiChannelExportGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>; public apiChannelExportGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>; public apiChannelExportGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> { let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.get<any>(`${this.configuration.basePath}/api/channel/export`, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } /** * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<ChannelsVm>; public apiChannelGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpResponse<ChannelsVm>>; public apiChannelGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpEvent<ChannelsVm>>; public apiChannelGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<any> { let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'text/plain', 'application/json', 'text/json' ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.get<ChannelsVm>(`${this.configuration.basePath}/api/channel`, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } /** * @param id * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelIdDelete(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>; public apiChannelIdDelete(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>; public apiChannelIdDelete(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>; public apiChannelIdDelete(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling apiChannelIdDelete.'); } let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.delete<any>(`${this.configuration.basePath}/api/channel/${encodeURIComponent(String(id))}`, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } /** * @param id * @param updateChannelCommand * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelIdPut(id: string, updateChannelCommand?: UpdateChannelCommand, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>; public apiChannelIdPut(id: string, updateChannelCommand?: UpdateChannelCommand, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>; public apiChannelIdPut(id: string, updateChannelCommand?: UpdateChannelCommand, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>; public apiChannelIdPut(id: string, updateChannelCommand?: UpdateChannelCommand, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling apiChannelIdPut.'); } let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } // to determine the Content-Type header const consumes: string[] = [ 'application/json', 'text/json', 'application/_*+json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.put<any>(`${this.configuration.basePath}/api/channel/${encodeURIComponent(String(id))}`, updateChannelCommand, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } /** * @param channelId * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelLogsChannelIdGet(channelId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<GetChannelLogsVm>; public apiChannelLogsChannelIdGet(channelId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpResponse<GetChannelLogsVm>>; public apiChannelLogsChannelIdGet(channelId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpEvent<GetChannelLogsVm>>; public apiChannelLogsChannelIdGet(channelId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<any> { if (channelId === null || channelId === undefined) { throw new Error('Required parameter channelId was null or undefined when calling apiChannelLogsChannelIdGet.'); } let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'text/plain', 'application/json', 'text/json' ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.get<GetChannelLogsVm>(`${this.configuration.basePath}/api/channel/logs/${encodeURIComponent(String(channelId))}`, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } /** * @param createChannelCommand * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public apiChannelPost(createChannelCommand?: CreateChannelCommand, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<string>; public apiChannelPost(createChannelCommand?: CreateChannelCommand, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpResponse<string>>; public apiChannelPost(createChannelCommand?: CreateChannelCommand, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<HttpEvent<string>>; public apiChannelPost(createChannelCommand?: CreateChannelCommand, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json', context?: HttpContext}): Observable<any> { let localVarHeaders = this.defaultHeaders; let localVarCredential: string | undefined; // authentication (Bearer) required localVarCredential = this.configuration.lookupCredential('Bearer'); if (localVarCredential) { localVarHeaders = localVarHeaders.set('Authorization', localVarCredential); } let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (localVarHttpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'text/plain', 'application/json', 'text/json' ]; localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } let localVarHttpContext: HttpContext | undefined = options && options.context; if (localVarHttpContext === undefined) { localVarHttpContext = new HttpContext(); } // to determine the Content-Type header const consumes: string[] = [ 'application/json', 'text/json', 'application/_*+json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); } let responseType_: 'text' | 'json' | 'blob' = 'json'; if (localVarHttpHeaderAcceptSelected) { if (localVarHttpHeaderAcceptSelected.startsWith('text')) { responseType_ = 'text'; } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { responseType_ = 'json'; } else { responseType_ = 'blob'; } } return this.httpClient.post<string>(`${this.configuration.basePath}/api/channel`, createChannelCommand, { context: localVarHttpContext, responseType: <any>responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, observe: observe, reportProgress: reportProgress } ); } }
the_stack
import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { TranslateService } from '@ngx-translate/core'; import { ToastrService } from 'ngx-toastr'; import { Subject } from 'rxjs'; import { debounceTime, skip } from 'rxjs/operators'; import { environment } from '@/environments/environment'; import { ApiService } from '@/app/core/api.service'; import { WsService } from '@/app/core/ws.service'; import { NotificationService } from '@/app/core/notification.service'; @Component({ selector: 'app-custom-plugins', templateUrl: './custom-plugins.component.html', styleUrls: ['./custom-plugins.component.scss'], }) export class CustomPluginsComponent implements OnInit, OnDestroy { private io = this.$ws.connectToNamespace('plugins/settings-ui'); @ViewChild('custompluginui', { static: true }) customPluginUiElementTarget: ElementRef; @Input() plugin; @Input() schema; @Input() pluginConfig: Record<string, any>[]; public pluginAlias: string; public pluginType: 'platform' | 'accessory'; public loading = true; public saveInProgress = false; public pluginSpinner = false; private basePath: string; private iframe: HTMLIFrameElement; // main config schema forms public showSchemaForm = false; private schemaFormRecentlyUpdated = false; private schemaFormRecentlyRefreshed = false; private schemaFormRefreshSubject = new Subject(); public schemaFormUpdatedSubject = new Subject(); // other forms public formId; public formSchema; public formData; public formSubmitButtonLabel: string; public formCancelButtonLabel: string; public formValid = true; public formUpdatedSubject = new Subject(); public formActionSubject = new Subject(); constructor( public activeModal: NgbActiveModal, private $translate: TranslateService, private $toastr: ToastrService, private $api: ApiService, private $ws: WsService, private $notification: NotificationService, ) { } ngOnInit(): void { this.pluginAlias = this.schema.pluginAlias; this.pluginType = this.schema.pluginType; // start accessory subscription if (this.io.connected) { this.io.socket.emit('start', this.plugin.name); setTimeout(() => { this.io.connected.subscribe(() => { this.io.socket.emit('start', this.plugin.name); }); }, 1000); } else { this.io.connected.subscribe(() => { this.io.socket.emit('start', this.plugin.name); }); } this.io.socket.on('response', (data) => { data.action = 'response'; this.iframe.contentWindow.postMessage(data, environment.api.origin); }); this.io.socket.on('stream', (data) => { data.action = 'stream'; this.iframe.contentWindow.postMessage(data, environment.api.origin); }); this.io.socket.on('ready', (data) => { this.loading = false; this.loadUi(); }); this.schemaFormRefreshSubject.pipe( debounceTime(250), ).subscribe(this.schemaFormRefresh.bind(this)); this.schemaFormUpdatedSubject.pipe( debounceTime(250), skip(1), ).subscribe(this.schemaFormUpdated.bind(this)); this.formUpdatedSubject.pipe( debounceTime(100), skip(1), ).subscribe(this.formUpdated.bind(this)); this.formActionSubject.subscribe(this.formActionEvent.bind(this)); this.basePath = `/plugins/settings-ui/${encodeURIComponent(this.plugin.name)}`; window.addEventListener('message', this.handleMessage, false); } get arrayKey() { return this.pluginType === 'accessory' ? 'accessories' : 'platforms'; } loadUi() { this.iframe = this.customPluginUiElementTarget.nativeElement as HTMLIFrameElement; this.iframe.src = environment.api.base + this.basePath + '/index.html?origin=' + encodeURIComponent(location.origin) + '&v=' + encodeURIComponent(this.plugin.installedVersion); } handleMessage = (e: MessageEvent) => { if (e.origin === environment.api.origin || e.origin === window.origin) { switch (e.data.action) { case 'loaded': this.injectDefaultStyles(e); this.confirmReady(e); break; case 'request': { this.handleRequest(e); break; } case 'scrollHeight': this.setiFrameHeight(e); break; case 'config.get': { this.requestResponse(e, this.getConfigBlocks()); break; } case 'config.save': { this.requestResponse(e, this.savePluginConfig()); break; } case 'config.update': { this.handleUpdateConfig(e, e.data.pluginConfig); break; } case 'config.schema': { this.requestResponse(e, this.schema); break; } case 'cachedAccessories.get': { this.handleGetCachedAccessories(e); break; } case 'schema.show': { this.formEnd(); // do not show other forms at the same time this.showSchemaForm = true; break; } case 'schema.hide': { this.showSchemaForm = false; break; } case 'form.create': { this.showSchemaForm = false; // hide the schema generated form this.formCreate(e.data.formId, e.data.schema, e.data.data, e.data.submitButton, e.data.cancelButton); break; } case 'form.end': { this.formEnd(); break; } case 'i18n.lang': { this.requestResponse(e, this.$translate.currentLang); break; } case 'i18n.translations': { this.requestResponse(e, this.$translate.store.translations[this.$translate.currentLang]); break; } case 'close': { this.activeModal.close(); break; } case 'toast.success': this.$toastr.success(e.data.message, e.data.title); break; case 'toast.error': this.$toastr.error(e.data.message, e.data.title); break; case 'toast.warning': this.$toastr.warning(e.data.message, e.data.title); break; case 'toast.info': this.$toastr.info(e.data.message, e.data.title); break; case 'spinner.show': this.pluginSpinner = true; break; case 'spinner.hide': this.pluginSpinner = false; break; default: console.log(e); } } }; confirmReady(event) { event.source.postMessage({ action: 'ready' }, event.origin); } setiFrameHeight(event: MessageEvent) { this.iframe.style.height = (event.data.scrollHeight) + 10 + 'px'; } handleRequest(event: MessageEvent) { this.io.socket.emit('request', event.data); } handleUpdateConfig(event: MessageEvent, pluginConfig: Array<any>) { // refresh the schema form this.schemaFormRefreshSubject.next(); // ensure the update contains an array if (!Array.isArray(pluginConfig)) { this.$toastr.error('Plugin config must be an array.', 'Invalid Config Update'); return this.requestResponse(event, { message: 'Plugin config must be an array.' }, false); } // validate each block in the array for (const block of pluginConfig) { if (typeof block !== 'object' || Array.isArray(block)) { this.$toastr.error('Plugin config must be an array of objects.', 'Invalid Config Update'); return this.requestResponse(event, { message: 'Plugin config must be an array of objects.' }, false); } } this.updateConfigBlocks(pluginConfig); return this.requestResponse(event, this.getConfigBlocks()); } requestResponse(event, data, success = true) { event.source.postMessage({ action: 'response', requestId: event.data.requestId, success, data, }, event.origin); } async injectDefaultStyles(event) { // fetch current theme const currentTheme = Array.from(window.document.body.classList).find(x => x.startsWith('config-ui-x-')); const darkMode = window.document.body.classList.contains('dark-mode'); // set body class event.source.postMessage({ action: 'body-class', class: currentTheme }, event.origin); if (darkMode) { event.source.postMessage({ action: 'body-class', class: 'dark-mode' }, event.origin); } // use parent's linked style sheets const externalCss = Array.from(document.querySelectorAll('link')); for (const css of externalCss) { if (css.getAttribute('rel') === 'stylesheet') { const srcHref = css.getAttribute('href'); const href = document.baseURI + (srcHref.startsWith('/') ? srcHref.substr(1) : srcHref); event.source.postMessage({ action: 'link-element', href, rel: 'stylesheet' }, event.origin); } } // use parent's inline css const inlineCss = Array.from(document.querySelectorAll('style')); for (const css of inlineCss) { event.source.postMessage({ action: 'inline-style', style: css.innerHTML }, event.origin); } // add custom css const customStyles = ` body { height: unset !important; background-color: ${darkMode ? '#242424' : '#FFFFFF'} !important; color: ${darkMode ? '#FFFFFF' : '#000000'}; padding: 5px !important; } `; event.source.postMessage({ action: 'inline-style', style: customStyles }, event.origin); } getConfigBlocks(): Array<any> { return this.pluginConfig; } updateConfigBlocks(pluginConfig: Record<string, any>[]) { for (const block of pluginConfig) { block[this.pluginType] = this.pluginAlias; } this.pluginConfig = pluginConfig; } /** * Called when changes are made to the schema form content * These changes are emitted to the custom ui */ schemaFormUpdated() { if (!this.iframe || !this.iframe.contentWindow) { return; } if (this.schemaFormRecentlyRefreshed) { this.schemaFormRecentlyRefreshed = false; return; } this.schemaFormRecentlyUpdated = true; this.iframe.contentWindow.postMessage({ action: 'stream', event: 'configChanged', data: this.pluginConfig, }, environment.api.origin); } /** * Called when changes sent from the custom ui config * Updates the schema form with the new values */ schemaFormRefresh() { if (this.schemaFormRecentlyUpdated) { this.schemaFormRecentlyUpdated = false; return; } this.schemaFormRecentlyRefreshed = true; if (this.showSchemaForm) { this.showSchemaForm = false; setTimeout(() => { this.showSchemaForm = true; }); } } /** * Create a new other-form */ async formCreate(formId: string, schema, data, submitButton?: string, cancelButton?: string) { // need to clear out existing forms await this.formEnd(); this.formId = formId; this.formSchema = schema; this.formData = data; this.formSubmitButtonLabel = submitButton; this.formCancelButtonLabel = cancelButton; } /** * Removes the current other-form */ async formEnd() { if (this.formId) { this.formId = undefined; this.formSchema = undefined; this.formData = undefined; this.formSubmitButtonLabel = undefined; this.formCancelButtonLabel = undefined; await new Promise((resolve) => setTimeout(resolve)); } } /** * Called when a other-form type is updated */ formUpdated(data) { this.iframe.contentWindow.postMessage({ action: 'stream', event: this.formId, data: { formEvent: 'change', formData: data, }, }, environment.api.origin); } /** * Fired when the form changes with a boolean indicating if the form is valid */ formValidEvent(isValid: boolean) { this.formValid = isValid; } /** * Fired when a custom form is cancelled or submitted * * @param action */ formActionEvent(formEvent: 'cancel' | 'submit') { this.iframe.contentWindow.postMessage({ action: 'stream', event: this.formId, data: { formEvent, formData: this.formData, }, }, environment.api.origin); } /** * Handle the event to get a list of cached accessories */ async handleGetCachedAccessories(event) { const cachedAccessories = await this.$api.get('/server/cached-accessories').toPromise(); return this.requestResponse(event, cachedAccessories.filter(x => x.plugin === this.plugin.name)); } async savePluginConfig(exit = false) { this.saveInProgress = true; return await this.$api.post(`/config-editor/plugin/${encodeURIComponent(this.plugin.name)}`, this.pluginConfig) .toPromise() .then(data => { this.$toastr.success( this.$translate.instant('plugins.settings.toast_restart_required'), this.$translate.instant('plugins.settings.toast_plugin_config_saved'), ); this.saveInProgress = false; this.$notification.configUpdated.next(); if (exit) { this.activeModal.close(); } }) .catch(err => { this.saveInProgress = false; this.$toastr.error(this.$translate.instant('config.toast_failed_to_save_config'), this.$translate.instant('toast.title_error')); }); } deletePluginConfig() { this.updateConfigBlocks([]); this.savePluginConfig(true); } ngOnDestroy() { window.removeEventListener('message', this.handleMessage); this.io.end(); this.schemaFormRefreshSubject.complete(); this.schemaFormUpdatedSubject.complete(); this.formUpdatedSubject.complete(); } }
the_stack
import * as cdk from '@aws-cdk/core'; import * as dynamodb from '@aws-cdk/aws-dynamodb'; import * as kms from '@aws-cdk/aws-kms'; import * as iam from '@aws-cdk/aws-iam'; import * as lambda from '@aws-cdk/aws-lambda'; import * as node_lambda from '@aws-cdk/aws-lambda-nodejs'; import * as sns from '@aws-cdk/aws-sns'; import * as logs from '@aws-cdk/aws-logs'; import * as cw from '@aws-cdk/aws-cloudwatch'; import * as cw_actions from '@aws-cdk/aws-cloudwatch-actions'; import * as path from 'path'; export interface BLEALambdaNodejsStackProps extends cdk.StackProps { alarmTopic: sns.Topic; table: dynamodb.Table; appKey: kms.Key; } export class BLEALambdaNodejsStack extends cdk.Stack { public readonly getItemFunction: lambda.Function; public readonly listItemsFunction: lambda.Function; public readonly putItemFunction: lambda.Function; constructor(scope: cdk.Construct, id: string, props: BLEALambdaNodejsStackProps) { super(scope, id, props); // Custom Policy for App Key props.appKey.addToResourcePolicy( new iam.PolicyStatement({ actions: ['kms:*'], principals: [new iam.AccountRootPrincipal()], resources: ['*'], }), ); props.appKey.addToResourcePolicy( new iam.PolicyStatement({ actions: ['kms:Encrypt*', 'kms:Decrypt*', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:Describe*'], principals: [ new iam.AnyPrincipal().withConditions({ ArnLike: { 'aws:PrincipalArn': `arn:aws:iam::${cdk.Stack.of(this).account}:role/BLEA-LambdaNodejs-*`, }, }), ], resources: ['*'], }), ); // Policy operating KMS CMK for Lambda const kmsPolicy = new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['kms:Encrypt*', 'kms:Decrypt*', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:Describe*'], resources: [props.appKey.keyArn], }); // Using Lambda Node.js Library // See: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-nodejs-readme.html // GetItem Function const getItemFunction = new node_lambda.NodejsFunction(this, 'getItem', { runtime: lambda.Runtime.NODEJS_14_X, entry: path.join(__dirname, '../lambda/nodejs/getItem.js'), handler: 'getItem', memorySize: 256, timeout: cdk.Duration.seconds(25), tracing: lambda.Tracing.ACTIVE, insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0, environment: { DDB_TABLE: props.table.tableName, }, environmentEncryption: props.appKey, logRetention: logs.RetentionDays.THREE_MONTHS, }); getItemFunction.addToRolePolicy(kmsPolicy); getItemFunction.addToRolePolicy( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['dynamodb:Query', 'dynamodb:GetItem'], resources: [props.table.tableArn, props.table.tableArn + '/index/*'], }), ); this.getItemFunction = getItemFunction; // Sample metrics and alarm // See: https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/best-practices.html getItemFunction .metricErrors({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'getItemErrorsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); getItemFunction .metricDuration({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'getItemDurationAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); new cw.Metric({ namespace: 'AWS/Lambda', metricName: 'ConcurrentExecutions', period: cdk.Duration.minutes(5), statistic: cw.Statistic.MAXIMUM, dimensionsMap: { FunctionName: getItemFunction.functionName, }, }) .createAlarm(this, 'getItemConcurrentExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); getItemFunction .metricThrottles({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'getItemThrottlesAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // ListItem Function const listItemsFunction = new node_lambda.NodejsFunction(this, 'listItems', { runtime: lambda.Runtime.NODEJS_14_X, entry: path.join(__dirname, '../lambda/nodejs/listItems.js'), handler: 'listItems', timeout: cdk.Duration.seconds(25), memorySize: 256, tracing: lambda.Tracing.ACTIVE, insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0, environment: { DDB_TABLE: props.table.tableName, }, environmentEncryption: props.appKey, logRetention: logs.RetentionDays.THREE_MONTHS, }); listItemsFunction.addToRolePolicy(kmsPolicy); listItemsFunction.addToRolePolicy( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['dynamodb:Query', 'dynamodb:Scan'], resources: [props.table.tableArn, props.table.tableArn + '/index/*'], }), ); this.listItemsFunction = listItemsFunction; // Sample metrics and alarm // See: https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/best-practices.html listItemsFunction .metricErrors({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'listItemsErrorsExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); listItemsFunction .metricDuration({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'listItemsDurationAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); new cw.Metric({ namespace: 'AWS/Lambda', metricName: 'ConcurrentExecutions', period: cdk.Duration.minutes(5), statistic: cw.Statistic.MAXIMUM, dimensionsMap: { FunctionName: listItemsFunction.functionName, }, }) .createAlarm(this, 'listItemsConcurrentExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); listItemsFunction .metricThrottles({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'listItemsThrottlesAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // PutItem Function const putItemFunction = new node_lambda.NodejsFunction(this, 'putItem', { runtime: lambda.Runtime.NODEJS_14_X, entry: path.join(__dirname, '../lambda/nodejs/putItem.js'), handler: 'putItem', timeout: cdk.Duration.seconds(25), memorySize: 256, tracing: lambda.Tracing.ACTIVE, insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0, environment: { DDB_TABLE: props.table.tableName, }, environmentEncryption: props.appKey, logRetention: logs.RetentionDays.THREE_MONTHS, }); putItemFunction.addToRolePolicy(kmsPolicy); putItemFunction.addToRolePolicy( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: ['dynamodb:PutItem'], resources: [props.table.tableArn, props.table.tableArn + '/index/*'], }), ); this.putItemFunction = putItemFunction; // Sample metrics and alarm // See: https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/best-practices.html putItemFunction .metricErrors({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'putItemErrorsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); putItemFunction .metricDuration({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'putItemDurationAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); new cw.Metric({ namespace: 'AWS/Lambda', metricName: 'ConcurrentExecutions', period: cdk.Duration.minutes(5), statistic: cw.Statistic.MAXIMUM, dimensionsMap: { FunctionName: putItemFunction.functionName, }, }) .createAlarm(this, 'putItemConcurrentExecutionsAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); putItemFunction .metricThrottles({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'putItemThrottlesAlarm', { evaluationPeriods: 3, threshold: 80, datapointsToAlarm: 3, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); } }
the_stack
import path = require('path'); import fs = require('fs'); import os = require('os'); import _ = require('underscore'); import webpack = require('webpack'); import karma = require('karma'); import async = require('async'); import express = require('express'); import bodyParser = require('body-parser'); import glob = require('glob'); /** * Returns a webpack configuration for testing a particular DoppioJVM build. */ function getWebpackTestConfig(target: string, optimize = false, benchmark = false): webpack.Configuration { const config = getWebpackConfig(target, optimize); const entries: {[name: string]: string} = {}; if (!benchmark) { // Worker and non-worker entries. entries[`test-${target}/harness`] = path.resolve(__dirname, `build/scratch/test/${target}/tasks/test/harness`); entries[`test-${target}/harness_webworker`] = path.resolve(__dirname, `build/scratch/test/${target}/tasks/test/harness_webworker`); } else { entries[`${target}/benchmark_harness`] = path.resolve(__dirname, `build/scratch/test/release/tasks/test/benchmark_harness`); } // Change entries. config.entry = entries; // No longer a UMD module, so change external configuration. (<any> config.externals)['browserfs'] = 'BrowserFS'; // Test config should run immediately; it is not a library. delete config.output.libraryTarget; delete config.output.library; return config; } /** * Returns a webpack configuration file for the given compilation target * @param target release, dev, or fast-dev */ function getWebpackConfig(target: string, optimize: boolean = false): webpack.Configuration { const output = `${target}/doppio`, entry = path.resolve(__dirname, `build/${target}-cli/src/index`); const entries: {[name: string]: string} = {}; entries[output] = entry; const config: webpack.Configuration = { entry: entries, devtool: "source-map", output: { path: path.join(__dirname, 'build'), filename: '[name].js', libraryTarget: 'umd', library: <any> 'Doppio' }, resolve: { extensions: ['', '.js', '.json'], // Use our versions of Node modules. alias: { 'buffer': require.resolve('browserfs/dist/shims/buffer'), 'fs': require.resolve('browserfs/dist/shims/fs'), 'path': require.resolve('browserfs/dist/shims/path'), 'BFSBuffer': require.resolve('browserfs/dist/shims/bufferGlobal'), 'process': require.resolve('browserfs/dist/shims/process') } }, externals: <any> { 'browserfs': { root: 'BrowserFS', commonjs2: 'browserfs', commonjs: 'browserfs', amd: 'browserfs' } }, plugins: [ new webpack.ProvidePlugin({ Buffer: 'BFSBuffer', process: 'process' }), // Hack to fix relative paths of JSON includes. new webpack.NormalModuleReplacementPlugin(/\.json$/, <any> function(requireReq: {request: string}) { const request = requireReq.request; switch (path.basename(request)) { case 'jdk.json': requireReq.request = path.resolve(__dirname, 'vendor', 'java_home', 'jdk.json'); break; case 'package.json': requireReq.request = path.resolve(__dirname, 'package.json'); break; case 'benchmarks.json': requireReq.request = path.resolve(__dirname, 'vendor', 'benchmarks', 'benchmarks.json'); break; } }) ], node: { process: false, Buffer: false, setImmediate: false }, target: "web", module: { // Load source maps for any relevant files. preLoaders: [ { test: /\.js$/, loader: "source-map-loader" } ], loaders: [ { test: /\.json$/, loader: 'json-loader' } ] } } if (optimize) { config.plugins.push(new webpack.optimize.UglifyJsPlugin(<any> { compress: { warnings: false, unsafe: true, screw_ie8: false }, mangle: { screw_ie8: false }, output: { screw_ie8: false }, sourceMap: true })); } return config; } /** * Returns a Karma configuration file for the given compilation target * @param target release, dev, or fast-dev */ function getKarmaConfig(target: string, singleRun = false, browsers = ['Chrome']): karma.ConfigOptions { return <any> { // base path, that will be used to resolve files and exclude basePath: '.', frameworks: ['jasmine'], reporters: ['progress'], port: 9876, //runnerPort: 9100, colors: true, logLevel: 'INFO', autoWatch: true, browsers: browsers, captureTimeout: 60000, concurrency: 1, // Avoid hardcoding and cross-origin issues. proxies: { '/': 'http://localhost:8000/' }, files: [ 'node_modules/browserfs/dist/browserfs.js', {pattern: 'node_modules/browserfs/dist/browserfs.js.map', included: false}, {pattern: `build/test-${target}/**/*.js*`, included: false}, `build/test-${target}/harness.js` ], singleRun: singleRun, urlRoot: '/karma/', browserNoActivityTimeout: 180000, browserDisconnectTimeout: 180000 }; } export function setup(grunt: IGrunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // doppio build configuration build: { // Path to Java CLI utils. Will be updated by find_native_java task // if needed. java: 'java', javap: 'javap', javac: 'javac', is_java_8: true, // Will be set by JDK download task. bootclasspath: null }, make_build_dir: { options: { base: path.resolve(__dirname, 'build') }, // It's a multi-task, so you need a default target. default: {} }, listings: { }, includes: { options: { packages: fs.readdirSync('src/natives') .filter((item: string) => item.indexOf(".ts") !== -1) .map((item: string) => item.slice(0, item.indexOf('.')).replace(/_/g, '.')), dest: "includes", // The following classes are referenced by DoppioJVM code, but aren't // referenced by any JVM classes directly for some reason. force: [ 'java.nio.file.NoSuchFileException', 'java.nio.file.FileAlreadyExistsException', 'sun.nio.fs.UnixConstants', 'sun.nio.fs.DefaultFileSystemProvider', 'sun.nio.fs.UnixException', 'java.lang.ExceptionInInitializerError', 'java.nio.charset.Charset$3', 'java.lang.invoke.MethodHandleNatives$Constants', 'java.lang.reflect.InvocationTargetException', 'java.nio.DirectByteBuffer', 'java.security.PrivilegedActionException', 'java.security.ProviderException', 'doppio.security.DoppioProvider'], headersOnly: true }, default: {} }, 'ice-cream': { 'release-cli': { options: { remove: ['assert', 'trace', 'vtrace', 'debug'] }, files: [{ expand: true, cwd: 'build/dev-cli', src: '+(console|src)/**/*.js', dest: 'build/scratch/ice-cream/release-cli' }] }, 'fast-dev-cli': { options: { remove: ['debug', 'trace', 'vtrace'] }, files: [{ expand: true, cwd: 'build/dev-cli', src: '+(console|src)/**/*.js', dest: 'build/fast-dev-cli' }] }, 'test-release': { options: { remove: ['assert', 'trace', 'vtrace', 'debug'] }, files: [{ expand: true, cwd: 'build/scratch/test/dev', src: '+(console|src|tasks)/**/*.js', dest: 'build/scratch/ice-cream/test-release' }] }, 'test-fast-dev': { options: { remove: ['debug', 'trace', 'vtrace'] }, files: [{ expand: true, cwd: 'build/scratch/test/dev', src: '+(console|src|tasks)/**/*.js', dest: 'build/scratch/test/fast-dev' }] } }, launcher: { 'doppio-dev': { options: { src: path.resolve(__dirname, 'build', 'dev-cli', 'console', 'runner.js'), dest: path.resolve(__dirname, 'doppio-dev') } }, 'doppio-fast-dev': { options: { src: path.resolve(__dirname, 'build', 'fast-dev-cli', 'console', 'runner.js'), dest: path.resolve(__dirname, 'doppio-fast-dev') } }, 'doppio': { options: { src: path.resolve(__dirname, 'build', 'release-cli', 'console', 'runner.js'), dest: path.resolve(__dirname, 'doppio') } }, 'doppioh': { options: { src: path.resolve(__dirname, 'build', 'release-cli', 'console', 'doppioh.js'), dest: path.resolve(__dirname, 'doppioh') } } }, // Compiles TypeScript files. ts: { options: { comments: true, declaration: true, target: 'es3', noImplicitAny: true, inlineSourceMap: true, inlineSources: true, fast: 'watch' }, 'dev-cli': { src: ["console/*.ts", "src/**/*.ts", "typings/index.d.ts"], outDir: 'build/dev-cli', options: { module: 'commonjs' } }, 'test': { src: ["console/*.ts", "src/**/*.ts", "typings/index.d.ts", 'tasks/test/*.ts'], outDir: 'build/scratch/test/dev', options: { module: 'commonjs' } } }, uglify: { options: { warnings: false, unsafe: true, compress: { global_defs: { RELEASE: true }, screw_ie8: false }, mangle: { screw_ie8: false }, output: { screw_ie8: false }, sourceMap: true, sourceMapIncludeSources: true }, 'release-cli': { files: [{ expand: true, cwd: path.resolve(__dirname, 'build', 'scratch', 'ice-cream', 'release-cli'), src: '+(console|src)/**/*.js', dest: path.resolve(__dirname, 'build', 'release-cli') }] }, 'release': { options: { sourceMapIn: 'build/release/doppio.js.map' }, files: [{ src: 'build/release/doppio.js', dest: 'build/release/doppio.js' }] }, 'test-release': { files: [{ expand: true, cwd: path.resolve(__dirname, 'build', 'scratch', 'ice-cream', 'test-release'), src: '+(console|src|tasks)/**/*.js', dest: path.resolve(__dirname, 'build', 'scratch', 'test', 'release') }] } }, copy: { dist: { files: [{ expand: true, cwd: "build", src: ["+(dev|dev-cli|release|release-cli|fast-dev|fast-dev-cli)/!(vendor)/**/*.js*", "+(dev|dev-cli|release|release-cli|fast-dev|fast-dev-cli)/*.js*"], dest: "dist" }, { expand: true, cwd: "build/dev-cli", src: "**/*.d.ts", dest: "dist/typings" }, { expand: true, src: "includes/**/*.d.ts", dest: "dist/typings" }, { expand: true, cwd: 'vendor/java_home/lib', src: 'doppio.jar', dest: 'dist' }] }, 'examples': { files: [{ expand: true, cwd: "build/release", src: ["*.js", "*.js.map", "natives/**/*.js*", "vendor/**/*"], dest: "docs/examples/doppio" }, { expand: true, flatten: true, cwd: ".", src: "node_modules/browserfs/dist/browserfs.min.*", dest: "docs/examples/doppio" }] } }, javac: { default: { files: [{ expand: true, src: ['classes/+(awt|demo|test|util)/*.java', 'classes/doppio/**/*.java'], ext: '.class' }] }, examples: { files: [{ expand: true, src: 'docs/examples/example/**/*.java', ext: '.class' }] } }, run_java: { default: { expand: true, src: 'classes/test/*.java', ext: '.runout' } }, compress: { doppio: { options: { archive: 'vendor/java_home/lib/doppio.jar', mode: 'zip', level: 0 }, files: [ { expand: true, cwd: 'classes/', src: 'doppio/**/*.class', dest: ''} ] } }, lineending: { options: { eol: 'lf' }, default: { files: [{ expand: true, src: ['classes/test/*.runout'] }] } }, unit_test: { default: { files: [{ expand: true, src: 'classes/test/*.java' }] } }, connect: { server: { options: { keepalive: false } }, examples: { options: { base: 'docs/examples', keepalive: true } } }, karma: { 'fast-dev': { options: getKarmaConfig('fast-dev') }, release: { options: getKarmaConfig('release') }, dev: { options: getKarmaConfig('dev') }, travis: { options: getKarmaConfig('release', true, ['Firefox']) }, appveyor: { options: getKarmaConfig('release', true, ['Firefox', 'Chrome', 'IE']) } }, webpack: { dev: getWebpackConfig('dev'), 'fast-dev': getWebpackConfig('fast-dev'), release: getWebpackConfig('release', true), 'test-dev': getWebpackTestConfig('dev'), 'test-fast-dev': getWebpackTestConfig('fast-dev'), 'test-release': getWebpackTestConfig('release', true), 'benchmark': getWebpackTestConfig('benchmark', true, true) }, "merge-source-maps": { options: { inlineSources: true, inlineSourceMaps: true }, "release-cli": { files: [ { expand: true, cwd: "build/release-cli", // Ignore vendor files! src: ['./*.js', 'src/**/*.js', 'console/**/*.js'], dest: "build/release-cli", ext: '.js.map' } ] }, "fast-dev-cli": { files: [ { expand: true, cwd: "build/fast-dev-cli", // Ignore vendor files! src: ['./*.js', 'src/**/*.js', 'console/**/*.js'], dest: "build/fast-dev-cli", ext: '.js.map' } ] }, "test-fast-dev": { files: [ { expand: true, cwd: "build/scratch/test/fast-dev", // Ignore vendor files! src: ['./*.js', 'src/**/*.js', 'console/**/*.js', 'tasks/**/*.js'], dest: "build/scratch/test/fast-dev", ext: '.js.map' } ] }, "test-release": { files: [ { expand: true, cwd: "build/scratch/test/release", // Ignore vendor files! src: ['./*.js', 'src/**/*.js', 'console/**/*.js', 'tasks/**/*.js'], dest: "build/scratch/test/release", ext: '.js.map' } ] } } }); grunt.loadNpmTasks('grunt-ts'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-lineending'); grunt.loadNpmTasks('grunt-merge-source-maps'); grunt.loadNpmTasks('grunt-webpack'); grunt.loadNpmTasks('grunt-newer'); grunt.loadNpmTasks('grunt-contrib-compress'); // Load our custom tasks. grunt.loadTasks('tasks'); grunt.registerMultiTask('launcher', 'Creates a launcher for the given CLI release.', function() { var launcherPath: string, exePath: string, options = this.options(); launcherPath = options.dest; exePath = options.src; if (!grunt.file.exists(launcherPath) && !grunt.file.exists(launcherPath + ".bat")) { try { if (process.platform.match(/win32/i)) { fs.writeFileSync(launcherPath + ".bat", 'node %~dp0\\' + path.relative(path.dirname(launcherPath), exePath) + ' %*'); } else { // Write with mode 755. fs.writeFileSync(launcherPath, 'node $(dirname $0)/' + path.relative(path.dirname(launcherPath), exePath) + ' "$@"', { mode: 493 }); } grunt.log.ok("Created launcher " + path.basename(launcherPath)); } catch (e) { grunt.log.error("Could not create launcher " + path.basename(launcherPath) + ": " + e); return false; } } }); grunt.registerTask("check_jdk", "Checks the status of the JDK. Downloads if needed.", function() { let done: (status?: boolean) => void = this.async(); let child = grunt.util.spawn({ cmd: 'node', args: ['build/dev-cli/console/download_jdk.js'] }, (err, result, code) => { if (code === 0) { let JDKInfo = require('./vendor/java_home/jdk.json'); grunt.config.set("build.bootclasspath", JDKInfo.classpath.map((item: string) => path.resolve(path.join(__dirname, 'vendor', 'java_home'), item).replace(/\\/g, '/')).join(path.delimiter)); } done(code === 0); }); (<NodeJS.ReadableStream> (<any> child).stdout).on('data', function(d: Buffer) { grunt.log.write(d.toString()); }); }); grunt.registerTask("bootstrap", "Bootstraps DoppioJVM, if needed, by generating includes and downloading the JDK.", function() { const downloadScriptExists = grunt.file.exists("build/dev-cli/console/download_jdk.js"); const includeExists = grunt.file.exists('includes/JVMTypes.d.ts'); let tasks = ['check_jdk', 'java']; if (!downloadScriptExists || !includeExists) { // Awkward bootstrapping: // Need to build DoppioJVM before we can check if a new JDK is needed. tasks.unshift('ts:dev-cli'); if (!includeExists) { // Tell Grunt to ignore these errors; we'll compile it a second time // once bootstrapped to catch any valid errors. grunt.config.set('ts.options.failOnTypeErrors', false); // Disable the grunt-ts cache for this compilation. Otherwise, it may // cache a problematic compile and will not error when we go to build // the app with error checking turned on. grunt.config.set('ts.options.fast', 'never'); // Generate includes, then re-enable type errors. tasks.push('includes:default', 'enable_type_errors'); } } grunt.task.run(tasks); }); grunt.registerTask("enable_type_errors", "Enables TypeScript type errors after bootstrapping.", function() { grunt.config.set('ts.options.failOnTypeErrors', true); grunt.config.set('ts.options.fast', 'watch'); }); grunt.registerTask('generate_doppio_jar', 'Only generates doppio.jar if input classes have changed.', function() { if (!fs.existsSync('vendor/java_home/lib/doppio.jar')) { grunt.task.run('compress:doppio'); } else { const zipModified = fs.statSync('vendor/java_home/lib/doppio.jar').mtime; const filesModified = glob.sync('classes/doppio/**/*.java').map((file) => fs.statSync(file).mtime).filter((modTime) => modTime > zipModified); if (filesModified.length > 0) { grunt.task.run('compress:doppio'); } } }); // Convenience task that combines several Java-related tasks. grunt.registerTask('java', ['find_native_java', 'newer:javac', 'generate_doppio_jar', 'newer:run_java', // Windows: Convert CRLF to LF. 'newer:lineending']); grunt.registerTask('clean_natives', "Deletes already-inlined sourcemaps from natives.", function() { let done: (success?: boolean) => void = this.async(); grunt.file.glob("build/*/src/natives/*.js.map", (err: Error, files: string[]) => { if (err) { grunt.log.error("" + err); return done(false); } grunt.file.glob("build/*/natives/*.js.map", (err: Error, files2: string[]) => { if (err) { grunt.log.error("" + err); return done(false); } files.concat(files2).forEach((file) => grunt.file.delete(file)); done(true); }); }); }); function benchmarkLocally(command: string, intOnly: boolean, outFile: string, done: (e?: Error) => void): void { const benchmarks = require('./vendor/benchmarks/benchmarks.json'); const benchmarkNames = Object.keys(benchmarks); const curdir = process.cwd(); const bmDir = path.resolve('vendor/benchmarks'); const results: {[name: string]: number} = {}; async.eachSeries(benchmarkNames, (benchmarkName: string, done: (e?: Error) => void) => { console.log(benchmarkName); const bm = benchmarks[benchmarkName]; process.chdir(bmDir); if (bm.cwd) { process.chdir(bm.cwd); } const start = process.hrtime(); let args = bm.args; if (intOnly) { args = ["-Xint"].concat(args); } grunt.util.spawn({ cmd: command, args: args /*opts: { stdio: "inherit" }*/ }, (err, result, code) => { if (err || code !== 0) { done(new Error("Benchmark failed.")); } else { const time = process.hrtime(start); // Convert to ms. const timeMs = ((time[0] * 1000) + (time[1]/1000000))|0; results[benchmarkName] = timeMs; console.log(`${timeMs} ms`); done(); } }); }, (err?: Error) => { process.chdir(curdir); if (!err) { grunt.file.write(outFile, JSON.stringify(results)); grunt.log.ok(`Wrote benchmark results to ${outFile}.`); } done(err); }); } grunt.registerTask('run-benchmark-native-java', 'Runs benchmarks locally', function() { benchmarkLocally(grunt.config.get<string>("build.java"), true, path.resolve(__dirname, 'native_java.json'), this.async()); }); grunt.registerTask('run-benchmark-node', 'Runs benchmarks in DoppioJVM in node.', function() { const done = this.async(); grunt.log.writeln(">>> Running with JIT. <<<"); benchmarkLocally(path.resolve(__dirname, 'doppio'), false, path.join(__dirname, 'node.json'), (e) => { if (e) { return done(e); } grunt.log.writeln(">>> Running without JIT. <<<"); benchmarkLocally(path.resolve(__dirname, 'doppio'), true, path.join(__dirname, 'node-int.json'), done); }); }); grunt.registerTask('benchmark-node', ['release-cli', 'run-benchmark-node']); grunt.registerTask("benchmark-native", ["java", "run-benchmark-native-java"]); grunt.registerTask("benchmark-browser", ['build-test-release', 'make_build_dir:benchmark', 'webpack:benchmark', 'listings:benchmark', 'benchmark-browser-server']); grunt.registerTask("benchmark-browser-server", 'Runs an HTTP server for serving up benchmarks.', function() { const done = this.async(); const app = express(); app.use(bodyParser.json()); app.use(express.static('.')); app.put('/results/:name', function(req, res) { const data = req.body; grunt.log.ok(`Creating ${req.params.name}...`); fs.writeFileSync(req.params.name, JSON.stringify(data)); res.end(); }); app.put('/done', function(req, res) { grunt.log.ok("Your browser has informed us that it has completed running benchmarks."); res.end(); }); app.get('/', function(req, res) { res.set('Content-Type', 'text/html'); res.send(`<!doctype html> <html> <script type="text/javascript" src="node_modules/browserfs/dist/browserfs.min.js"></script> <script type="text/javascript" src="build/benchmark/benchmark_harness.js"></script> </html>`); }); app.listen(3000, 'localhost', function() { console.log("Visit http://localhost:3000 to run benchmarks in your browser.") }) }); /** * PUBLIC-FACING TARGETS BELOW. */ grunt.registerTask('dev-cli', ['make_build_dir:dev-cli', 'bootstrap', 'ts:dev-cli', 'launcher:doppio-dev']); grunt.registerTask('fast-dev-cli', ['dev-cli', 'make_build_dir:fast-dev-cli', 'newer:ice-cream:fast-dev-cli', 'merge-source-maps:fast-dev-cli', 'launcher:doppio-fast-dev']); grunt.registerTask('release-cli', ['dev-cli', 'make_build_dir:release-cli', 'newer:ice-cream:release-cli', 'newer:uglify:release-cli', 'merge-source-maps:release-cli', 'launcher:doppio', 'launcher:doppioh']); grunt.registerTask('dev', ['dev-cli', 'make_build_dir:dev', 'webpack:dev', 'listings:dev']); grunt.registerTask('fast-dev', ['fast-dev-cli', 'make_build_dir:fast-dev', 'webpack:fast-dev', 'listings:fast-dev']); grunt.registerTask('release', ['release-cli', 'make_build_dir:release', 'webpack:release', 'listings:release']); grunt.registerTask('examples', ['release', 'newer:javac:examples', 'copy:examples', 'listings:examples', "connect:examples" ]); grunt.registerTask('dist', [ 'clean', 'release', 'fast-dev', 'dev', 'clean_natives', 'copy:dist' ]); grunt.registerTask('test', ['release-cli', 'unit_test']); grunt.registerTask('build-test-dev', [ 'make_build_dir:dev-cli', 'bootstrap', 'ts:test' ]); grunt.registerTask('build-test-fast-dev', [ 'build-test-dev', 'ice-cream:test-fast-dev', 'merge-source-maps:test-fast-dev' ]); grunt.registerTask('build-test-release', [ 'build-test-dev', 'ice-cream:test-release', 'uglify:test-release', 'merge-source-maps:test-release' ]); grunt.registerTask('test-browser', ['build-test-release', 'make_build_dir:test-release', 'webpack:test-release', 'listings:test-release', 'connect:server', 'karma:release']); grunt.registerTask('test-browser-fast-dev', ['build-test-fast-dev', 'make_build_dir:test-fast-dev', 'webpack:test-fast-dev', 'listings:test-fast-dev', 'connect:server', 'karma:fast-dev']); grunt.registerTask('test-browser-dev', ['build-test-dev', 'make_build_dir:test-dev', 'webpack:test-dev', 'listings:test-dev', 'connect:server', 'karma:dev']); grunt.registerTask('clean', 'Deletes built files.', function() { ['includes', 'dist', 'build', 'doppio', 'doppio-dev'].concat(grunt.file.expand(['tscommand*.txt'])).concat(grunt.file.expand(['classes/*/*.+(class|runout)'])).forEach(function (path: string) { if (grunt.file.exists(path)) { grunt.file.delete(path); } }); grunt.log.writeln('All built files have been deleted, except for Grunt-related tasks (e.g. tasks/*.js and Grunttasks.js).'); }); grunt.registerTask('test-browser-travis', ['build-test-release', 'make_build_dir:test-release', 'webpack:test-release', 'listings:test-release', 'connect:server', 'karma:travis']); grunt.registerTask('test-browser-appveyor', ['build-test-release', 'make_build_dir:test-release', 'webpack:test-release', 'listings:test-release', 'connect:server', 'karma:appveyor']); };
the_stack
import { Components, registerComponent } from '../../lib/vulcan-lib'; import { useSingle } from '../../lib/crud/withSingle'; import React from 'react'; import { Localgroups } from '../../lib/collections/localgroups/collection'; import { Link } from '../../lib/reactRouterWrapper'; import { Posts } from '../../lib/collections/posts'; import { useCurrentUser } from '../common/withUser'; import { createStyles } from '@material-ui/core/styles'; import qs from 'qs' import { userIsAdmin } from '../../lib/vulcan-users'; import { forumTypeSetting } from '../../lib/instanceSettings'; import { useMulti } from '../../lib/crud/withMulti'; import Button from '@material-ui/core/Button'; import { FacebookIcon, MeetupIcon, RoundFacebookIcon, SlackIcon } from './GroupLinks'; import EmailIcon from '@material-ui/icons/Email'; import LinkIcon from '@material-ui/icons/Link'; import LocationIcon from '@material-ui/icons/LocationOn'; import { GROUP_CATEGORIES } from '../../lib/collections/localgroups/schema'; const styles = createStyles((theme: ThemeType): JssStyles => ({ root: {}, topSection: { [theme.breakpoints.up('md')]: { marginTop: -50, } }, topSectionMap: { height: 250, [theme.breakpoints.up('md')]: { marginTop: -50, }, [theme.breakpoints.down('sm')]: { marginLeft: -4, marginRight: -4, }, }, imageContainer: { [theme.breakpoints.up('md')]: { marginTop: -50, }, [theme.breakpoints.down('sm')]: { marginLeft: -4, marginRight: -4, }, }, bannerImg: { display: 'block', maxWidth: '100%', objectFit: 'cover', margin: '0 auto', }, titleRow: { display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', columnGap: 20, marginTop: 24, [theme.breakpoints.down('xs')]: { display: 'block' } }, inactiveGroupTag: { color: theme.palette.grey[500], marginRight: 10 }, notifyMe: { justifyContent: 'flex-end', margin: '8px 4px 20px', [theme.breakpoints.down('xs')]: { justifyContent: 'flex-start', marginTop: 30 } }, organizerActions: { [theme.breakpoints.down('xs')]: { justifyContent: 'flex-start !important' } }, groupName: { ...theme.typography.headerStyle, fontSize: "30px", marginTop: "0px", marginBottom: "0.5rem" }, groupLocation: { ...theme.typography.body2, display: "flex", columnGap: 5, alignItems: 'center', color: theme.palette.text.slightlyDim2, }, groupLocationIcon: { fontSize: 20 }, groupCategories: { display: 'flex', columnGap: 10, marginTop: theme.spacing.unit * 2 }, groupCategory: { backgroundColor: theme.palette.panelBackground.default, fontFamily: theme.typography.fontFamily, fontSize: 12, color: theme.palette.grey[600], padding: '6px 12px', border: `1px solid ${theme.palette.grey[0]}`, borderColor: theme.palette.grey[300], borderRadius: 4 }, groupDescription: { marginTop: theme.spacing.unit * 3, marginBottom: 20, [theme.breakpoints.down('xs')]: { marginLeft: 0 } }, groupDescriptionBody: { padding: theme.spacing.unit, }, contactUsSection: { display: 'flex', justifyContent: 'space-between', columnGap: '40px', marginTop: 40, [theme.breakpoints.down('xs')]: { display: 'block' }, }, externalLinkBtns: { flex: 'none', }, externalLinkBtnRow: { marginBottom: 16 }, externalLinkBtn: { textTransform: 'none', fontSize: 13, paddingLeft: 14, boxShadow: 'none', '& svg': { width: 17, marginRight: 10 } }, facebookGroupIcon: { fontSize: 13, }, facebookPageIcon: { fontSize: 14, }, meetupIcon: { fontSize: 15, }, slackIcon: { fontSize: 14, }, linkIcon: { transform: "rotate(-45deg)", fontSize: 17 }, emailIcon: { fontSize: 17, }, contactUsHeadline: { marginBottom: 16, }, eventsHeadline: { marginTop: 40, marginBottom: 16, }, eventCards: { display: 'grid', gridTemplateColumns: 'repeat(2, 373px)', gridGap: '20px', '@media (max-width: 812px)': { gridTemplateColumns: 'auto', } }, loading: { marginLeft: 0 }, noUpcomingEvents: { color: theme.palette.grey[500], }, notifyMeButton: { display: 'inline !important', color: theme.palette.primary.main, }, pastEventCard: { height: 350, filter: 'saturate(0.3) opacity(0.8)', '& .EventCards-addToCal': { display: 'none' } }, mapContainer: { height: 260, maxWidth: 450, marginTop: 0, marginLeft: 0, marginRight: 0, [theme.breakpoints.down('xs')]: { height: 200, maxWidth: 'none' }, } })); const LocalGroupPage = ({ classes, documentId: groupId }: { classes: ClassesType, documentId: string, groupId?: string, }) => { const currentUser = useCurrentUser(); const { HeadTags, CommunityMapWrapper, SingleColumnSection, SectionTitle, PostsList2, Loading, SectionButton, NotifyMeButton, SectionFooter, GroupFormLink, ContentItemBody, Error404, CloudinaryImage2, EventCards, LoadMore, ContentStyles } = Components const { document: group, loading: groupLoading } = useSingle({ collectionName: "Localgroups", fragmentName: 'localGroupsHomeFragment', documentId: groupId }) const { results: upcomingEvents, loading: upcomingEventsLoading, loadMoreProps: upcomingEventsLoadMoreProps } = useMulti({ terms: {view: 'upcomingEvents', groupId: groupId}, collectionName: "Posts", fragmentName: 'PostsList', fetchPolicy: 'cache-and-network', nextFetchPolicy: "cache-first", limit: 2, itemsPerPage: 6, enableTotal: true, }); const { results: tbdEvents, loading: tbdEventsLoading, loadMoreProps: tbdEventsLoadMoreProps } = useMulti({ terms: {view: 'tbdEvents', groupId: groupId}, collectionName: "Posts", fragmentName: 'PostsList', fetchPolicy: 'cache-and-network', nextFetchPolicy: "cache-first", limit: 2, itemsPerPage: 6, enableTotal: true, }); const { results: pastEvents, loading: pastEventsLoading, loadMoreProps: pastEventsLoadMoreProps } = useMulti({ terms: {view: 'pastEvents', groupId: groupId}, collectionName: "Posts", fragmentName: 'PostsList', fetchPolicy: 'cache-and-network', nextFetchPolicy: "cache-first", limit: 2, itemsPerPage: 6, enableTotal: true, }); if (groupLoading) return <Loading /> if (!group || group.deleted) return <Error404 /> const { html = ""} = group.contents || {} const htmlBody = {__html: html} const isAdmin = userIsAdmin(currentUser); const isGroupAdmin = currentUser && group.organizerIds.includes(currentUser._id); const isEAForum = forumTypeSetting.get() === 'EAForum'; // by default, we try to show the map at the top if the group has a location let topSection = (group.googleLocation && !group.isOnline) ? <CommunityMapWrapper className={classes.topSectionMap} terms={{view: "events", groupId: groupId}} groupQueryTerms={{view: "single", groupId: groupId}} hideLegend={true} mapOptions={{zoom: 11, center: group.googleLocation.geometry.location, initialOpenWindows:[groupId]}} /> : <div className={classes.topSection}></div>; let smallMap; // if the group has a banner image, show that at the top instead, and move the map down if (group.bannerImageId) { topSection = <div className={classes.imageContainer}> <CloudinaryImage2 imgProps={{ar: '191:100', w: '765'}} publicId={group.bannerImageId} className={classes.bannerImg} /> </div> smallMap = (group.googleLocation && !group.isOnline) && <CommunityMapWrapper className={classes.mapContainer} terms={{view: "events", groupId: groupId}} groupQueryTerms={{view: "single", groupId: groupId}} hideLegend={true} mapOptions={{zoom: 5, center: group.googleLocation.geometry.location}} /> } const groupHasContactInfo = group.facebookLink || group.facebookPageLink || group.meetupLink || group.slackLink || group.website || group.contactInfo // the EA Forum shows the group's events as event cards instead of post list items let upcomingEventsList = <PostsList2 terms={{view: 'upcomingEvents', groupId: groupId}} /> if (isEAForum) { upcomingEventsList = !!upcomingEvents?.length ? ( <div className={classes.eventCards}> <EventCards events={upcomingEvents} loading={upcomingEventsLoading} numDefaultCards={2} hideSpecialCards hideGroupNames /> <LoadMore {...upcomingEventsLoadMoreProps} loadingClassName={classes.loading} /> </div> ) : <Components.Typography variant="body2" className={classes.noUpcomingEvents}>No upcoming events.{' '} <NotifyMeButton showIcon={false} document={group} subscribeMessage="Subscribe to be notified when an event is added." componentIfSubscribed={<span>We'll notify you when an event is added.</span>} className={classes.notifyMeButton} /> </Components.Typography> } let tbdEventsList: JSX.Element|null = <PostsList2 terms={{view: 'tbdEvents', groupId: groupId}} showNoResults={false} /> if (isEAForum) { tbdEventsList = tbdEvents?.length ? <> <Components.Typography variant="headline" className={classes.eventsHeadline}> Events Yet To Be Scheduled </Components.Typography> <div className={classes.eventCards}> <EventCards events={tbdEvents} loading={tbdEventsLoading} hideSpecialCards hideGroupNames /> <LoadMore {...tbdEventsLoadMoreProps} /> </div> </> : null } let pastEventsList: JSX.Element|null = <> <Components.Typography variant="headline" className={classes.eventsHeadline}> Past Events </Components.Typography> <PostsList2 terms={{view: 'pastEvents', groupId: groupId}} /> </> if (isEAForum) { pastEventsList = pastEvents?.length ? <> <Components.Typography variant="headline" className={classes.eventsHeadline}> Past Events </Components.Typography> <div className={classes.eventCards}> <EventCards events={pastEvents} loading={pastEventsLoading} hideSpecialCards hideGroupNames cardClassName={classes.pastEventCard} /> <LoadMore {...pastEventsLoadMoreProps} /> </div> </> : null } return ( <div className={classes.root}> <HeadTags title={group.name} description={group.contents?.plaintextDescription} image={group.bannerImageId && `https://res.cloudinary.com/cea/image/upload/q_auto,f_auto/${group.bannerImageId}.jpg`} /> {topSection} <SingleColumnSection> <div className={classes.titleRow}> <div> <SectionTitle title={ <span>{group.inactive ? <span className={classes.inactiveGroupTag}>[Inactive]</span> : null}{group.name}</span> } noTopMargin /> <div className={classes.groupLocation}> <LocationIcon className={classes.groupLocationIcon} /> {group.isOnline ? 'Online Group' : group.location} </div> {group.categories?.length > 0 && <div className={classes.groupCategories}> {group.categories.map(category => { return <div key={category} className={classes.groupCategory}>{GROUP_CATEGORIES.find(option => option.value === category)?.label}</div> })} </div>} </div> <div> {currentUser && <SectionButton className={classes.notifyMe}> <NotifyMeButton showIcon document={group} subscribeMessage="Subscribe to group" unsubscribeMessage="Unsubscribe from group" /> </SectionButton>} <SectionFooter className={classes.organizerActions}> {Posts.options.mutations.new.check(currentUser) && (!isEAForum || isAdmin || isGroupAdmin) && <SectionButton> <Link to={{pathname:"/newPost", search: `?${qs.stringify({eventForm: true, groupId})}`}}> New event </Link> </SectionButton>} {Localgroups.options.mutations.edit.check(currentUser, group) && (!isEAForum || isAdmin || isGroupAdmin ) && <GroupFormLink documentId={groupId} /> } </SectionFooter> </div> </div> <ContentStyles contentType="post" className={classes.groupDescription}> {group.contents && <ContentItemBody dangerouslySetInnerHTML={htmlBody} className={classes.groupDescriptionBody} description={`group ${groupId}`} />} </ContentStyles> <PostsList2 terms={{view: 'nonEventGroupPosts', groupId: groupId}} showNoResults={false} /> {(groupHasContactInfo || smallMap) && <div className={classes.contactUsSection}> {groupHasContactInfo && <div className={classes.externalLinkBtns}> <Components.Typography variant="headline" className={classes.contactUsHeadline}> Contact Us </Components.Typography> <div> {group.facebookLink && <div className={classes.externalLinkBtnRow}> <Button variant="contained" color="primary" href={group.facebookLink} target="_blank" rel="noopener noreferrer" className={classes.externalLinkBtn} > <FacebookIcon className={classes.facebookGroupIcon} /> See our Facebook group </Button> </div>} {group.facebookPageLink && <div className={classes.externalLinkBtnRow}> <Button variant="contained" color="primary" href={group.facebookPageLink} target="_blank" rel="noopener noreferrer" className={classes.externalLinkBtn} > <RoundFacebookIcon className={classes.facebookPageIcon} /> Learn more on our Facebook page </Button> </div>} {group.meetupLink && <div className={classes.externalLinkBtnRow}> <Button variant="contained" color="primary" href={group.meetupLink} target="_blank" rel="noopener noreferrer" className={classes.externalLinkBtn} > <MeetupIcon className={classes.meetupIcon} /> Find us on Meetup </Button> </div>} {group.slackLink && <div className={classes.externalLinkBtnRow}> <Button variant="contained" color="primary" href={group.slackLink} target="_blank" rel="noopener noreferrer" className={classes.externalLinkBtn} > <SlackIcon className={classes.slackIcon} /> Join us on Slack </Button> </div>} {group.website && <div className={classes.externalLinkBtnRow}> <Button variant="outlined" color="primary" href={group.website} target="_blank" rel="noopener noreferrer" className={classes.externalLinkBtn} > <LinkIcon className={classes.linkIcon} /> Explore our website </Button> </div>} {group.contactInfo && <div className={classes.externalLinkBtnRow}> <Button variant="outlined" color="primary" href={`mailto:${group.contactInfo}`} className={classes.externalLinkBtn}> <EmailIcon className={classes.emailIcon} /> Email the organizers </Button> </div>} </div> </div>} {smallMap} </div>} <Components.Typography variant="headline" className={classes.eventsHeadline}> Upcoming Events </Components.Typography> {upcomingEventsList} {tbdEventsList} {pastEventsList} </SingleColumnSection> </div> ) } const LocalGroupPageComponent = registerComponent('LocalGroupPage', LocalGroupPage, {styles}); declare global { interface ComponentTypes { LocalGroupPage: typeof LocalGroupPageComponent } }
the_stack
'use strict'; import * as React from 'react'; import {connect} from 'react-redux'; import {State} from '../../store'; import {InteractionRecord, ApplicationRecord, SelectionRecord, ScaleInfo, MarkApplicationRecord, PointSelectionRecord, IntervalSelectionRecord, IntervalSelection, PointSelection, MarkApplication, ScaleApplication, TransformApplication, InteractionInput, InteractionSignal, getInteractionSignals, TransformApplicationRecord, ScaleApplicationRecord, applicationIsEnabled} from '../../store/factory/Interaction'; import {GroupRecord} from '../../store/factory/marks/Group'; import {setInput, setSelection, setApplication, removeApplication, toggleEnableApplicationType, setSignals} from '../../actions/interactionActions'; import {getScaleInfoForGroup, getNestedMarksOfGroup, getFieldsOfGroup} from '../../ctrl/demonstrations'; import {ScaleSimpleType, scaleTypeSimple} from '../../store/factory/Scale' import {DatasetRecord} from '../../store/factory/Dataset'; import {MarkRecord} from '../../store/factory/Mark'; import exportName from '../../util/exportName'; import InteractionPreview from '../interactions/InteractionPreview'; import {Map} from 'immutable'; import {debounce} from 'vega'; import {InteractionInputType} from './InteractionInputType'; import {InteractionSignals} from './InteractionSignals'; import {signalLookup} from '../../util/signal-lookup'; import {batchGroupBy} from '../../reducers/historyOptions'; import {InteractionApplicationProperties} from './InteractionApplicationProperties'; const ctrl = require('../../ctrl'); const listeners = require('../../ctrl/listeners'); interface OwnProps { primId: number; } interface OwnState { selectionPreviews: SelectionRecord[] applicationPreviews: ApplicationRecord[] } interface DispatchProps { setInput: (input: InteractionInput, id: number) => void; setSelection: (record: SelectionRecord, id: number) => void; toggleEnableApplicationType: (payload: ApplicationRecord, id: number) => void; setApplication: (record: ApplicationRecord, id: number) => void; removeApplication: (record: ApplicationRecord, id: number) => void; setSignals: (signals: InteractionSignal[], id: number) => void; } interface StateProps { groups: Map<number, GroupRecord>; interaction: InteractionRecord; scaleInfo: ScaleInfo; datasets: Map<string, DatasetRecord>; groupName: string; marksOfGroups: Map<number, MarkRecord[]>; // map of group ids to array of mark specs fieldsOfGroup: string[]; markScalesOfGroup: MarkScales[]; canDemonstrate: boolean; isDemonstratingInterval: boolean; } interface MarkScales { mark: MarkRecord; xScaleType: ScaleSimpleType; yScaleType: ScaleSimpleType; scaleFields: string[]; } function mapStateToProps(state: State, ownProps: OwnProps): StateProps { const interaction: InteractionRecord = state.getIn(['vis', 'present', 'interactions', String(ownProps.primId)]); const groupId = interaction.get('groupId'); const scaleInfo: ScaleInfo = getScaleInfoForGroup(state, groupId); const group: GroupRecord = state.getIn(['vis', 'present', 'marks', String(groupId)]); const groupName = exportName(group.name); const marks: Map<string, MarkRecord> = state.getIn(['vis', 'present', 'marks']); const groups: Map<number, GroupRecord> = marks.filter((mark: MarkRecord) => { return mark.type === 'group'; }).mapEntries(([k, v]) => { return [Number(k), v as GroupRecord]; }); const marksOfGroups: Map<number, MarkRecord[]> = groups.map(group => { return getNestedMarksOfGroup(state, group); }); const scaleInfoOfGroups: Map<number, ScaleInfo> = groups.map(group => { return getScaleInfoForGroup(state, group._id); }); const marksOfGroup = marksOfGroups.get(groupId); const datasets: Map<string, DatasetRecord> = state.getIn(['vis', 'present', 'datasets']); const fieldsOfGroup = getFieldsOfGroup(state, group._id); const isParsing = state.getIn(['vega', 'isParsing']); const canDemonstrate = Boolean(!isParsing && ctrl.view && (scaleInfo.xScaleName && scaleInfo.xFieldName || scaleInfo.yScaleName && scaleInfo.yFieldName)); const isDemonstratingInterval = interaction.input ? interaction.input.mouse === 'drag' : null; const markScalesOfGroup = marksOfGroup.map(mark => { let xScaleType, yScaleType = null; if (mark.encode && mark.encode.update && mark.encode.update.x && (mark.encode.update.x as any).scale) { const xScaleId = (mark.encode.update.x as any).scale; const xScaleRecord = state.getIn(['vis', 'present', 'scales', String(xScaleId)]); xScaleType = scaleTypeSimple(xScaleRecord.get('type')); } if (mark.encode && mark.encode.update && mark.encode.update.y && (mark.encode.update.y as any).scale) { const yScaleId = (mark.encode.update.y as any).scale; const yScaleRecord = state.getIn(['vis', 'present', 'scales', String(yScaleId)]); yScaleType = scaleTypeSimple(yScaleRecord.get('type')); } const scaleFields = []; if (mark.encode && mark.encode.update && mark.encode.update) { for (const [key, value] of Object.entries(mark.encode.update)) { if (key === 'x' || key === 'y' || !value) continue; const field = (value as any).field; if (field) { scaleFields.push(field); } } } return { mark, xScaleType, yScaleType, scaleFields } }); return { interaction, groups, scaleInfo, groupName, datasets, marksOfGroups, fieldsOfGroup, markScalesOfGroup, canDemonstrate, isDemonstratingInterval }; } const actionCreators: DispatchProps = {setInput, setSelection, toggleEnableApplicationType, setApplication, removeApplication, setSignals}; function generateSelectionPreviews(markScalesOfGroup: MarkScales[], interaction: InteractionRecord, isDemonstratingInterval: boolean): SelectionRecord[] { if (isDemonstratingInterval) { const defs: IntervalSelectionRecord[] = []; const brush = IntervalSelection({ id: "brush", label: "Brush" }); const brush_y = IntervalSelection({ id: "brush_y", label: "Brush (y-axis)", encoding: 'y' }); const brush_x = IntervalSelection({ id: "brush_x", label: "Brush (x-axis)", encoding: 'x' }); // HEURISTICS: surface different interval selections depending on mark type markScalesOfGroup.forEach(markScales => { const {mark, xScaleType, yScaleType} = markScales; switch (mark.type) { case 'rect': if (xScaleType === ScaleSimpleType.DISCRETE || yScaleType === ScaleSimpleType.DISCRETE) { if (xScaleType === ScaleSimpleType.DISCRETE) { defs.push(brush_x); } if (yScaleType === ScaleSimpleType.DISCRETE) { defs.push(brush_y); } } else { if (xScaleType === ScaleSimpleType.CONTINUOUS && yScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush); if (yScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush_y); if (xScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush_x); } break; case 'symbol': case 'text': if (xScaleType === ScaleSimpleType.CONTINUOUS && yScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush); if (yScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush_y); if (xScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush_x); break; case 'line': if (yScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush_y); if (xScaleType === ScaleSimpleType.CONTINUOUS) defs.push(brush_x); break; case 'area': const areaMark = mark.toJS(); const orient = areaMark.encode?.update?.orient; const value = orient ? orient.value || signalLookup(orient.signal) : null; if (value) { // TODO(jzong) what if orient is not in update but is in one of the other ones? if (value === 'vertical' && xScaleType) { defs.push(brush_x); } else if (value === 'horizontal' && yScaleType) { defs.push(brush_y); } } break; } }); return [... new Set(defs)]; } else { let field = '_vgsid_'; if (interaction && interaction.selection) { const selection = (interaction.selection as PointSelectionRecord); if (selection.field && selection.field !== '_vgsid_') { field = selection.field } } if (field === '_vgsid_') { const boundFields = new Set<string>(); markScalesOfGroup.forEach(markScales => { markScales.scaleFields.forEach(field => { boundFields.add(field); }) }); if (boundFields.size) { field = boundFields.values().next().value; } } const defs: PointSelectionRecord[] = [ PointSelection({ ptype: 'single', id: 'single', label: 'Single point', field: '_vgsid_' }), PointSelection({ ptype: 'multi', id: 'multi', label: 'Multi point', field: '_vgsid_' }), PointSelection({ ptype: 'single', id: 'single_project', label: 'Single point (projected)', field: field, encoding: null }), PointSelection({ ptype: 'multi', id: 'multi_project', label: 'Multi point (projected)', field: field, encoding: null }) ]; return defs; } } function generateApplicationPreviews(groupId: number, groupName: string, marksOfGroup: MarkRecord[], scaleInfo: ScaleInfo, groups: Map<number, GroupRecord>, marksOfGroups: Map<number, MarkRecord[]>, datasets: Map<string, DatasetRecord>, isDemonstratingInterval: boolean): ApplicationRecord[] { const defs: ApplicationRecord[] = []; if (marksOfGroup.length) { const mark = marksOfGroup[0]; const maybeSymbol = marksOfGroup.find(mark => mark.type === 'symbol'); defs.push(MarkApplication({ id: "color_" + isDemonstratingInterval, label: "Color", targetGroupName: groupName, targetMarkName: exportName(mark.name), propertyName: mark.type === 'line' ? "stroke" : "fill", unselectedValue: "#797979" })); defs.push(MarkApplication({ id: "opacity_" + isDemonstratingInterval, label: "Opacity", targetGroupName: groupName, targetMarkName: exportName(mark.name), propertyName: "opacity", unselectedValue: "0.2" })); if (maybeSymbol) { defs.push(MarkApplication({ id: "size_" + isDemonstratingInterval, label: "Size", targetGroupName: groupName, targetMarkName: exportName(maybeSymbol.name), propertyName: "size", unselectedValue: 30 })); } } if (isDemonstratingInterval) { defs.push(ScaleApplication({ id: "panzoom", label: "Pan and zoom", targetGroupName: groupName, scaleInfo })); } const otherGroup = groups.find(group => group._id !== groupId); if (otherGroup) { const otherGroupId = otherGroup._id; const marksOfOtherGroup = marksOfGroups.get(otherGroupId); const mark = marksOfOtherGroup.find(mark => mark.from && mark.from.data); // TODO(jzong): && mark.from.data === mark dataset in current group? if (mark) { const targetGroupName = exportName(otherGroup.name); const targetMarkName = exportName(mark.name); const datasetName = datasets.get(String(mark.from.data)).name; defs.push(TransformApplication({ id: "filter_" + targetGroupName + "_" + isDemonstratingInterval, label: "Filter", targetGroupName, datasetName, targetMarkName, })); } } return defs; } class BaseInteractionInspector extends React.Component<OwnProps & StateProps & DispatchProps, OwnState> { constructor(props) { super(props); this.state = { selectionPreviews: [], applicationPreviews: [] }; } public componentDidMount() { // necessary because state goes away when unmounting (when you close the inspector) if (this.props.interaction?.input) { const previews = this.generatePreviews(this.props.isDemonstratingInterval); this.setState(previews); } } private generatePreviews(isDemonstratingInterval: boolean): { selectionPreviews: SelectionRecord[], applicationPreviews: ApplicationRecord[] } { if (isDemonstratingInterval === null) { return { selectionPreviews: [], applicationPreviews: [] } } const marksOfGroup = this.props.marksOfGroups.get(this.props.interaction.groupId); return { selectionPreviews: generateSelectionPreviews(this.props.markScalesOfGroup, this.props.interaction, isDemonstratingInterval), applicationPreviews: generateApplicationPreviews(this.props.interaction.groupId, this.props.groupName, marksOfGroup, this.props.scaleInfo, this.props.groups, this.props.marksOfGroups, this.props.datasets, isDemonstratingInterval) }; }; public componentDidUpdate(prevProps: OwnProps & StateProps, prevState) { if (!prevProps.canDemonstrate && this.props.canDemonstrate) { this.restoreMainViewSignals(this.props.groupName); this.restorePreviewSignals(); this.onSignal(this.props.groupName, this.scopedSignalName('points_tuple'), (name, value) => this.onMainViewPointSignal(name, value)); this.onSignal(this.props.groupName, this.scopedSignalName('points_tuple_projected'), (name, value) => this.onMainViewPointSignal(name, value)); this.onSignal(this.props.groupName, this.scopedSignalName('points_toggle'), (name, value) => this.onMainViewPointSignal(name, value)); this.onSignal(this.props.groupName, this.scopedSignalName('brush_x'), (name, value) => this.onMainViewIntervalSignal(name, value)); this.onSignal(this.props.groupName, this.scopedSignalName('brush_y'), (name, value) => this.onMainViewIntervalSignal(name, value)); this.onSignal(this.props.groupName, this.scopedSignalName('grid_translate_anchor'), (name, value) => this.onMainViewGridSignal(name, value)); this.onSignal(this.props.groupName, this.scopedSignalName('grid_translate_delta'), (name, value) => this.onMainViewGridSignal(name, value)); if (this.props.interaction?.signals?.length) { this.props.interaction.signals.forEach(s => { this.onSignal(this.props.groupName, s.signal, (name, value) => this.updatePreviewSignals(name, value)); }) } } // necessary to handle undo/redo if (this.props.interaction?.selection) { if (!this.state.selectionPreviews?.find(x => x.id === this.props.interaction.selection.id)) { const previews = this.generatePreviews(this.props.isDemonstratingInterval); this.setState(previews); } } } private scopedSignalName(signalName: string) { return `${signalName}_${this.props.interaction.id}` } private restoreMainViewSignals(groupName) { for (let signalName of ['brush_x', 'brush_y', 'points_tuple', 'points_tuple_projected'].map(s => this.scopedSignalName(s))) { if (this.mainViewSignalValues[signalName]) { listeners.setSignalInGroup(ctrl.view, groupName, signalName, this.mainViewSignalValues[signalName]); } } } private clearMainViewSignals(groupName) { for (let signalName of ['brush_x', 'brush_y', 'points_tuple', 'points_tuple_projected'].map(s => this.scopedSignalName(s))) { this.mainViewSignalValues[signalName] = null; listeners.setSignalInGroup(ctrl.view, groupName, signalName, null); } } private restorePreviewSignals() { for (let signalName of ['brush_x', 'brush_y', 'points_tuple', 'points_tuple_projected'].map(s => this.scopedSignalName(s))) { if (this.mainViewSignalValues[signalName]) { setTimeout(() => { this.updatePreviewSignals(signalName, this.mainViewSignalValues[signalName]); }, 50); // somehow it only works if you have both of these??? some kind of vega invalidation thing this.updatePreviewSignals(signalName, this.mainViewSignalValues[signalName]); } } } private previewRefs = {}; // id -> ref private mainViewSignalValues = {}; // name -> value private updatePreviewSignals(name, value) { this.state.selectionPreviews.forEach(preview => { if (this.previewRefs[preview.id]) { this.previewRefs[preview.id].setPreviewSignal(name, value); } }); this.state.applicationPreviews.forEach(preview => { if (this.previewRefs[preview.id]) { this.previewRefs[preview.id].setPreviewSignal(name, value); } }); } private updateIsDemonstrating = debounce(250, () => { // debounce is important const intervalActive = (this.mainViewSignalValues[this.scopedSignalName('brush_x')] && this.mainViewSignalValues[this.scopedSignalName('brush_y')] && Math.abs(this.mainViewSignalValues[this.scopedSignalName('brush_x')][0] - this.mainViewSignalValues[this.scopedSignalName('brush_x')][1]) > 10 && Math.abs(this.mainViewSignalValues[this.scopedSignalName('brush_y')][0] - this.mainViewSignalValues[this.scopedSignalName('brush_y')][1]) > 10); const pointActive = this.mainViewSignalValues[this.scopedSignalName('points_tuple')] || this.mainViewSignalValues[this.scopedSignalName('points_tuple_projected')]; const isDemonstratingInterval = intervalActive || this.props.isDemonstratingInterval && !pointActive; if (this.props.isDemonstratingInterval !== isDemonstratingInterval) { // re-initialize interaction using a demonstration if if (!this.props.interaction.selection || // it hasn't been initialized (this.state.selectionPreviews.length && this.props.interaction.selection.id === this.state.selectionPreviews[0].id) && !this.props.interaction.applications.length // user hasn't touched the default selection / application ) { this.initializeInteraction(isDemonstratingInterval ? 'drag' : 'click'); } } }); private initializeInteraction(mouse: InteractionInput['mouse'], didUseDropdown?: boolean) { const isDemonstratingInterval = mouse === 'drag'; const previews = this.generatePreviews(isDemonstratingInterval); this.setState(previews); if (didUseDropdown) { // clear the demonstration signals so that they don't reset the dropdown choice this.clearMainViewSignals(this.props.groupName) } batchGroupBy.start(); let input = this.props.interaction.input; if (!this.props.interaction.input) { const inputKeyboard: InteractionInput = (window as any)._inputKeyboard; input = { mouse, keycode: inputKeyboard ? inputKeyboard.keycode : undefined, _key: inputKeyboard ? inputKeyboard._key : undefined }; } else { input = { ...this.props.interaction.input, mouse, } } this.props.setInput(input, this.props.primId); let didHeuristicSetSelection = false; if (isDemonstratingInterval) { didHeuristicSetSelection = this.updateBrushXYHeuristic(); } else { didHeuristicSetSelection = this.updatePointMultiHeuristic(); } if (!didHeuristicSetSelection) this.props.setSelection(previews.selectionPreviews[0], this.props.interaction.id); const signals = getInteractionSignals(this.props.interaction.id, input, this.props.scaleInfo, this.props.fieldsOfGroup); this.props.setSignals(signals, this.props.interaction.id); batchGroupBy.end(); } private updateBrushXYHeuristic() { if (this.props.interaction && this.props.interaction.selection) return; const brush_x = this.mainViewSignalValues[this.scopedSignalName('brush_x')]; const brush_y = this.mainViewSignalValues[this.scopedSignalName('brush_y')]; if (!(brush_x && brush_y)) return; const d_brush_x = Math.abs(brush_x[1] - brush_x[0]); const d_brush_y = Math.abs(brush_y[1] - brush_y[0]); const threshold_distance = 10; if (!(Math.sqrt(d_brush_y * d_brush_y + d_brush_x * d_brush_x) > threshold_distance)) return; const atan2_degrees = Math.abs(Math.atan2(d_brush_y, d_brush_x)) * 180 / Math.PI; const threshold_degrees = 15; if (atan2_degrees <= threshold_degrees) { const brush_x_selection = this.state.selectionPreviews.find(s => s.id === 'brush_x'); if (brush_x_selection) { this.props.setSelection(brush_x_selection, this.props.interaction.id); return true; } } if (atan2_degrees >= 90 - threshold_degrees) { const brush_y_selection = this.state.selectionPreviews.find(s => s.id === 'brush_y'); if (brush_y_selection) { this.props.setSelection(brush_y_selection, this.props.interaction.id); return true; } } } private updatePointMultiHeuristic() { if (this.props.interaction && this.props.interaction.selection) return; const points_tuple = this.mainViewSignalValues[this.scopedSignalName('points_tuple')]; if (!(points_tuple && this.previousPointSignal)) return; const point_multi_selection = this.state.selectionPreviews.find(s => s.id === 'multi'); if (point_multi_selection) { this.props.setSelection(point_multi_selection, this.props.interaction.id); return true; } } // for the purposes of demonstrating multi point selection by quickly clicking multiple points private previousPointSignal = null; private previousPointSignalTimeout = null; private onMainViewPointSignal(name, value) { if (this.mainViewSignalValues[name] !== value) { if (name.indexOf('points_tuple') >= 0) { clearTimeout(this.previousPointSignalTimeout); this.previousPointSignal = this.mainViewSignalValues[name]; this.previousPointSignalTimeout = setTimeout(() => { this.previousPointSignal = null; }, 800); } this.mainViewSignalValues[name] = value; this.updateIsDemonstrating(); this.updatePreviewSignals(name, value); } } private onMainViewIntervalSignal(name, value) { if (this.mainViewSignalValues[name] !== value) { this.mainViewSignalValues[name] = value; this.updateIsDemonstrating(); // TODO: consider adding this.updateBrushXYHeuristic() debounced here this.updatePreviewSignals(name, value); } } private onMainViewGridSignal(name, value) { this.mainViewSignalValues[name] = value; this.updatePreviewSignals(name, value); } private onSignal(groupName, signalName, handler) { listeners.onSignalInGroup(ctrl.view, groupName, signalName, handler); } private onClickInteractionPreview(preview: SelectionRecord | ApplicationRecord) { switch (preview.type) { case 'point': case 'interval': if (this.props.interaction) { this.props.setSelection(preview as SelectionRecord, this.props.interaction.id); } break; case 'mark': case 'scale': case 'transform': if (this.props.interaction) { preview = preview as ApplicationRecord; this.props.toggleEnableApplicationType(preview, this.props.interaction.id); if (!this.props.interaction.applications.some(application => { return application.id === preview.id; })) { this.props.setApplication(preview, this.props.interaction.id); } } break; } } private getProjectionOptions(preview: PointSelectionRecord) { const fieldOptions = [ <option key='_vgsid_' value={'_vgsid_'}>None</option>, ...this.props.fieldsOfGroup.map(field => <option key={field} value={field}>{field}</option>) ]; return ( <div> <div className="property"> <label htmlFor='project_fields'>Field:</label> <div className='control'> <select name='project_fields' value={preview.field} onChange={e => this.onSelectProjectionField(preview, e.target.value)}> {fieldOptions} </select> </div> </div> <div className="property"> <label htmlFor='project_encodings'>Encoding:</label> <div className='control'> <select name='project_encodings' value={preview.encoding} onChange={e => this.onSelectProjectionEncoding(preview, e.target.value)}> <option key='null' value='null'>None</option> <option key='x' value='x'>x</option> <option key='y' value='y'>y</option> </select> </div> </div> </div> ); } private onSelectProjectionField(preview: PointSelectionRecord, field: string) { const newPreview = preview.set('field', field); this.props.setSelection(newPreview, this.props.interaction.id); } private onSelectProjectionEncoding(preview: PointSelectionRecord, encoding: string) { let newPreview; switch (encoding) { case 'x': newPreview = preview.set('encoding', 'x'); break; case 'y': newPreview = preview.set('encoding', 'y'); break; default: newPreview = preview.set('encoding', null); break; } this.props.setSelection(newPreview, this.props.interaction.id); } public render() { const interaction = this.props.interaction; const applications = interaction.applications; return ( <div> <InteractionInputType interactionId={interaction.id} input={interaction.input} initializeInteraction={(m) => this.initializeInteraction(m, true)}></InteractionInputType> { interaction.input ? ( <div> <div className={"preview-controller"}> <div className='property-group'> <h3>Selections</h3> <div className="preview-scroll"> { this.state.selectionPreviews.map((preview) => { return ( <div key={preview.id} className={interaction && interaction.selection && interaction.selection.id === preview.id ? 'selected' : ''} onClick={() => this.onClickInteractionPreview(preview)}> <div className="preview-label">{preview.label}</div> <InteractionPreview ref={ref => this.previewRefs[preview.id] = ref} id={`preview-${preview.id}`} interaction={this.props.interaction} groupName={this.props.groupName} applicationPreviews={this.state.applicationPreviews} preview={preview} canDemonstrate={this.props.canDemonstrate}/> </div> ) }) } </div> { (interaction && interaction.selection && interaction.selection.id.includes('project')) ? ( this.getProjectionOptions(interaction.selection as PointSelectionRecord) ) : null } </div> <div className='property-group'> <h3>Applications</h3> <div className={"preview-scroll " + (this.state.applicationPreviews.length > 4 ? "overflow" : '')}> { this.state.applicationPreviews.map((preview) => { return ( <div key={preview.id} className={interaction && applicationIsEnabled(preview, interaction) ? 'selected' : ''}> <div onClick={() => this.onClickInteractionPreview(preview)}> <div className="preview-label">{preview.label}</div> <InteractionPreview ref={ref => this.previewRefs[preview.id] = ref} id={`preview-${preview.id}`} interaction={this.props.interaction} groupName={this.props.groupName} applicationPreviews={this.state.applicationPreviews} preview={preview} canDemonstrate={this.props.canDemonstrate}/> </div> </div> ) }) } </div> <InteractionApplicationProperties interaction={this.props.interaction} applications={applications} groups={this.props.groups} marksOfGroups={this.props.marksOfGroups}></InteractionApplicationProperties> </div> </div> <div className="property-group"> <h3>Signals</h3> <InteractionSignals interactionId={this.props.interaction.id} fieldsOfGroup={this.props.fieldsOfGroup} input={this.props.interaction.input} scaleInfo={this.props.scaleInfo}></InteractionSignals> </div> </div> ) : null } </div> ); } }; export const InteractionInspector = connect(mapStateToProps, actionCreators)(BaseInteractionInspector);
the_stack
export interface IForEachAble<T> extends Iterable<T> { forEach(callback: (v: T, i: number) => void): void; } /** * @internal */ export function isForEachAble<T>(v: IForEachAble<T> | any): v is IForEachAble<T> { return typeof v.forEach === 'function'; } /** * generalized version of Array function similar to Scala ISeq */ export interface ISequence<T> extends IForEachAble<T> { readonly length: number; filter(callback: (v: T, i: number) => boolean): ISequence<T>; map<U>(callback: (v: T, i: number) => U): ISequence<U>; some(callback: (v: T, i: number) => boolean): boolean; every(callback: (v: T, i: number) => boolean): boolean; reduce<U>(callback: (acc: U, v: T, i: number) => U, initial: U): U; } /** * @internal */ export function isSeqEmpty(seq: ISequence<any>) { return seq.every(() => false); // more efficient than counting length } /** * helper function for faster access to avoid function calls * @internal */ export function isIndicesAble<T>(it: Iterable<T>): it is ArrayLike<T> & Iterable<T> { return ( Array.isArray(it) || it instanceof Uint8Array || it instanceof Uint16Array || it instanceof Uint32Array || it instanceof Float32Array || it instanceof Int8Array || it instanceof Int16Array || it instanceof Int32Array || it instanceof Float64Array ); } declare type ISequenceBase<T> = ISequence<T> | (ArrayLike<T> & Iterable<T>); /** * sequence implementation that does the operation lazily on the fly */ class LazyFilter<T> implements ISequence<T> { private _length = -1; constructor(private readonly it: ISequenceBase<T>, private readonly filters: ((v: T, i: number) => boolean)[]) {} get length() { // cached if (this._length >= 0) { return this._length; } let l = 0; this.forEach(() => l++); this._length = l; return l; } filter(callback: (v: T, i: number) => boolean): ISequence<T> { // propagate filter return new LazyFilter(this.it, this.filters.concat(callback)); } map<U>(callback: (v: T, i: number) => U): ISequence<U> { // create lazy map out of myself return new LazyMap1(this, callback); } forEach(callback: (v: T, i: number) => void) { if (isIndicesAble(this.it)) { // fast array version outer: for (let i = 0; i < this.it.length; ++i) { const v = this.it[i]; for (const f of this.filters) { if (!f(v, i)) { continue outer; } } callback(v, i); } return; } // iterator version let valid = 0; const it = this.it[Symbol.iterator](); let v = it.next(); let i = 0; outer: while (!v.done) { for (const f of this.filters) { if (f(v.value, i)) { continue; } v = it.next(); i++; continue outer; } callback(v.value, valid++); v = it.next(); i++; } } [Symbol.iterator]() { const it = this.it[Symbol.iterator](); const next = () => { let v = it.next(); let i = -1; outer: while (!v.done) { i++; for (const f of this.filters) { if (f(v.value, i)) { continue; } // invalid go to next v = it.next(); continue outer; } return v; } return v; }; return { next }; } some(callback: (v: T, i: number) => boolean) { if (isIndicesAble(this.it)) { // fast array version outer: for (let i = 0; i < this.it.length; ++i) { const v = this.it[i]; for (const f of this.filters) { if (!f(v, i)) { continue outer; } } if (callback(v, i)) { return true; } } return false; } let valid = 0; const it = this.it[Symbol.iterator](); let v = it.next(); let i = 0; outer: while (!v.done) { for (const f of this.filters) { if (f(v.value, i)) { continue; } v = it.next(); i++; continue outer; } if (callback(v.value, valid++)) { return true; } v = it.next(); i++; } return false; } every(callback: (v: T, i: number) => boolean) { if (isIndicesAble(this.it)) { // fast array version outer: for (let i = 0; i < this.it.length; ++i) { const v = this.it[i]; for (const f of this.filters) { if (!f(v, i)) { continue outer; } } if (!callback(v, i)) { return false; } } return true; } let valid = 0; const it = this.it[Symbol.iterator](); let v = it.next(); let i = 0; outer: while (!v.done) { for (const f of this.filters) { if (f(v.value, i)) { continue; } v = it.next(); i++; continue outer; } if (!callback(v.value, valid++)) { return false; } v = it.next(); i++; } return true; } reduce<U>(callback: (acc: U, v: T, i: number) => U, initial: U) { if (isIndicesAble(this.it)) { // fast array version let acc = initial; let j = 0; outer: for (let i = 0; i < this.it.length; ++i) { const v = this.it[i]; for (const f of this.filters) { if (!f(v, i)) { continue outer; } } acc = callback(acc, v, j++); } return acc; } let valid = 0; const it = this.it[Symbol.iterator](); let v = it.next(); let i = 0; let r = initial; outer: while (!v.done) { for (const f of this.filters) { if (f(v.value, i)) { continue; } v = it.next(); i++; continue outer; } r = callback(r, v.value, valid++); v = it.next(); i++; } return r; } } /** * lazy mapping operation */ abstract class ALazyMap<T, T2> implements ISequence<T2> { constructor(protected readonly it: ISequenceBase<T>) {} get length() { return this.it.length; } filter(callback: (v: T2, i: number) => boolean): ISequence<T2> { return new LazyFilter(this, [callback]); } abstract map<U>(callback: (v: T2, i: number) => U): ISequence<U>; protected abstract mapV(v: T, i: number): T2; forEach(callback: (v: T2, i: number) => void) { if (isIndicesAble(this.it)) { for (let i = 0; i < this.it.length; ++i) { callback(this.mapV(this.it[i], i), i); } return; } const it = this.it[Symbol.iterator](); for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { callback(this.mapV(v.value, i), i); } } [Symbol.iterator]() { const it = this.it[Symbol.iterator](); let i = 0; const next = () => { const v = it.next(); if (v.done) { return { value: undefined as unknown as T2, done: true, }; } const value = this.mapV(v.value, i); i++; return { value, done: false, }; }; return { next }; } some(callback: (v: T2, i: number) => boolean) { if (isIndicesAble(this.it)) { for (let i = 0; i < this.it.length; ++i) { if (callback(this.mapV(this.it[i], i), i)) { return true; } } return false; } const it = this.it[Symbol.iterator](); for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { if (callback(this.mapV(v.value, i), i)) { return true; } } return false; } every(callback: (v: T2, i: number) => boolean) { if (isIndicesAble(this.it)) { for (let i = 0; i < this.it.length; ++i) { if (!callback(this.mapV(this.it[i], i), i)) { return false; } } return true; } const it = this.it[Symbol.iterator](); for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { if (!callback(this.mapV(v.value, i), i)) { return false; } } return true; } reduce<U>(callback: (acc: U, v: T2, i: number) => U, initial: U) { if (isIndicesAble(this.it)) { let acc = initial; for (let i = 0; i < this.it.length; ++i) { acc = callback(acc, this.mapV(this.it[i], i), i); } return acc; } const it = this.it[Symbol.iterator](); let acc = initial; for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { acc = callback(acc, this.mapV(v.value, i), i); } return acc; } } class LazyMap1<T1, T2> extends ALazyMap<T1, T2> implements ISequence<T2> { constructor(it: ISequenceBase<T1>, protected readonly map12: (v: T1, i: number) => T2) { super(it); } protected mapV(v: T1, i: number) { return this.map12(v, i); } map<U>(callback: (v: T2, i: number) => U): ISequence<U> { return new LazyMap2(this.it, this.map12, callback); } } class LazyMap2<T1, T2, T3> extends ALazyMap<T1, T3> implements ISequence<T3> { constructor( it: ISequenceBase<T1>, private readonly map12: (v: T1, i: number) => T2, private readonly map23: (v: T2, i: number) => T3 ) { super(it); } map<U>(callback: (v: T3, i: number) => U): ISequence<U> { return new LazyMap3(this.it, this.map12, this.map23, callback); } protected mapV(v: T1, i: number) { return this.map23(this.map12(v, i), i); } } class LazyMap3<T1, T2, T3, T4> extends ALazyMap<T1, T4> implements ISequence<T4> { constructor( it: ISequenceBase<T1>, private readonly map12: (v: T1, i: number) => T2, private readonly map23: (v: T2, i: number) => T3, private readonly map34: (v: T3, i: number) => T4 ) { super(it); } map<U>(callback: (v: T4, i: number) => U): ISequence<U> { const map1U = (v: T1, i: number) => callback(this.map34(this.map23(this.map12(v, i), i), i), i); return new LazyMap1(this.it, map1U); } protected mapV(v: T1, i: number) { return this.map34(this.map23(this.map12(v, i), i), i); } } class LazySeq<T> implements ISequence<T> { private _arr: ISequenceBase<T> | null = null; constructor(private readonly iterable: Iterable<T>) {} get arr() { if (this._arr) { return this._arr; } if (isIndicesAble(this.iterable)) { this._arr = this.iterable; } else { this._arr = Array.from(this.iterable); } return this._arr!; } [Symbol.iterator]() { return this.iterable[Symbol.iterator](); } filter(callback: (v: T, i: number) => boolean) { return new LazyFilter(this.arr, [callback]); } map<U>(callback: (v: T, i: number) => U) { return new LazyMap1(this.arr, callback); } forEach(callback: (v: T, i: number) => void) { if (isIndicesAble(this.iterable)) { for (let i = 0; i < this.iterable.length; ++i) { callback(this.iterable[i], i); } return; } const it = this[Symbol.iterator](); for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { callback(v.value, i); } } some(callback: (v: T, i: number) => boolean) { if (isIndicesAble(this.iterable)) { for (let i = 0; i < this.iterable.length; ++i) { if (callback(this.iterable[i], i)) { return true; } } return false; } const it = this[Symbol.iterator](); for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { if (callback(v.value, i)) { return true; } } return false; } every(callback: (v: T, i: number) => boolean) { if (isIndicesAble(this.iterable)) { for (let i = 0; i < this.iterable.length; ++i) { if (!callback(this.iterable[i], i)) { return false; } } return true; } const it = this[Symbol.iterator](); for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { if (!callback(v.value, i)) { return false; } } return true; } reduce<U>(callback: (acc: U, v: T, i: number) => U, initial: U) { if (isIndicesAble(this.iterable)) { let acc = initial; for (let i = 0; i < this.iterable.length; ++i) { acc = callback(acc, this.iterable[i], i); } return acc; } const it = this[Symbol.iterator](); let acc = initial; for (let v = it.next(), i = 0; !v.done; v = it.next(), i++) { acc = callback(acc, v.value, i); } return acc; } get length() { const it = this.iterable; if (isIndicesAble(it)) { return it.length; } if (it instanceof Set || it instanceof Map) { return it.size; } return this.arr.length; } } /** * @internal */ export function lazySeq<T>(iterable: Iterable<T>): ISequence<T> { return new LazySeq(iterable); } class ConcatSequence<T> implements ISequence<T> { constructor(private readonly seqs: ISequence<ISequence<T>>) { // } [Symbol.iterator]() { const seqs = Array.from(this.seqs); let it = seqs.shift()![Symbol.iterator](); const next = (): { value: T; done: boolean } => { const v = it.next(); if (!v.done) { return v as { value: T; done: boolean }; } if (seqs.length === 0) { // last last return v; } // next iterator and compute next element it = seqs.shift()![Symbol.iterator](); return next(); }; return { next }; } filter(callback: (v: T, i: number) => boolean): ISequence<T> { return new LazyFilter(this, [callback]); } map<U>(callback: (v: T, i: number) => U): ISequence<U> { return new LazyMap1(this, callback); } forEach(callback: (v: T, i: number) => void) { this.seqs.forEach((s) => s.forEach(callback)); } some(callback: (v: T, i: number) => boolean) { return this.seqs.some((s) => s.some(callback)); } every(callback: (v: T, i: number) => boolean) { return this.seqs.every((s) => s.every(callback)); } reduce<U>(callback: (acc: U, v: T, i: number) => U, initial: U) { return this.seqs.reduce((acc, s) => s.reduce(callback, acc), initial); } get length() { return this.seqs.reduce((a, b) => a + b.length, 0); } } /** * @internal */ export function concatSeq<T>(seqs: ISequence<ISequence<T>>): ISequence<T>; export function concatSeq<T>(seq1: ISequence<T>, seq2: ISequence<T>, ...seqs: ISequence<T>[]): ISequence<T>; export function concatSeq<T>( seq1: ISequence<T>[] | ISequence<T>, seq2?: ISequence<T>, ...seqs: ISequence<T>[] ): ISequence<T> { if (seq2) { return new ConcatSequence([seq1 as ISequence<T>, seq2].concat(seqs)); } return new ConcatSequence(seq1 as ISequence<T>[]); }
the_stack
import { ComponentRef } from '@angular/core'; import { PipelineStatus } from 'app/model/pipeline.model'; import * as d3 from 'd3'; import * as dagreD3 from 'dagre-d3'; import { GraphNode } from '../workflowv3.model'; export enum GraphDirection { HORIZONTAL = 'horizontal', VERTICAL = 'vertical' } export interface WithHighlight { getNodes(): Array<GraphNode>; setHighlight(active: boolean): void; setSelect(active: boolean): void; } export type ComponentFactory<T> = (nodes: Array<GraphNode>, type: string) => ComponentRef<T>; export class Node { key: string; width: number; height: number; } export class Edge { from: string; to: string; options: {}; } export class WorkflowV3Graph<T extends WithHighlight> { static margin = 40; // let 40px on top and bottom of the graph static marginSubGraph = 20; // let 20px on top and bottom of the sub graph static maxOriginScale = 1; static baseStageWidth = 300; static minStageWidth = 200; static minJobWidth = 60; nodesComponent = new Map<string, ComponentRef<T>>(); nodes = new Array<Node>(); edges = new Array<Edge>(); direction: string; zoom: d3.ZoomBehavior<Element, {}>; svg: d3.Selection<any, any, any, any>; g: d3.Selection<any, any, any, any>; graph: dagreD3.graphlib.Graph; render: dagreD3.Render; minScale = 1; maxScale = 1; transformed: any = null; componentFactory: ComponentFactory<T>; nodeOutNames: { [key: string]: string } = {}; nodeInNames: { [key: string]: string } = {}; forks: { [key: string]: { parents: Array<string>, children: Array<string> } } = {}; joins: { [key: string]: { parents: Array<string>, children: Array<string> } } = {}; nodeStatus: { [key: string]: string } = {}; currentSelectedNodeKey: string = null; constructor( factory: ComponentFactory<T>, direction: GraphDirection, minScale: number, maxScale: number ) { this.componentFactory = factory; this.direction = direction; this.graph = new dagreD3.graphlib.Graph().setGraph({ rankdir: this.direction === GraphDirection.VERTICAL ? 'TB' : 'LR', nodesep: 10, ranksep: 10, edgesep: 0 }); this.minScale = minScale; this.maxScale = maxScale; this.render = new dagreD3.render(); this.render.shapes().customRectH = WorkflowV3Graph.customRect(GraphDirection.HORIZONTAL); this.render.shapes().customRectV = WorkflowV3Graph.customRect(GraphDirection.VERTICAL); this.render.shapes().customCircle = WorkflowV3Graph.customCircle; this.render.arrows().customArrow = WorkflowV3Graph.customArrow; } static customRect = (direction: GraphDirection) => (parent, bbox, node) => { let shapeSvg = parent.insert('rect', ':first-child') .attr('rx', node.rx) .attr('ry', node.ry) .attr('x', -bbox.width / 2) .attr('y', -bbox.height / 2) .attr('width', bbox.width) .attr('height', bbox.height); node.intersect = (point) => { if (direction === GraphDirection.VERTICAL) { const h = ((node.height) / 2); return { x: node.x, y: node.y + (point.y < node.y ? -h : h) }; } const w = ((node.width) / 2); return { x: node.x + (point.x < node.x ? -w : w), y: node.y }; }; return shapeSvg; }; static customCircle = (parent, bbox, node) => { let r = Math.max(bbox.width, bbox.height) / 2; let shapeSvg = parent.insert('circle', ':first-child') .attr('x', -bbox.width / 2) .attr('y', -bbox.height / 2) .attr('r', r); node.intersect = point => ({ x: node.x, y: node.y }); return shapeSvg; }; static customArrow = (parent, id, edge, type) => { let markerHead = parent.append('marker') .attr('id', id) .attr('viewBox', '0 0 10 10') .attr('refX', 0) .attr('refY', 5) .attr('markerUnits', 'strokeWidth') .attr('markerWidth', 5) .attr('markerHeight', 5) .attr('orient', 'auto'); let pathHead = markerHead.append('path') .attr('d', 'M 0 5 L 10 5'); pathHead.attr('style', edge['style']); pathHead.attr('class', edge['class']); const arrowEndId = id.replace('head', 'start'); let markerEnd = parent.append('marker') .attr('id', arrowEndId) .attr('viewBox', '0 0 10 10') .attr('refX', 10) .attr('refY', 5) .attr('markerUnits', 'strokeWidth') .attr('markerWidth', 5) .attr('markerHeight', 5) .attr('orient', 'auto'); let pathEnd = markerEnd.append('path') .attr('d', 'M 0 5 L 10 5'); pathEnd.attr('style', edge['style']); pathEnd.attr('class', edge['class']); const makeFragmentRef = (url, fragmentId) => { const baseUrl = url.split('#')[0]; return `${baseUrl}#${fragmentId}`; }; const defs = parent._groups[0][0]; const edgePath = d3.select(defs.parentNode.childNodes[0]); edgePath.attr('marker-start', () => `url(${makeFragmentRef(location.href, arrowEndId)})`); }; resize(width: number, height: number): void { if (!this.svg) { return; } this.svg.attr('width', width); this.svg.attr('height', height); } clean(): void { this.graph.edges().forEach(e => this.graph.removeEdge(e.v, e.w)); this.graph.nodes().forEach(n => this.graph.removeNode(n)); this.nodesComponent.forEach(c => c.destroy()); this.nodesComponent = new Map<string, ComponentRef<T>>(); this.nodes = new Array<Node>(); this.edges = new Array<Edge>(); } draw(element: any, withZoom: boolean): void { d3.select(element).selectAll('svg').remove(); this.svg = d3.select(element).insert('svg'); this.g = this.svg.insert('g'); this.drawNodes(); this.drawEdges(); this.render(this.g, <any>this.graph); if (withZoom) { this.zoom = d3.zoom().scaleExtent([this.minScale, this.maxScale]).on('zoom', () => { if (d3.event.transform && d3.event.transform.x && d3.event.transform.x !== Number.POSITIVE_INFINITY && d3.event.transform.y && d3.event.transform.y !== Number.POSITIVE_INFINITY) { this.g.attr('transform', d3.event.transform); this.transformed = d3.event.transform; } }); this.svg.call(this.zoom); if (!!this.transformed) { this.svg.call(this.zoom.transform, d3.zoomIdentity.translate(this.transformed.x, this.transformed.y).scale(this.transformed.k)); } } if (this.currentSelectedNodeKey) { this.unselectAllNode(); this.selectNode(this.currentSelectedNodeKey); } } center(containerWidth: number, containerHeight: number): void { if (this.zoom) { let w = containerWidth - WorkflowV3Graph.margin * 2; let h = containerHeight - WorkflowV3Graph.margin * 2; let gw = this.graph.graph().width; let gh = this.graph.graph().height; let oScale = Math.min(w / gw, h / gh); // calculate optimal scale for current graph // calculate final scale that fit min and max scale values let scale = Math.min( WorkflowV3Graph.maxOriginScale, Math.max(this.minScale, oScale) ); let centerX = (w - gw * scale + WorkflowV3Graph.margin * 2) / 2; let centerY = (h - gh * scale + WorkflowV3Graph.margin * 2) / 2; this.svg.call(this.zoom.transform, d3.zoomIdentity.translate(centerX, centerY).scale(scale)); } else { let w = containerWidth - WorkflowV3Graph.marginSubGraph * 2; let h = containerHeight - WorkflowV3Graph.marginSubGraph * 2; let gw = this.graph.graph().width; let gh = this.graph.graph().height; let oScale = Math.min(w / gw, h / gh); // calculate optimal scale for current graph let centerX = (w - gw * oScale + WorkflowV3Graph.marginSubGraph * 2) / 2; let centerY = (h - gh * oScale + WorkflowV3Graph.marginSubGraph * 2) / 2; this.g.attr('transform', `translate(${centerX}, ${centerY}) scale(${oScale})`); } this.transformed = null; } centerNode(nodeName: string, containerWidth: number, containerHeight: number): void { if (!this.zoom) { return; } let node = this.graph.node(nodeName); // calculate optimal scale for current graph let oScale = Math.min((containerWidth - WorkflowV3Graph.margin * 2) / 300, (containerHeight - WorkflowV3Graph.margin * 2) / 169); // calculate final scale that fit min and max scale values let scale = Math.max(this.minScale, oScale); let nodeDeltaCenterX = containerWidth / 2 - node.x * scale; let nodeDeltaCenterY = containerHeight / 2 - node.y * scale; this.svg.call(this.zoom.transform, d3.zoomIdentity.translate(nodeDeltaCenterX, nodeDeltaCenterY).scale(scale)); } drawNodes(): void { this.nodes.forEach(n => { this.createGNode(`node-${n.key}`, this.nodesComponent.get(`node-${n.key}`), n.width, n.height, { class: n.key }); }); } uniqueStrings(a: Array<string>): Array<string> { let o = {}; a.forEach(s => o[s] = true); return Object.keys(o); } drawEdges(): void { let nodesChildren: { [key: string]: Array<string> } = {}; let nodesParents: { [key: string]: Array<string> } = {}; this.edges.forEach(e => { if (!nodesChildren[e.from]) { nodesChildren[e.from] = [e.to]; } else { nodesChildren[e.from] = this.uniqueStrings([...nodesChildren[e.from], e.to]); } if (!nodesParents[e.to]) { nodesParents[e.to] = [e.from]; } else { nodesParents[e.to] = this.uniqueStrings([...nodesParents[e.to], e.from]); } }); // Create fork this.forks = {}; this.nodeOutNames = {}; Object.keys(nodesChildren).forEach(c => { if (nodesChildren[c].length > 1) { const children = nodesChildren[c].map(n => n.split('node-')[1]).sort(); const keyFork = children.join('-'); if (this.forks[keyFork]) { this.forks[keyFork].parents = this.forks[keyFork].parents.concat(c); this.forks[keyFork].children = this.uniqueStrings(this.forks[keyFork].children.concat(nodesChildren[c])); } else { this.forks[keyFork] = { parents: [c], children: nodesChildren[c] }; } } }); Object.keys(this.forks).forEach(f => { let nodes = this.forks[f].parents.map(n => this.nodesComponent.get(n).instance.getNodes()).reduce((p, c) => p.concat(c)); const componentRef = this.componentFactory(nodes, 'fork'); let nodeKeys = this.forks[f].parents.map(n => n.split('node-')[1]).sort().join(' '); this.createGFork(f, componentRef, { class: `${nodeKeys}` }); this.nodeStatus[`fork-${f}`] = PipelineStatus.sum(nodes.map(n => n.run ? n.run.status : null)); this.forks[f].parents.forEach(n => { let edge = <Edge>{ from: n, to: `fork-${f}`, options: { class: `${f} ${n.split('node-')[1]}` } }; if (this.nodeStatus[`fork-${f}`]) { const color = this.nodeStatusToColor(this.nodeStatus[`fork-${f}`]); edge.options['class'] += ' ' + color; edge.options['style'] = 'stroke-width: 2px;'; } this.createGEdge(edge); this.nodeOutNames[n] = `fork-${f}`; }); }); // Create join this.joins = {}; this.nodeInNames = {}; Object.keys(nodesParents).forEach(p => { if (nodesParents[p].length > 1) { const parents = nodesParents[p].map(n => n.split('node-')[1]).sort(); const keyJoin = parents.join('-'); if (this.joins[keyJoin]) { this.joins[keyJoin].children = this.joins[keyJoin].children.concat(p); this.joins[keyJoin].parents = this.uniqueStrings(this.joins[keyJoin].children.concat(nodesParents[p])); } else { this.joins[keyJoin] = { children: [p], parents: nodesParents[p] }; } } }); Object.keys(this.joins).forEach(j => { let nodes = this.joins[j].parents.map(n => this.nodesComponent.get(n).instance.getNodes()).reduce((p, c) => p.concat(c)); const componentRef = this.componentFactory(nodes, 'join'); let nodeKeys = this.joins[j].children.map(n => n.split('node-')[1]).sort().join(' '); this.createGJoin(j, componentRef, { class: `${nodeKeys}` }); this.nodeStatus[`join-${j}`] = PipelineStatus.sum(nodes.map(n => n.run ? n.run.status : null)); this.joins[j].children.forEach(n => { let edge = <Edge>{ from: `join-${j}`, to: n, options: { class: `${j} ${n.split('node-')[1]}` } }; if (this.nodeStatus[`join-${j}`]) { const color = this.nodeStatusToColor(this.nodeStatus[`join-${j}`]); edge.options['class'] += ' ' + color; edge.options['style'] = 'stroke-width: 2px;'; } this.createGEdge(edge); this.nodeInNames[n] = `join-${j}`; }); }); let uniqueEdges: { [key: string]: { from: string, to: string, classes: Array<string> } } = {}; this.edges.forEach(e => { let from = this.nodeOutNames[e.from] ?? e.from; let to = this.nodeInNames[e.to] ?? e.to; let edgeKey = `${from}-${to}`; let nodeKeyFrom = e.from.split('node-')[1]; let nodeKeyTo = e.to.split('node-')[1]; if (!uniqueEdges[edgeKey]) { uniqueEdges[edgeKey] = { from, to, classes: [nodeKeyFrom, nodeKeyTo] }; return; } uniqueEdges[edgeKey].classes = this.uniqueStrings(uniqueEdges[edgeKey].classes.concat(nodeKeyFrom, nodeKeyTo)); }); Object.keys(uniqueEdges).forEach(edgeKey => { let e = uniqueEdges[edgeKey]; let options = { class: e.classes.join(' ') }; if (this.nodeStatus[e.from]) { const color = this.nodeStatusToColor(this.nodeStatus[e.from]); options['class'] += ' ' + color; options['style'] = 'stroke-width: 2px;'; } this.createGEdge(<Edge>{ from: e.from, to: e.to, options }); }); } nodeStatusToColor(s: string): string { switch (s) { case PipelineStatus.SUCCESS: return 'color-success'; case PipelineStatus.FAIL: return 'color-fail'; case PipelineStatus.WAITING: case PipelineStatus.DISABLED: case PipelineStatus.BUILDING: case PipelineStatus.PENDING: case PipelineStatus.NEVER_BUILT: case PipelineStatus.STOPPED: return 'color-inactive'; default: return ''; } } createNode(key: string, componentRef: ComponentRef<T>, status: string, width: number = 180, height: number = 60): void { this.nodes.push(<Node>{ key, width, height }); this.nodesComponent.set(`node-${key}`, componentRef); if (status) { this.nodeStatus[`node-${key}`] = status; } } createGNode(name: string, componentRef: ComponentRef<T>, width: number, height: number, options: {}): void { this.graph.setNode(name, <any>{ shape: this.direction === GraphDirection.VERTICAL ? 'customRectV' : 'customRectH', label: () => componentRef.location.nativeElement, labelStyle: `width: ${width}px;height: ${height}px;`, width, height, ...options }); } createGFork(key: string, componentRef: ComponentRef<T>, options: {}): void { this.nodesComponent.set(`fork-${key}`, componentRef); this.createGNode(`fork-${key}`, componentRef, 20, 20, { shape: 'customCircle', width: 60, height: 60, ...options }); } createGJoin(key: string, componentRef: ComponentRef<T>, options: {}): void { this.nodesComponent.set(`join-${key}`, componentRef); this.createGNode(`join-${key}`, componentRef, 20, 20, { shape: 'customCircle', width: 60, height: 60, ...options }); } createEdge(from: string, to: string): void { this.edges.push(<Edge>{ from, to }); } createGEdge(e: Edge): void { this.graph.setEdge(e.from, e.to, { arrowhead: 'customArrow', style: 'stroke: #B5B7BD;stroke-width: 2px;', curve: d3.curveBasis, ...e.options }); } nodeMouseEvent(type: string, key: string): void { switch (type) { case 'enter': this.highlightNode(true, key); break; case 'out': this.highlightNode(false, key); break; case 'click': this.unselectAllNode(); this.selectNode(key); break; } } unselectAllNode(): void { this.nodesComponent.forEach(n => n.instance.setSelect(false)); } selectNode(key: string): void { if (this.nodesComponent.has(`node-${key}`)) { this.nodesComponent.get(`node-${key}`).instance.setSelect(true); this.currentSelectedNodeKey = key; } else { this.currentSelectedNodeKey = null; } } highlightNode(active: boolean, key: string) { let selectionEdges = d3.selectAll(`.${key} > .path`); if (selectionEdges.size() > 0) { selectionEdges.attr('class', active ? 'path highlight' : 'path'); } let selectionEdgeMarkers = d3.selectAll(`.${key} > defs > marker > path`); if (selectionEdgeMarkers.size() > 0) { selectionEdgeMarkers.attr('class', active ? 'highlight' : ''); } if (this.nodesComponent.has(`node-${key}`)) { this.nodesComponent.get(`node-${key}`).instance.setHighlight(active); } let inName = this.nodeInNames[`node-${key}`]; if (inName !== `node-${key}`) { if (this.nodesComponent.has(inName)) { this.nodesComponent.get(inName).instance.setHighlight(active); } } let outName = this.nodeOutNames[`node-${key}`]; if (outName !== `node-${key}`) { if (this.nodesComponent.has(outName)) { this.nodesComponent.get(outName).instance.setHighlight(active); } } } }
the_stack
import { AbortController } from 'node-abort-controller'; import { AbortContext } from './AbortContext'; import { RootContext } from './RootContext'; describe('AbortContext', () => { afterEach(() => { jest.useRealTimers(); }); describe('forTimeoutMillis', () => { it('can abort on a timeout', async () => { jest.useFakeTimers(); const timeout = 200; const deadline = Date.now() + timeout; const root = new RootContext(); const child = AbortContext.forTimeoutMillis(root, timeout); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(child.abortSignal.aborted).toBe(false); expect(Math.abs(+child.deadline! - deadline)).toBeLessThan(50); expect(childListener).toBeCalledTimes(0); jest.advanceTimersByTime(timeout + 1); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(1); }); it('results in minimum deadline when parent triggers sooner', async () => { jest.useFakeTimers(); const parentTimeout = 200; const childTimeout = 300; const parentDeadline = Date.now() + parentTimeout; const childDeadline = parentDeadline; // clamped const root = new RootContext(); const parent = AbortContext.forTimeoutMillis(root, parentTimeout); const parentListener = jest.fn(); parent.abortSignal.addEventListener('abort', parentListener); const child = AbortContext.forTimeoutMillis(parent, childTimeout); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(false); expect(Math.abs(+parent.deadline! - parentDeadline)).toBeLessThan(50); expect(Math.abs(+child.deadline! - childDeadline)).toBeLessThan(50); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(0); jest.advanceTimersByTime(parentTimeout + 1); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(parentListener).toBeCalledTimes(1); expect(childListener).toBeCalledTimes(1); }); it('results in minimum deadline when child triggers sooner', async () => { jest.useFakeTimers(); const parentTimeout = 300; const childTimeout = 200; const parentDeadline = Date.now() + parentTimeout; const childDeadline = Date.now() + childTimeout; const root = new RootContext(); const parent = AbortContext.forTimeoutMillis(root, parentTimeout); const parentListener = jest.fn(); parent.abortSignal.addEventListener('abort', parentListener); const child = AbortContext.forTimeoutMillis(parent, childTimeout); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(false); expect(Math.abs(+parent.deadline! - parentDeadline)).toBeLessThan(50); expect(Math.abs(+child.deadline! - childDeadline)).toBeLessThan(50); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(0); jest.advanceTimersByTime(childTimeout + 1); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(true); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(1); jest.advanceTimersByTime(parentTimeout - childTimeout + 1); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(parentListener).toBeCalledTimes(1); expect(childListener).toBeCalledTimes(1); }); it('child carries over parent signal state if parent was already aborted and had no deadline', async () => { jest.useFakeTimers(); const childTimeout = 200; const childDeadline = Date.now() + childTimeout; const root = new RootContext(); const parentController = new AbortController(); const parent = AbortContext.forSignal(root, parentController.signal); parentController.abort(); const child = AbortContext.forTimeoutMillis(parent, childTimeout); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); expect(Math.abs(+child.deadline! - childDeadline)).toBeLessThan(50); jest.advanceTimersByTime(childTimeout + 1); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); // still }); it('child carries over parent signal state if parent was already aborted and had a deadline', async () => { jest.useFakeTimers(); const first = new RootContext(); const secondController = new AbortController(); const second = AbortContext.forSignal(first, secondController.signal); secondController.abort(); const third = AbortContext.forTimeoutMillis(second, 200); const fourth = AbortContext.forTimeoutMillis(third, 300); expect(third.abortSignal.aborted).toBe(true); expect(fourth.abortSignal.aborted).toBe(true); expect(Math.abs(+fourth.deadline! - Date.now() - 200)).toBeLessThan(50); }); }); describe('forController', () => { it('signals child when parent is aborted', () => { const root = new RootContext(); const parentController = new AbortController(); const parent = AbortContext.forController(root, parentController); const parentListener = jest.fn(); parent.abortSignal.addEventListener('abort', parentListener); const childController = new AbortController(); const child = AbortContext.forController(parent, childController); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(false); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(0); parentController.abort(); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(parentListener).toBeCalledTimes(1); expect(childListener).toBeCalledTimes(1); }); it('does not signal parent when child is aborted', async () => { const root = new RootContext(); const parentController = new AbortController(); const parent = AbortContext.forController(root, parentController); const parentListener = jest.fn(); parent.abortSignal.addEventListener('abort', parentListener); const childController = new AbortController(); const child = AbortContext.forController(parent, childController); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(false); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(0); childController.abort(); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(true); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(1); }); it('child carries over parent signal state if parent was already aborted', async () => { const root = new RootContext(); const parentController = new AbortController(); const parent = AbortContext.forController(root, parentController); parentController.abort(); const childController = new AbortController(); const child = AbortContext.forController(parent, childController); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); childController.abort(); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); }); it('child carries over given signal state if it was already aborted', async () => { const root = new RootContext(); const childController = new AbortController(); childController.abort(); const child = AbortContext.forController(root, childController); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); }); }); describe('forSignal', () => { it('signals child when parent is aborted', async () => { const root = new RootContext(); const parentController = new AbortController(); const parent = AbortContext.forSignal(root, parentController.signal); const parentListener = jest.fn(); parent.abortSignal.addEventListener('abort', parentListener); const childController = new AbortController(); const child = AbortContext.forSignal(parent, childController.signal); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(false); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(0); parentController.abort(); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(parentListener).toBeCalledTimes(1); expect(childListener).toBeCalledTimes(1); }); it('does not signal parent when child is aborted', async () => { const root = new RootContext(); const parentController = new AbortController(); const parent = AbortContext.forSignal(root, parentController.signal); const parentListener = jest.fn(); parent.abortSignal.addEventListener('abort', parentListener); const childController = new AbortController(); const child = AbortContext.forSignal(parent, childController.signal); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(false); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(0); childController.abort(); expect(parent.abortSignal.aborted).toBe(false); expect(child.abortSignal.aborted).toBe(true); expect(parentListener).toBeCalledTimes(0); expect(childListener).toBeCalledTimes(1); }); it('child carries over parent signal state if parent was already aborted', async () => { const root = new RootContext(); const parentController = new AbortController(); const parent = AbortContext.forSignal(root, parentController.signal); parentController.abort(); const childController = new AbortController(); const child = AbortContext.forSignal(parent, childController.signal); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); childController.abort(); expect(parent.abortSignal.aborted).toBe(true); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); }); it('child carries over given signal state if it was already aborted', async () => { const root = new RootContext(); const childController = new AbortController(); childController.abort(); const child = AbortContext.forSignal(root, childController.signal); const childListener = jest.fn(); child.abortSignal.addEventListener('abort', childListener); expect(child.abortSignal.aborted).toBe(true); expect(childListener).toBeCalledTimes(0); }); }); });
the_stack
import React, { HTMLAttributes, ReactNode, useCallback, useMemo, useRef } from 'react'; import classnames from 'classnames'; import Checkbox from 'src/components/Checkbox'; import useLocale from 'src/components/LocaleProvider/useLocale'; import { CollapseProps, useCollapse } from 'src/components/Collapse/hooks'; import CollapseContext from 'src/components/Collapse/CollapseContext'; import { useGroup, Key, groupChildrenAsDataSource, SubGroupMap, ChildrenMap } from 'src/hooks/group'; import useUncontrolled from 'src/hooks/useUncontrolled'; import noop from 'src/utils/noop'; import { Override } from 'src/type'; import once from 'src/utils/once'; import useVirtualList from 'src/hooks/useVirtualList'; import useSimpleVirtualList from 'src/hooks/useSimpleVirtualList'; import { MenuWrap, prefixCls, multipleCls, singleCls, selectallWrapCls, checkboxCls, blockCls, disabledCls } from './style'; import MenuContext from './MenuContext'; import LOCALE from './locale/zh_CN'; export interface MenuProps { /** 选中的菜单项的key,controlled */ selectedKeys?: Key[]; /** 默认选中的菜单项的key,uncontrolled */ defaultSelectedKeys?: Key[]; /** 选中变化时的回调 */ onChange?: (keys: Key[]) => void; /** 是否支持多选 */ multiple?: boolean; /** 是否可选 */ selectable?: boolean; /** 是否显示全选,多选时有效 */ showSelectAll?: boolean; /** 是否使用块元素显示模式,去除宽高限制,撑满容器,去除外阴影、border,方便放置在自定义容器中 */ block?: boolean; /** 是否禁用 */ disabled?: boolean; /** collapse 的配置,参考 collapse 组件 */ collapseProps?: CollapseProps; /** 启用虚拟滚动,启用后需要注意所有 item 需提供 key(可不提供 itemKey 和 subMenuKey,会使用 key 作为对应),且 Item key 和 SubMenu 不可重复,目前不支持 collapse 类 SubMenu */ virtualList?: | boolean | { // 简易模式,如确认每个 item 高度一致且不会变化可启用,可一定程度上优化性能 simple?: true; // 虚拟滚动的高度,默认为 200 height?: number; }; /** 自定义样式 */ customStyle?: { /** 菜单的最大高度 */ maxHeight?: string; /** 菜单的最大宽度 */ maxWidth?: string; }; /** @ignore */ locale?: typeof LOCALE; /** * @ignore * use for inner usage */ dataSource?: ReturnType<typeof groupChildrenAsDataSource>; } const warn = once(() => console.warn(`Virtual menu only support popover type of SubMenu`)); export const strictGroupChildrenAsDataSource = ( children: ReactNode, globalDisabled = false, { itemTag, subGroupTag, itemKeyName, subGroupKeyName }: { itemTag: string; subGroupTag?: string; itemKeyName: string; subGroupKeyName?: string; } = { itemTag: 'isItem', subGroupTag: 'isSubGroup', itemKeyName: 'itemKey', subGroupKeyName: 'subGroupKey' } ): [Key[], Key[], ReactNode[], SubGroupMap, ChildrenMap] => { const subGroupMap: SubGroupMap = new Map(); const childrenMap: ChildrenMap = new Map(); const group = (children: ReactNode, disabled: boolean, prefix: string): [Key[], Key[], ReactNode[]] => { const validKeys: Key[] = []; const disabledKeys: Key[] = []; const l = React.Children.count(children); const renderChildren: ReactNode[] = []; React.Children.forEach(children, (child, i) => { const isFirst = i === 0; const isLast = i === l - 1; if (React.isValidElement(child)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any if ((child.type as any)?.[itemTag]) { const props = child.props; const key = props[itemKeyName] === undefined ? child.key : props[itemKeyName]; const isDisabled = disabled || props.disabled; if (isDisabled) { disabledKeys.push(key); } else { validKeys.push(key); } childrenMap.set(key, props.children); renderChildren.push( React.cloneElement(child, { [itemKeyName]: key, disabled: globalDisabled || isDisabled, isFirst, isLast }) ); return; // eslint-disable-next-line @typescript-eslint/no-explicit-any } else if (subGroupTag && subGroupKeyName && (child.type as any)?.[subGroupTag]) { const props = child.props; const key = props[subGroupKeyName] || child.key || `${prefix}-${i}`; const isDisabled = disabled || props.disabled; const [subValidKeys, subDisabledKeys, subRenderChildren] = group( child.props.children, isDisabled, key ); subGroupMap.set(key, { validKeys: subValidKeys, disabledKeys: subDisabledKeys }); validKeys.push(...subValidKeys); disabledKeys.push(...subDisabledKeys); if (props.styleType === 'collapse') warn(); return renderChildren.push( React.cloneElement( child, { disabled: globalDisabled || isDisabled, [subGroupKeyName]: key, isFirst, isLast, styleType: 'popover' }, subRenderChildren ) ); } renderChildren.push(child); return; } }); return [validKeys, disabledKeys, renderChildren]; }; return [...group(children, false, 'group-root'), subGroupMap, childrenMap]; }; const Menu = ({ selectedKeys: _selectedKeys, defaultSelectedKeys = [], onChange: _onChange, selectable = true, multiple = false, showSelectAll, disabled, block, locale: _locale, className, children, dataSource, collapseProps, virtualList, ...rest }: MenuProps & Override<HTMLAttributes<HTMLDivElement>, MenuProps>) => { let [selectedKeys, onSelectedKeysChange] = useUncontrolled(_selectedKeys, defaultSelectedKeys, _onChange); // clean selectedStatus here let onChange = useCallback((keys: Key[]) => onSelectedKeysChange(keys), [onSelectedKeysChange]); if (!selectable) { // when unselectable clean selectedKeys and onChange handle selectedKeys = []; onChange = noop; } const locale = useLocale(LOCALE, 'Menu', _locale); const [validKeys, disabledKeys, renderChildren, subGroupMap] = useMemo( () => dataSource ? dataSource : (virtualList ? strictGroupChildrenAsDataSource : groupChildrenAsDataSource)(children, disabled, { itemTag: 'isMenuItem', subGroupTag: 'isMenuSubMenu', itemKeyName: 'itemKey', subGroupKeyName: 'subMenuKey' }), [children, dataSource, disabled, virtualList] ); const [collapseContext] = useCollapse(collapseProps || {}); const [groupContext, selectedStatus, toggleAllItems] = useGroup( selectedKeys, onChange, multiple, validKeys, disabledKeys, subGroupMap ); const selectAllCheckbox = useMemo( () => selectable && multiple && showSelectAll && ( <div className={classnames(selectallWrapCls, disabled && disabledCls)} key="menu-select-all"> <Checkbox className={checkboxCls} checked={selectedStatus === 'ALL'} indeterminate={selectedStatus === 'PART'} onChange={toggleAllItems} size="lg" disabled={disabled} > {locale.selectAll} </Checkbox> </div> ), [disabled, locale.selectAll, multiple, selectable, selectedStatus, showSelectAll, toggleAllItems] ); const renderList = useMemo(() => { if (virtualList) { const virtualRenderChildren: ReactNode[] = (selectAllCheckbox ? [selectAllCheckbox as ReactNode] : [] ).concat(renderChildren as ReactNode[]); const virtualInfo = typeof virtualList === 'object' ? virtualList : { simple: false, height: 200 }; return virtualInfo.simple ? ( <SimpleVirtualScrollList height={virtualInfo.height ?? 200} width="100%"> {virtualRenderChildren} </SimpleVirtualScrollList> ) : ( <VirtualScrollList height={virtualInfo.height ?? 200} width="100%"> {virtualRenderChildren} </VirtualScrollList> ); } else { return ( <div> {selectAllCheckbox} {renderChildren} </div> ); } }, [renderChildren, selectAllCheckbox, virtualList]); return ( <CollapseContext.Provider value={collapseContext}> <MenuContext.Provider value={{ ...groupContext, locale }}> <MenuWrap className={classnames(className, prefixCls, multiple ? multipleCls : singleCls, block && blockCls)} {...rest} > {renderList} </MenuWrap> </MenuContext.Provider> </CollapseContext.Provider> ); }; const VirtualScrollList = ({ children, height, width }: { children: ReactNode[]; height: number; width?: number | string; }) => { const scrollerRef = useRef(null); const heightWrapperRef = useRef(null); const wrapperRef = useRef(null); const [renderChildren, offsetTop] = useVirtualList(scrollerRef, wrapperRef, heightWrapperRef, children, { clientHeight: height }); return ( <div ref={scrollerRef} style={{ maxHeight: height, width, overflowY: 'auto' }}> <div ref={heightWrapperRef}> <div ref={wrapperRef} style={{ transform: `translate(0, ${offsetTop}px)` }}> {renderChildren} </div> </div> </div> ); }; const SimpleVirtualScrollList = ({ children, height, width }: { children: ReactNode[]; height: number; width?: number | string; }) => { const scrollerRef = useRef(null); const heightWrapperRef = useRef(null); const wrapperRef = useRef(null); const [renderChildren, offsetTop] = useSimpleVirtualList(scrollerRef, wrapperRef, heightWrapperRef, children, { clientHeight: height }); return ( <div ref={scrollerRef} style={{ maxHeight: height, width, overflowY: 'auto' }}> <div ref={heightWrapperRef}> <div ref={wrapperRef} style={{ transform: `translate(0, ${offsetTop}px)` }}> {renderChildren} </div> </div> </div> ); }; export default React.memo(Menu);
the_stack
import React from 'react'; import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import TreeView, { ITreeNodeItemProps } from '../index'; import { dragToTargetNode, expectFnCalled, sleep } from '@test/utils'; import { act } from 'react-test-renderer'; import { unexpandTreeNodeClassName, expandTreeNodeClassName } from '../base'; const mockData: ITreeNodeItemProps[] = [ { id: '1', name: 'test1', children: [ { id: '1-1', name: 'test1-1', icon: 'test', isLeaf: true, }, ], }, { id: '2', name: 'test2', }, ]; // mock Scrollable component jest.mock('lodash', () => { const originalModule = jest.requireActual('lodash'); return { ...originalModule, debounce: (fn) => fn, }; }); describe('Test the Tree component', () => { afterEach(cleanup); test('Should render name', async () => { const { getByTitle, findByTitle } = render( <TreeView data={mockData} /> ); expect(getByTitle('test1')).toBeInTheDocument(); expect(getByTitle('test2')).toBeInTheDocument(); fireEvent.click(getByTitle('test1')); expect(await findByTitle('test1-1')).toBeInTheDocument(); }); test('Should render custom title', async () => { const { container, getByTitle } = render( <TreeView renderTitle={(node) => { if (node.id === '1') { return "I'm renderTitle"; } return node.name!; }} data={mockData} /> ); const testDom = await waitFor(() => container.querySelector('[title="test1"]') ); const dom = await waitFor(() => container.querySelector('[title="I\'m renderTitle"]') ); expect(testDom).not.toBeInTheDocument(); expect(dom).toBeInTheDocument(); expect(getByTitle('test2')).toBeInTheDocument(); }); test('Should have correct levels', async () => { const { container, getByTitle } = render(<TreeView data={mockData} />); const parentNode = container.querySelector<HTMLDivElement>( 'div[data-id="mo_treeNode_1"]' ); fireEvent.click(getByTitle('test1')); const childNode = await waitFor(() => container.querySelector<HTMLDivElement>( 'div[data-id="mo_treeNode_1_1-1"]' ) ); expect(parentNode?.dataset.indent).toBe('0'); expect(childNode?.dataset.indent).toBe('1'); }); test('Should render customer icon only in leaf node & render specific icon in non-leaf node', async () => { const { container, getByTitle } = render(<TreeView data={mockData} />); fireEvent.click(getByTitle('test1')); const parentIcon = container .querySelector<HTMLDivElement>('div[data-id="mo_treeNode_1"]') ?.querySelector('span.codicon-chevron-down'); const childNode = await waitFor(() => container.querySelector<HTMLDivElement>( 'div[data-id="mo_treeNode_1_1-1"]' ) ); const childIcon = childNode?.querySelector('span.codicon-test') || null; expect(parentIcon).toBeInTheDocument(); expect(childIcon).not.toBeNull(); }); test('Should support to render React.ReactNode icon in leaf node', async () => { mockData[0].children![0].icon = <span role="icon"></span>; const { container, getByTitle } = render(<TreeView data={mockData} />); fireEvent.click(getByTitle('test1')); const childNode = await waitFor(() => container.querySelector<HTMLDivElement>( 'div[data-id="mo_treeNode_1_1-1"]' ) ); const childIcon = childNode?.querySelector('span[role="icon"]'); expect(childIcon).toBeInTheDocument(); }); test('Should calculate key by id', async () => { const data = [ { id: '1', name: 'test1', children: [ { id: '2', name: 'test2', }, ], }, ]; const { container, getByTitle } = render(<TreeView data={data} />); fireEvent.click(getByTitle('test1')); const parentNode = container.querySelector<HTMLDivElement>( 'div[data-id="mo_treeNode_1"]' ); const childNode = await waitFor(() => container.querySelector<HTMLDivElement>( 'div[data-id="mo_treeNode_1_2"]' ) ); expect(parentNode).toBeInTheDocument(); expect(childNode).toBeInTheDocument(); }); test('Should trigger events', async () => { const mockFn = jest.fn(); const mockRightClickFn = jest.fn(); const { getByTitle } = render( <TreeView data={mockData} onSelect={mockFn} onRightClick={mockRightClickFn} /> ); await waitFor(() => { fireEvent.click(getByTitle('test2')); fireEvent.contextMenu(getByTitle('test2')); }); expect(mockFn).toBeCalled(); expect(mockRightClickFn).toBeCalled(); }); test('Should fold when click expand node', async () => { const { getByTitle, findByTitle } = render( <TreeView data={mockData} /> ); fireEvent.click(getByTitle('test1')); expect((await findByTitle('test1')).className).toContain('open'); fireEvent.click(getByTitle('test1')); expect((await findByTitle('test1')).className).toContain('close'); }); test('Should expand the parent of editable node', async () => { const data = [ { id: '1', name: 'test1', children: [ { id: '2', name: 'test2', isEditable: true, }, ], }, ]; const { findByTitle } = render(<TreeView data={data} />); expect(await findByTitle('test2')).toBeInTheDocument(); }); test('Should support to drag into children', async () => { const data = [ { id: '1', name: 'test1', children: [ { id: '2', name: 'test2', isEditable: true, }, ], }, ]; const { findByTitle } = render(<TreeView data={data} />); expect(await findByTitle('test2')).toBeInTheDocument(); }); test('Should NOT support to sort via drag', async () => { const data = [ { id: '1', name: 'test1', isLeaf: true }, { id: '2', name: 'test2', isLeaf: true }, { id: '3', name: 'test3', isLeaf: true }, ]; const mockFn = jest.fn(); const { findByTitle } = render( <TreeView draggable onDropTree={mockFn} data={data} /> ); dragToTargetNode( await findByTitle('test3'), await findByTitle('test1') ); expect(mockFn).not.toBeCalled(); }); test('Should NOT darg to the its parent node', async () => { const data = [ { id: '1', name: 'test1', isLeaf: false, children: [{ id: '1-1', name: 'test1-1', isLeaf: true }], }, ]; const mockFn = jest.fn(); const { findByTitle, getByTitle } = render( <TreeView draggable onDropTree={mockFn} data={data} /> ); fireEvent.click(getByTitle('test1')); dragToTargetNode( await findByTitle('test1-1'), await findByTitle('test1') ); expect(mockFn).not.toBeCalled(); }); test('Should support to drag into children', async () => { const source = { id: '2', name: 'test2', isLeaf: true }; const target = { id: '1-1', name: 'test1-1', isLeaf: false }; const data = [ { id: '1', name: 'test1', isLeaf: false, children: [target], }, source, ]; const mockFn = jest.fn(); const { findByTitle, getByTitle } = render( <TreeView draggable onDropTree={mockFn} data={data} /> ); fireEvent.click(getByTitle('test1')); dragToTargetNode( await findByTitle(source.name), await findByTitle(target.name) ); expect(mockFn).toBeCalled(); expect(mockFn.mock.calls[0][0]).toEqual(source); expect(mockFn.mock.calls[0][1]).toEqual(target); }); test('Should support to drag to the folder rather than a file', async () => { const source = { id: '2-1', name: 'test2-1', isLeaf: true }; const target = { id: '1-1', name: 'test1-1', isLeaf: true }; const data = [ { id: '1', name: 'test1', isLeaf: false, children: [target], }, { id: '2', name: 'test2', isLeaf: false, children: [source], }, ]; const mockFn = jest.fn(); const { findByTitle, getByTitle } = render( <TreeView draggable onDropTree={mockFn} data={data} /> ); fireEvent.click(getByTitle('test1')); fireEvent.click(getByTitle('test2')); dragToTargetNode( await findByTitle(source.name), await findByTitle(target.name) ); expect(mockFn).toBeCalled(); expect(mockFn.mock.calls[0][0]).toEqual(source); expect(mockFn.mock.calls[0][1]).toEqual({ id: '1', name: 'test1', isLeaf: false, children: [target], }); }); test('Should NOT drag node to its parent node or drag node to its siblings or drag node to itself', async () => { const data = [ { id: '1', name: 'test1', children: [ { id: '1-1', isLeaf: true, name: 'test1-1' }, { id: '1-2', isLeaf: true, name: 'test1-2' }, ], }, { id: '2', name: 'test2', isLeaf: true, }, ]; const mockFn = jest.fn(); const { findByTitle } = render( <TreeView draggable onDropTree={mockFn} data={data} /> ); fireEvent.click(await findByTitle('test1')); dragToTargetNode( await findByTitle('test1-1'), await findByTitle('test1') ); expect(mockFn).not.toBeCalled(); dragToTargetNode( await findByTitle('test1-2'), await findByTitle('test1-1') ); expect(mockFn).not.toBeCalled(); dragToTargetNode( await findByTitle('test1'), await findByTitle('test1') ); expect(mockFn).not.toBeCalled(); }); test('Should end drop when drag node out of tree', async () => { const data = [ { id: '1', name: 'test1', children: [ { id: '1-1', isLeaf: true, name: 'test1-1' }, { id: '1-2', isLeaf: true, name: 'test1-2' }, ], }, ]; const mockFn = jest.fn(); const { findByTitle, container, getByTestId } = render( <TreeView draggable onDropTree={mockFn} data={data} /> ); // creat a dom insert into body as the drop node const outOfTree = document.createElement('div'); outOfTree.dataset.testid = 'outOfTree'; outOfTree.style.width = '100px'; outOfTree.style.height = '100px'; container.appendChild(outOfTree); // expand the parent node fireEvent.click(await findByTitle('test1')); fireEvent.dragStart(await findByTitle('test1')); fireEvent.dragOver(await findByTitle('test1')); expect(container.querySelectorAll('.drag-over').length).not.toBe(0); // drag node out of tree and drop it fireEvent.dragOver(getByTestId('outOfTree')); fireEvent.dragEnd(getByTestId('outOfTree')); expect(container.querySelectorAll('.drag-over').length).toBe(0); }); test('Should expand the drop node if this node is a folder', async () => { const data = [ { id: '1', name: 'test1', children: [{ id: '1-1', isLeaf: true, name: 'test1-1' }], }, { id: '2', isLeaf: true, name: 'test2' }, ]; const { getByText } = render(<TreeView draggable data={data} />); expect(getByText('test1').parentElement!.classList).toContain( unexpandTreeNodeClassName ); dragToTargetNode(getByText('test2'), getByText('test1')); expect(getByText('test1').parentElement!.classList).toContain( expandTreeNodeClassName ); // drag to itself won't expand dragToTargetNode(getByText('test1'), getByText('test1')); expect(getByText('test1').parentElement!.classList).toContain( unexpandTreeNodeClassName ); }); test('Should support to loadData in sync', async () => { const data = [ { id: '1', name: 'test1', isLeaf: false, children: [], }, ]; const mockFn = jest.fn().mockImplementation(() => sleep(1000)); const { getByText, container } = render( <TreeView data={data} onLoadData={mockFn} /> ); act(() => { fireEvent.click(getByText('test1')); }); expect(mockFn).toBeCalledTimes(1); expect(container.querySelector('.codicon-spin')).toBeInTheDocument(); await sleep(1000); expect(container.querySelector('.codicon-spin')).toBeNull(); act(() => { // unfold it and open it again fireEvent.click(getByText('test1')); fireEvent.click(getByText('test1')); }); // didn't trigger onLoadData this time expect(mockFn).toBeCalledTimes(1); }); test('Should support to be controlled', () => { const mockFn = jest.fn(); const { getByText, rerender } = render( <TreeView data={mockData} expandKeys={[]} onExpand={mockFn} /> ); expect(getByText('test1').parentElement?.classList).toContain( unexpandTreeNodeClassName ); fireEvent.click(getByText('test1')); expect(getByText('test1').parentElement?.classList).toContain( unexpandTreeNodeClassName ); expect(mockFn).toBeCalled(); rerender( <TreeView data={mockData} expandKeys={[mockData[0].id.toString()!]} onExpand={mockFn} /> ); expect(getByText('test1').parentElement?.classList).toContain( expandTreeNodeClassName ); }); test('Should support to trigger tree click event', () => { expectFnCalled((fn) => { const { getByRole } = render( <TreeView data={mockData} onTreeClick={fn} /> ); const wrapper = getByRole('tree'); fireEvent.click(wrapper); }); }); });
the_stack
import turfUnion from '@turf/union'; import turfDifference from '@turf/difference'; import turfIntersect from '@turf/intersect'; import { ImmutableFeatureCollection, FeatureCollection, Feature, Polygon, Geometry, Position, } from '@nebula.gl/edit-modes'; import { ClickEvent, PointerMoveEvent, StartDraggingEvent, StopDraggingEvent, DeckGLPick, } from '../event-types'; export type EditHandleType = 'existing' | 'intermediate' | 'snap'; export type EditHandle = { position: Position; positionIndexes: number[]; featureIndex: number; type: EditHandleType; }; export type EditAction = { updatedData: FeatureCollection; editType: string; featureIndexes: number[]; editContext: any; }; export class ModeHandler { // TODO: add underscore featureCollection: ImmutableFeatureCollection; _tentativeFeature: Feature | null | undefined; _modeConfig: any = null; _selectedFeatureIndexes: number[] = []; _clickSequence: Position[] = []; constructor(featureCollection?: FeatureCollection) { if (featureCollection) { this.setFeatureCollection(featureCollection); } } getFeatureCollection(): FeatureCollection { return this.featureCollection.getObject(); } getImmutableFeatureCollection(): ImmutableFeatureCollection { return this.featureCollection; } getSelectedFeature(): Feature | null | undefined { if (this._selectedFeatureIndexes.length === 1) { return this.featureCollection.getObject().features[this._selectedFeatureIndexes[0]]; } return null; } getSelectedGeometry(): Geometry | null | undefined { const feature = this.getSelectedFeature(); if (feature) { return feature.geometry; } return null; } getSelectedFeaturesAsFeatureCollection(): FeatureCollection { const { features } = this.featureCollection.getObject(); const selectedFeatures = this.getSelectedFeatureIndexes().map( (selectedIndex) => features[selectedIndex] ); return { type: 'FeatureCollection', features: selectedFeatures, }; } setFeatureCollection(featureCollection: FeatureCollection): void { this.featureCollection = new ImmutableFeatureCollection(featureCollection); } getModeConfig(): any { return this._modeConfig; } setModeConfig(modeConfig: any): void { if (this._modeConfig === modeConfig) { return; } this._modeConfig = modeConfig; this._setTentativeFeature(null); } getSelectedFeatureIndexes(): number[] { return this._selectedFeatureIndexes; } setSelectedFeatureIndexes(indexes: number[]): void { if (this._selectedFeatureIndexes === indexes) { return; } this._selectedFeatureIndexes = indexes; this._setTentativeFeature(null); } getClickSequence(): Position[] { return this._clickSequence; } resetClickSequence(): void { this._clickSequence = []; } getTentativeFeature(): Feature | null | undefined { return this._tentativeFeature; } // TODO: remove the underscore _setTentativeFeature(tentativeFeature: Feature | null | undefined): void { this._tentativeFeature = tentativeFeature; if (!tentativeFeature) { // Reset the click sequence this._clickSequence = []; } } /** * Returns a flat array of positions for the given feature along with their indexes into the feature's geometry's coordinates. * * @param featureIndex The index of the feature to get edit handles */ getEditHandles(picks?: Array<Record<string, any>>, groundCoords?: Position): EditHandle[] { return []; } getCursor({ isDragging }: { isDragging: boolean }): string { return 'cell'; } isSelectionPicked(picks: DeckGLPick[]): boolean { if (!picks.length) return false; const pickedIndexes = picks.map(({ index }) => index); const selectedFeatureIndexes = this.getSelectedFeatureIndexes(); return selectedFeatureIndexes.some((index) => pickedIndexes.includes(index)); } getAddFeatureAction(geometry: Geometry): EditAction { // Unsure why flow can't deal with Geometry type, but there I fixed it const geometryAsAny: any = geometry; const updatedData = this.getImmutableFeatureCollection() .addFeature({ type: 'Feature', properties: {}, geometry: geometryAsAny, }) .getObject(); return { updatedData, editType: 'addFeature', featureIndexes: [updatedData.features.length - 1], editContext: { featureIndexes: [updatedData.features.length - 1], }, }; } getAddManyFeaturesAction(featureCollection: FeatureCollection): EditAction { const features = featureCollection.features; let updatedData = this.getImmutableFeatureCollection(); const initialIndex = updatedData.getObject().features.length; const updatedIndexes = []; for (const feature of features) { const { properties, geometry } = feature; const geometryAsAny: any = geometry; updatedData = updatedData.addFeature({ type: 'Feature', properties, geometry: geometryAsAny, }); updatedIndexes.push(initialIndex + updatedIndexes.length); } return { updatedData: updatedData.getObject(), editType: 'addFeature', featureIndexes: updatedIndexes, editContext: { featureIndexes: updatedIndexes, }, }; } getAddFeatureOrBooleanPolygonAction(geometry: Polygon): EditAction | null | undefined { const selectedFeature = this.getSelectedFeature(); const modeConfig = this.getModeConfig(); if (modeConfig && modeConfig.booleanOperation) { if ( !selectedFeature || (selectedFeature.geometry.type !== 'Polygon' && selectedFeature.geometry.type !== 'MultiPolygon') ) { // eslint-disable-next-line no-console,no-undef console.warn( 'booleanOperation only supported for single Polygon or MultiPolygon selection' ); return null; } const feature = { type: 'Feature', geometry, }; let updatedGeometry; if (modeConfig.booleanOperation === 'union') { updatedGeometry = turfUnion(selectedFeature, feature); } else if (modeConfig.booleanOperation === 'difference') { // @ts-ignore updatedGeometry = turfDifference(selectedFeature, feature); } else if (modeConfig.booleanOperation === 'intersection') { // @ts-ignore updatedGeometry = turfIntersect(selectedFeature, feature); } else { // eslint-disable-next-line no-console,no-undef console.warn(`Invalid booleanOperation ${modeConfig.booleanOperation}`); return null; } if (!updatedGeometry) { // eslint-disable-next-line no-console,no-undef console.warn('Canceling edit. Boolean operation erased entire polygon.'); return null; } const featureIndex = this.getSelectedFeatureIndexes()[0]; const updatedData = this.getImmutableFeatureCollection() .replaceGeometry(featureIndex, updatedGeometry.geometry) .getObject(); const editAction: EditAction = { updatedData, editType: 'unionGeometry', featureIndexes: [featureIndex], editContext: { featureIndexes: [featureIndex], }, }; return editAction; } return this.getAddFeatureAction(geometry); } handleClick(event: ClickEvent): EditAction | null | undefined { this._clickSequence.push(event.groundCoords); return null; } handlePointerMove( event: PointerMoveEvent ): { editAction: EditAction | null | undefined; cancelMapPan: boolean } { return { editAction: null, cancelMapPan: false }; } handleStartDragging(event: StartDraggingEvent): EditAction | null | undefined { return null; } handleStopDragging(event: StopDraggingEvent): EditAction | null | undefined { return null; } } export function getPickedEditHandle( picks: any[] | null | undefined ): EditHandle | null | undefined { const info = picks && picks.find((pick) => pick.isEditingHandle); if (info) { return info.object; } return null; } export function getIntermediatePosition(position1: Position, position2: Position): Position { const intermediatePosition = [ (position1[0] + position2[0]) / 2.0, (position1[1] + position2[1]) / 2.0, ]; // @ts-ignore return intermediatePosition; } export function getEditHandlesForGeometry( geometry: Geometry, featureIndex: number, editHandleType: EditHandleType = 'existing' ) { let handles: EditHandle[] = []; switch (geometry.type) { case 'Point': // positions are not nested handles = [ { position: geometry.coordinates, positionIndexes: [], featureIndex, type: editHandleType, }, ]; break; case 'MultiPoint': case 'LineString': // positions are nested 1 level handles = handles.concat( getEditHandlesForCoordinates(geometry.coordinates, [], featureIndex, editHandleType) ); break; case 'Polygon': case 'MultiLineString': // positions are nested 2 levels for (let a = 0; a < geometry.coordinates.length; a++) { handles = handles.concat( getEditHandlesForCoordinates(geometry.coordinates[a], [a], featureIndex, editHandleType) ); if (geometry.type === 'Polygon') { // Don't repeat the first/last handle for Polygons handles = handles.slice(0, -1); } } break; case 'MultiPolygon': // positions are nested 3 levels for (let a = 0; a < geometry.coordinates.length; a++) { for (let b = 0; b < geometry.coordinates[a].length; b++) { handles = handles.concat( getEditHandlesForCoordinates( geometry.coordinates[a][b], [a, b], featureIndex, editHandleType ) ); // Don't repeat the first/last handle for Polygons handles = handles.slice(0, -1); } } break; default: // @ts-ignore throw Error(`Unhandled geometry type: ${geometry.type}`); } return handles; } function getEditHandlesForCoordinates( coordinates: any[], positionIndexPrefix: number[], featureIndex: number, editHandleType: EditHandleType = 'existing' ): EditHandle[] { const editHandles = []; for (let i = 0; i < coordinates.length; i++) { const position = coordinates[i]; editHandles.push({ position, positionIndexes: [...positionIndexPrefix, i], featureIndex, type: editHandleType, }); } return editHandles; }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/sapMonitorsMappers"; import * as Parameters from "../models/parameters"; import { HanaManagementClientContext } from "../hanaManagementClientContext"; /** Class representing a SapMonitors. */ export class SapMonitors { private readonly client: HanaManagementClientContext; /** * Create a SapMonitors. * @param {HanaManagementClientContext} client Reference to the service client. */ constructor(client: HanaManagementClientContext) { this.client = client; } /** * Gets a list of SAP monitors in the specified subscription. The operations returns various * properties of each SAP monitor. * @summary Gets a list of SAP monitors in the specified subscription. * @param [options] The optional parameters * @returns Promise<Models.SapMonitorsListResponse> */ list(options?: msRest.RequestOptionsBase): Promise<Models.SapMonitorsListResponse>; /** * @param callback The callback */ list(callback: msRest.ServiceCallback<Models.SapMonitorListResult>): void; /** * @param options The optional parameters * @param callback The callback */ list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SapMonitorListResult>): void; list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SapMonitorListResult>, callback?: msRest.ServiceCallback<Models.SapMonitorListResult>): Promise<Models.SapMonitorsListResponse> { return this.client.sendOperationRequest( { options }, listOperationSpec, callback) as Promise<Models.SapMonitorsListResponse>; } /** * Gets properties of a SAP monitor for the specified subscription, resource group, and resource * name. * @summary Gets properties of a SAP monitor. * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param [options] The optional parameters * @returns Promise<Models.SapMonitorsGetResponse> */ get(resourceGroupName: string, sapMonitorName: string, options?: msRest.RequestOptionsBase): Promise<Models.SapMonitorsGetResponse>; /** * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param callback The callback */ get(resourceGroupName: string, sapMonitorName: string, callback: msRest.ServiceCallback<Models.SapMonitor>): void; /** * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, sapMonitorName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SapMonitor>): void; get(resourceGroupName: string, sapMonitorName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SapMonitor>, callback?: msRest.ServiceCallback<Models.SapMonitor>): Promise<Models.SapMonitorsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, sapMonitorName, options }, getOperationSpec, callback) as Promise<Models.SapMonitorsGetResponse>; } /** * Creates a SAP monitor for the specified subscription, resource group, and resource name. * @summary Creates a SAP monitor. * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param sapMonitorParameter Request body representing a SAP Monitor * @param [options] The optional parameters * @returns Promise<Models.SapMonitorsCreateResponse> */ create(resourceGroupName: string, sapMonitorName: string, sapMonitorParameter: Models.SapMonitor, options?: msRest.RequestOptionsBase): Promise<Models.SapMonitorsCreateResponse> { return this.beginCreate(resourceGroupName,sapMonitorName,sapMonitorParameter,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.SapMonitorsCreateResponse>; } /** * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. * @summary Deletes a SAP monitor. * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, sapMonitorName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,sapMonitorName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and * monitor name. * @summary Patches the Tags field of a SAP monitor. * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param tagsParameter Request body that only contains the new Tags field * @param [options] The optional parameters * @returns Promise<Models.SapMonitorsUpdateResponse> */ update(resourceGroupName: string, sapMonitorName: string, tagsParameter: Models.Tags, options?: msRest.RequestOptionsBase): Promise<Models.SapMonitorsUpdateResponse>; /** * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param tagsParameter Request body that only contains the new Tags field * @param callback The callback */ update(resourceGroupName: string, sapMonitorName: string, tagsParameter: Models.Tags, callback: msRest.ServiceCallback<Models.SapMonitor>): void; /** * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param tagsParameter Request body that only contains the new Tags field * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, sapMonitorName: string, tagsParameter: Models.Tags, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SapMonitor>): void; update(resourceGroupName: string, sapMonitorName: string, tagsParameter: Models.Tags, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SapMonitor>, callback?: msRest.ServiceCallback<Models.SapMonitor>): Promise<Models.SapMonitorsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, sapMonitorName, tagsParameter, options }, updateOperationSpec, callback) as Promise<Models.SapMonitorsUpdateResponse>; } /** * Creates a SAP monitor for the specified subscription, resource group, and resource name. * @summary Creates a SAP monitor. * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param sapMonitorParameter Request body representing a SAP Monitor * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(resourceGroupName: string, sapMonitorName: string, sapMonitorParameter: Models.SapMonitor, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, sapMonitorName, sapMonitorParameter, options }, beginCreateOperationSpec, options); } /** * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. * @summary Deletes a SAP monitor. * @param resourceGroupName Name of the resource group. * @param sapMonitorName Name of the SAP monitor resource. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, sapMonitorName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, sapMonitorName, options }, beginDeleteMethodOperationSpec, options); } /** * Gets a list of SAP monitors in the specified subscription. The operations returns various * properties of each SAP monitor. * @summary Gets a list of SAP monitors in the specified subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.SapMonitorsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.SapMonitorsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SapMonitorListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SapMonitorListResult>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SapMonitorListResult>, callback?: msRest.ServiceCallback<Models.SapMonitorListResult>): Promise<Models.SapMonitorsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.SapMonitorsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.HanaOnAzure/sapMonitors", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SapMonitorListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.sapMonitorName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SapMonitor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.sapMonitorName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "tagsParameter", mapper: { ...Mappers.Tags, required: true } }, responses: { 200: { bodyMapper: Mappers.SapMonitor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.sapMonitorName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "sapMonitorParameter", mapper: { ...Mappers.SapMonitor, required: true } }, responses: { 200: { bodyMapper: Mappers.SapMonitor }, 201: { bodyMapper: Mappers.SapMonitor }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.sapMonitorName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SapMonitorListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import uuid from '../util/uuid' import { IPane, IPaneContent, PaneSplitAxis } from './types' import { panesNsCurrentPaneSelector, panesNsPaneSelector, panesNsContentSelector, } from './store' /** * Get a pane by its id and throw if it doesn't exist. */ export const mustGetPane = <Data>( panes: Array<IPane<Data>>, paneId: string ): IPane<Data> => { if (panes.length === 0) { throw new Error(`there's no available pane`) } const foundPane = panesNsPaneSelector(panes, paneId) if (foundPane === undefined) { throw new Error(`no pane found for id: ${paneId}, available panes: ${panes.map(({ id }) => id).join(', ')}`) } return foundPane } /** * Get a content by its id and throw if it doesn't exist. */ export const mustGetContent = <Data>( pane: IPane<Data>, contentId: string ): IPaneContent<Data> => { if (pane.contents.length === 0) { throw new Error(`pane ${pane.id} doesn't have any content`) } const foundContent = pane.contents.find(content => content.id === contentId) if (foundContent === undefined) { throw new Error(`no content found in pane: ${pane.id} for id: ${contentId}, available contents: ${pane.contents.map(({ id }) => id).join(', ')}`) } return foundContent } /** * Mark pane having provided `paneId` current pane, * if it's already the current one, return untouched panes. */ export const setCurrentPane = <Data>( panes: Array<IPane<Data>>, paneId: string ): Array<IPane<Data>> => { mustGetPane<Data>(panes, paneId) const currentPane = panesNsCurrentPaneSelector<Data>(panes) if (currentPane !== undefined && currentPane.id === paneId) { return panes } return panes.map(pane => { const isCurrent = pane.id === paneId if (pane.isCurrent === isCurrent) { return pane } return { ...pane, isCurrent } }) } /** * Append a content to current pane. * If the content already exists, doesn't re-append. * If the content is unique and already exists in the existing * panes, doesn't re-append, and set pane/content current, * meaning the content will remains unique across all panes * in the namespace. */ export const addContentToCurrentPane = <Data>( panes: Array<IPane<Data>>, newContent: IPaneContent<Data> ): Array<IPane<Data>> => { if (newContent.isUnique) { const existing = panesNsContentSelector(panes, newContent.id) if (existing !== undefined) { return setPaneCurrentContent(panes, existing.pane.id, existing.content.id) } } const currentPane = panesNsCurrentPaneSelector<Data>(panes) if (currentPane === undefined) { throw new Error('unable to find a current pane') } const existingContent = currentPane.contents.find( content => content.id === newContent.id ) // content already exists, make sure it's current if (existingContent !== undefined) { if (existingContent.isCurrent) return panes else { return panes.map(pane => { if (!pane.isCurrent) return pane return { ...pane, contents: pane.contents.map(content => { const isCurrent = content.id === newContent.id if (isCurrent === content.isCurrent) return content return { ...content, isCurrent } }) } }) } } return panes.map(pane => { if (!pane.isCurrent) return pane return { ...pane, contents: [ ...pane.contents.map(content => { if (!content.isCurrent) return content return { ...content, isCurrent: false } }), { ...newContent, isCurrent: true } ] } }) } /** * Mark pane having provided `paneId` current pane, * and also mark content matching provided `contentId` current content. * Does not touch panes/contents already in desired state. */ export const setPaneCurrentContent = <Data>( panes: Array<IPane<Data>>, paneId: string, contentId: string ): Array<IPane<Data>> => { const currentPane = panesNsCurrentPaneSelector<Data>(panes) if (currentPane !== undefined && currentPane.id === paneId) { const currentContent = currentPane.contents.find( content => content.isCurrent ) if ( currentContent !== undefined && currentContent.id === contentId ) { // panes are already in the desired state return panes } } const targetPane = mustGetPane<Data>(panes, paneId) mustGetContent<Data>(targetPane, contentId) return panes.map(pane => { if (pane.id === paneId) { return { ...pane, isCurrent: true, contents: pane.contents.map(content => { const isCurrent = content.id === contentId if (content.isCurrent === isCurrent) { return content } return { ...content, isCurrent } }) } } if (!pane.isCurrent) return pane return { ...pane, isCurrent: false } }) } /** * Remove content from pane, if there's no remaining content * and pane does have a parent (childOf is defined), * un-split it. */ export const removePaneContent = <Data>( panes: Array<IPane<Data>>, paneId: string, contentId: string ): Array<IPane<Data>> => { const targetPane = mustGetPane<Data>(panes, paneId) mustGetContent<Data>(targetPane, contentId) let paneUpdate: { oldId: string pane: IPane<Data> } return panes .reduce((acc: Array<IPane<Data>>, pane: IPane<Data>) => { if (pane.id !== paneId) { if (!pane.isCurrent) return [...acc, pane] else return [...acc, { ...pane, isCurrent: false }] } const filteredContents = pane.contents.filter( content => content.id !== contentId ) const contentCount = filteredContents.length if (pane.childOf === undefined || contentCount > 0) { let contents = filteredContents const hasCurrent = filteredContents.some(content => content.isCurrent) if (!hasCurrent) { contents = filteredContents.map((content, i) => { if (i === contentCount - 1) return { ...content, isCurrent: true } return content }) } return [ ...acc, { ...pane, isCurrent: true, contents, } ] } // there's no remaining content && pane isn't root pane // we un-split parent const parentPane = mustGetPane(panes, pane.childOf) const siblingPaneId = parentPane.children.find( childPaneId => childPaneId !== pane.id ) const siblingPane = mustGetPane(panes, siblingPaneId!) paneUpdate = { oldId: siblingPane.id, pane: { ...siblingPane, id: parentPane.id, childOf: parentPane.childOf, isCurrent: true, }, } return acc }, []) .filter((pane: IPane<Data>) => paneUpdate === undefined || pane.id !== paneUpdate.oldId ) .map((pane: IPane<Data>) => { if (paneUpdate === undefined) return pane if (pane.id === paneUpdate.pane.id) return paneUpdate.pane return { ...pane, childOf: pane.childOf === paneUpdate.oldId ? paneUpdate.pane.id : pane.childOf, children: pane.children.map(childId => childId === paneUpdate.oldId ? paneUpdate.pane.id : childId ), } }) } /** * Remove a content from all panes in the namespace. */ export const removeContentFromAllPanes = <Data>( panes: Array<IPane<Data>>, contentId: string ): Array<IPane<Data>> => { let updatedPanes = panes panes.forEach(pane => { if (pane.contents.some(content => content.id === contentId)) { updatedPanes = removePaneContent( panes, pane.id, contentId ) } }) return updatedPanes } /** * Split the pane whose id is `paneId` into two child panes, * also set it as current pane. * The new pane (second child) will be created with * pane current content. */ export const splitPane = <Data>( panes: Array<IPane<Data>>, paneId: string, axis: PaneSplitAxis ): Array<IPane<Data>> => { const targetPane = mustGetPane<Data>(panes, paneId) const currentContent = targetPane.contents.find( content => content.isCurrent ) if (currentContent === undefined) return panes return panes.reduce((acc: Array<IPane<Data>>, pane: IPane<Data>) => { if (pane.id !== paneId) { if (!pane.isCurrent) return [...acc, pane] else return [...acc, { ...pane, isCurrent: false }] } const firstChildPaneId = uuid() const secondChildPaneBId = uuid() return [ ...acc, { id: firstChildPaneId, contents: pane.contents, split: false, childOf: paneId, children: [], isCurrent: false, }, { id: secondChildPaneBId, contents: [currentContent], split: false, childOf: paneId, children: [], isCurrent: true, }, { ...pane, isCurrent: false, split: true, splitAxis: axis, contents: [], children: [ firstChildPaneId, secondChildPaneBId, ] }, ] }, []) }
the_stack
import { readFileSync } from 'fs'; const lines = readFileSync('/home/tochi/code/scratches/proto2_advanced.proto', { encoding: 'utf-8' }).split(/\r?\n/); testTokenization('protobuf', [ lines.map((line) => ({ line, tokens: [] })) ]); */ import { testTokenization } from '../test/testRunner'; testTokenization('proto', [ // proto3 example file: https://developers.google.com/protocol-buffers/docs/reference/proto3-spec#proto_file [ { line: 'syntax = "proto3";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'operators.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'string.quote.proto' }, { startIndex: 10, type: 'string.proto' }, { startIndex: 16, type: 'string.quote.proto' }, { startIndex: 17, type: 'delimiter.proto' } ] }, { line: 'import public "other.proto";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'keyword.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'string.quote.proto' }, { startIndex: 15, type: 'string.proto' }, { startIndex: 26, type: 'string.quote.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: 'option java_package = "com.example.foo";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'annotation.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'operator.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'string.quote.proto' }, { startIndex: 23, type: 'string.proto' }, { startIndex: 38, type: 'string.quote.proto' }, { startIndex: 39, type: 'delimiter.proto' } ] }, { line: 'enum EnumAllowingAlias {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 4, type: 'white.proto' }, { startIndex: 5, type: 'type.identifier.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'delimiter.curly.proto' } ] }, { line: ' option allow_alias = true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'operator.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'keyword.constant.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' UNKNOWN = 0;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.octal.proto' }, { startIndex: 13, type: 'delimiter.proto' } ] }, { line: ' STARTED = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'delimiter.proto' } ] }, { line: ' RUNNING = 2 [(custom_option) = "hello world"];', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.square.proto' }, { startIndex: 15, type: 'annotation.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'operator.proto' }, { startIndex: 32, type: 'white.proto' }, { startIndex: 33, type: 'string.quote.proto' }, { startIndex: 34, type: 'string.proto' }, { startIndex: 45, type: 'string.quote.proto' }, { startIndex: 46, type: 'delimiter.square.proto' }, { startIndex: 47, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: 'message Outer {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.curly.proto' } ] }, { line: ' option (my_option).a = true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'operator.proto' }, { startIndex: 24, type: 'white.proto' }, { startIndex: 25, type: 'keyword.constant.proto' }, { startIndex: 29, type: 'delimiter.proto' } ] }, { line: ' message Inner { // Level 2', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 20, type: 'comment.proto' } ] }, { line: ' int64 ival = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'identifier.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'delimiter.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'number.proto' }, { startIndex: 18, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: ' repeated Inner inner_message = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'delimiter.proto' }, { startIndex: 32, type: 'white.proto' }, { startIndex: 33, type: 'number.proto' }, { startIndex: 34, type: 'delimiter.proto' } ] }, { line: ' EnumAllowingAlias enum_field =3;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'type.identifier.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'identifier.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'delimiter.proto' }, { startIndex: 32, type: 'number.proto' }, { startIndex: 33, type: 'delimiter.proto' } ] }, { line: ' map<int32, string> my_map = 4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 5, type: 'delimiter.angle.proto' }, { startIndex: 6, type: 'keyword.proto' }, { startIndex: 11, type: 'delimiter.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 19, type: 'delimiter.angle.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'identifier.proto' }, { startIndex: 27, type: 'white.proto' }, { startIndex: 28, type: 'operators.proto' }, { startIndex: 29, type: 'white.proto' }, { startIndex: 30, type: 'number.proto' }, { startIndex: 31, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] } ], // proto2 example file: https://developers.google.com/protocol-buffers/docs/reference/proto2-spec#proto_file [ { line: 'syntax = "proto2";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'operators.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'string.quote.proto' }, { startIndex: 10, type: 'string.proto' }, { startIndex: 16, type: 'string.quote.proto' }, { startIndex: 17, type: 'delimiter.proto' } ] }, { line: 'import public "other.proto";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'keyword.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'string.quote.proto' }, { startIndex: 15, type: 'string.proto' }, { startIndex: 26, type: 'string.quote.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: 'option java_package = "com.example.foo";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'annotation.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'operator.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'string.quote.proto' }, { startIndex: 23, type: 'string.proto' }, { startIndex: 38, type: 'string.quote.proto' }, { startIndex: 39, type: 'delimiter.proto' } ] }, { line: 'enum EnumAllowingAlias {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 4, type: 'white.proto' }, { startIndex: 5, type: 'type.identifier.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'delimiter.curly.proto' } ] }, { line: ' option allow_alias = true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'operator.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'keyword.constant.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' UNKNOWN = 0;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.octal.proto' }, { startIndex: 13, type: 'delimiter.proto' } ] }, { line: ' STARTED = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'delimiter.proto' } ] }, { line: ' RUNNING = 2 [(custom_option) = "hello world"];', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.square.proto' }, { startIndex: 15, type: 'annotation.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'operator.proto' }, { startIndex: 32, type: 'white.proto' }, { startIndex: 33, type: 'string.quote.proto' }, { startIndex: 34, type: 'string.proto' }, { startIndex: 45, type: 'string.quote.proto' }, { startIndex: 46, type: 'delimiter.square.proto' }, { startIndex: 47, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: 'message Outer {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.curly.proto' } ] }, { line: ' option (my_option).a = true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'operator.proto' }, { startIndex: 24, type: 'white.proto' }, { startIndex: 25, type: 'keyword.constant.proto' }, { startIndex: 29, type: 'delimiter.proto' } ] }, { line: ' message Inner { // Level 2', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 20, type: 'comment.proto' } ] }, { line: ' required int64 ival = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'identifier.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'delimiter.proto' }, { startIndex: 25, type: 'white.proto' }, { startIndex: 26, type: 'number.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: ' repeated Inner inner_message = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'delimiter.proto' }, { startIndex: 32, type: 'white.proto' }, { startIndex: 33, type: 'number.proto' }, { startIndex: 34, type: 'delimiter.proto' } ] }, { line: ' optional EnumAllowingAlias enum_field = 3;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'identifier.proto' }, { startIndex: 39, type: 'white.proto' }, { startIndex: 40, type: 'delimiter.proto' }, { startIndex: 41, type: 'white.proto' }, { startIndex: 42, type: 'number.proto' }, { startIndex: 43, type: 'delimiter.proto' } ] }, { line: ' map<int32, string> my_map = 4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 5, type: 'delimiter.angle.proto' }, { startIndex: 6, type: 'keyword.proto' }, { startIndex: 11, type: 'delimiter.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 19, type: 'delimiter.angle.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'identifier.proto' }, { startIndex: 27, type: 'white.proto' }, { startIndex: 28, type: 'operators.proto' }, { startIndex: 29, type: 'white.proto' }, { startIndex: 30, type: 'number.proto' }, { startIndex: 31, type: 'delimiter.proto' } ] }, { line: ' extensions 20 to 30;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'number.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'keyword.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'number.proto' }, { startIndex: 21, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: 'message Foo {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.curly.proto' } ] }, { line: ' optional group GroupMessage {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 29, type: 'white.proto' }, { startIndex: 30, type: 'delimiter.curly.proto' } ] }, { line: ' optional a = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'identifier.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'delimiter.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'number.proto' }, { startIndex: 18, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] } ], // proto3 edge cases [ { line: 'syntax = "proto3";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'operators.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'string.quote.proto' }, { startIndex: 10, type: 'string.proto' }, { startIndex: 16, type: 'string.quote.proto' }, { startIndex: 17, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'package foo . /**/ bar;', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'comment.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 20, type: 'identifier.proto' }, { startIndex: 23, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'import public "options.proto";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'keyword.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'string.quote.proto' }, { startIndex: 15, type: 'string.proto' }, { startIndex: 28, type: 'string.quote.proto' }, { startIndex: 29, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'option java_package = "com.example.foo";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'annotation.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'operator.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'string.quote.proto' }, { startIndex: 23, type: 'string.proto' }, { startIndex: 38, type: 'string.quote.proto' }, { startIndex: 39, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'message Foo {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.curly.proto' } ] }, { line: ' foo.bar.Bar nested_message = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'type.identifier.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'identifier.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'delimiter.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'number.proto' }, { startIndex: 32, type: 'delimiter.proto' } ] }, { line: ' repeated int32 samples = 3 [packed=true];', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 24, type: 'white.proto' }, { startIndex: 25, type: 'delimiter.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'number.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'delimiter.square.proto' }, { startIndex: 30, type: 'annotation.proto' }, { startIndex: 36, type: 'operator.proto' }, { startIndex: 37, type: 'keyword.constant.proto' }, { startIndex: 41, type: 'delimiter.square.proto' }, { startIndex: 42, type: 'delimiter.proto' } ] }, { line: ' oneof foo {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.curly.proto' } ] }, { line: ' string name = 4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'number.proto' }, { startIndex: 19, type: 'delimiter.proto' } ] }, { line: ' Bar sub_message = 92;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'type.identifier.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'delimiter.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'number.proto' }, { startIndex: 24, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: ' reserved 5, 15, 203 to 30;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'number.proto' }, { startIndex: 12, type: 'delimiter.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'number.proto' }, { startIndex: 16, type: 'delimiter.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'number.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'keyword.proto' }, { startIndex: 24, type: 'white.proto' }, { startIndex: 25, type: 'number.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' reserved "$46_ _$%$%\\"bar" "baz";', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'string.quote.proto' }, { startIndex: 12, type: 'string.proto' }, { startIndex: 22, type: 'string.escape.invalid.proto' }, { startIndex: 24, type: 'string.proto' }, { startIndex: 27, type: 'string.quote.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'string.quote.proto' }, { startIndex: 30, type: 'string.proto' }, { startIndex: 33, type: 'string.quote.proto' }, { startIndex: 34, type: 'delimiter.proto' } ] }, { line: ' reserved 100 to max ;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'number.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'keyword.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'keyword.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.proto' } ] }, { line: ' string baz = 10;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'identifier.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'delimiter.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'number.proto' }, { startIndex: 17, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message', tokens: [{ startIndex: 0, type: 'keyword.proto' }] }, { line: 'map {}', tokens: [ { startIndex: 0, type: 'type.identifier.proto' }, { startIndex: 3, type: 'white.proto' }, { startIndex: 4, type: 'delimiter.curly.proto' } ] }, { line: '', tokens: [] }, { line: 'message Bar {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.curly.proto' } ] }, { line: ' int32 x = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'delimiter.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message int32 {}', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.curly.proto' } ] }, { line: '', tokens: [] }, { line: 'enum EnumAllowingAlias {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 4, type: 'white.proto' }, { startIndex: 5, type: 'type.identifier.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'delimiter.curly.proto' } ] }, { line: ' option allow_alias = true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'operator.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'keyword.constant.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' uNkNoWN2 = 0;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'operators.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'number.octal.proto' }, { startIndex: 14, type: 'delimiter.proto' } ] }, { line: ' ENUM_ALLOWING_ALIAS_UNKNOWN = 0;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 29, type: 'white.proto' }, { startIndex: 30, type: 'operators.proto' }, { startIndex: 31, type: 'white.proto' }, { startIndex: 32, type: 'number.octal.proto' }, { startIndex: 33, type: 'delimiter.proto' } ] }, { line: ' STARTED = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'delimiter.proto' } ] }, { line: " running = 2 [( /***/ custom_option) = 'hello world'];", tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.square.proto' }, { startIndex: 15, type: 'annotation.brackets.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'comment.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'annotation.proto' }, { startIndex: 36, type: 'annotation.brackets.proto' }, { startIndex: 37, type: 'white.proto' }, { startIndex: 38, type: 'operator.proto' }, { startIndex: 39, type: 'white.proto' }, { startIndex: 40, type: 'string.quote.proto' }, { startIndex: 41, type: 'string.proto' }, { startIndex: 52, type: 'string.quote.proto' }, { startIndex: 53, type: 'delimiter.square.proto' }, { startIndex: 54, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message Outer {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.curly.proto' } ] }, { line: ' option (my_option).a= true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 22, type: 'operator.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'keyword.constant.proto' }, { startIndex: 28, type: 'delimiter.proto' } ] }, { line: ' message Inner { // Level 2', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 20, type: 'comment.proto' } ] }, { line: ' int64 ival = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'identifier.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'delimiter.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'number.proto' }, { startIndex: 18, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: ' repeated Inner inner_message = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'delimiter.proto' }, { startIndex: 32, type: 'white.proto' }, { startIndex: 33, type: 'number.proto' }, { startIndex: 34, type: 'delimiter.proto' } ] }, { line: ' foo .bar', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'type.identifier.proto' } ] }, { line: ' /**/ .EnumAllowingAlias enum_field =3;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 3, type: 'comment.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'identifier.proto' }, { startIndex: 37, type: 'white.proto' }, { startIndex: 38, type: 'delimiter.proto' }, { startIndex: 39, type: 'number.proto' }, { startIndex: 40, type: 'delimiter.proto' } ] }, { line: ' map my_map = 4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'type.identifier.proto' }, { startIndex: 5, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'delimiter.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'number.proto' }, { startIndex: 16, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message message {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' } ] }, { line: ' repeated Foo enum = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'identifier.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'delimiter.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'number.proto' }, { startIndex: 23, type: 'delimiter.proto' } ] }, { line: ' Foo int32 = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'type.identifier.proto' }, { startIndex: 5, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'number.proto' }, { startIndex: 15, type: 'delimiter.proto' } ] }, { line: ' service x = 3;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'type.identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'number.proto' }, { startIndex: 15, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message service {}', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' } ] }, { line: '', tokens: [] }, { line: '/** SearchService does nothing and returns the string "foo"', tokens: [{ startIndex: 0, type: 'comment.proto' }] }, { line: '*/', tokens: [{ startIndex: 0, type: 'comment.proto' }] }, { line: 'service SearchService {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.curly.proto' } ] }, { line: ' rpc Search (stream SearchRequest) returns (SearchResponse) {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 5, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'delimiter.parenthesis.proto' }, { startIndex: 14, type: 'keyword.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'type.identifier.proto' }, { startIndex: 34, type: 'delimiter.parenthesis.proto' }, { startIndex: 35, type: 'white.proto' }, { startIndex: 36, type: 'keyword.proto' }, { startIndex: 43, type: 'white.proto' }, { startIndex: 44, type: 'delimiter.parenthesis.proto' }, { startIndex: 45, type: 'type.identifier.proto' }, { startIndex: 59, type: 'delimiter.parenthesis.proto' }, { startIndex: 60, type: 'white.proto' }, { startIndex: 61, type: 'delimiter.curly.proto' } ] }, { line: ' option (method_option) = {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'annotation.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'operator.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'delimiter.curly.proto' } ] }, { line: ' method_id: 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 15, type: 'delimiter.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'number.proto' }, { startIndex: 18, type: 'delimiter.proto' } ] }, { line: ' method_name: "hello";', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 17, type: 'delimiter.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'string.quote.proto' }, { startIndex: 20, type: 'string.proto' }, { startIndex: 25, type: 'string.quote.proto' }, { startIndex: 26, type: 'delimiter.proto' } ] }, { line: ' method_sla: 9.807E+4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 16, type: 'delimiter.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'number.proto' }, { startIndex: 19, type: 'number.float.proto' }, { startIndex: 26, type: 'delimiter.proto' } ] }, { line: ' };', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'delimiter.curly.proto' }, { startIndex: 5, type: 'delimiter.proto' } ] }, { line: ' };', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' }, { startIndex: 3, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message SearchRequest {};', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.curly.proto' }, { startIndex: 24, type: 'delimiter.proto' } ] }, { line: 'message SearchResponse {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'delimiter.curly.proto' } ] }, { line: ' string response = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'identifier.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'delimiter.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'number.proto' }, { startIndex: 21, type: 'delimiter.proto' } ] }, { line: '};', tokens: [ { startIndex: 0, type: 'delimiter.curly.proto' }, { startIndex: 1, type: 'delimiter.proto' } ] } ], // proto2 edge cases [ { line: 'syntax = "proto2";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'operators.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'string.quote.proto' }, { startIndex: 10, type: 'string.proto' }, { startIndex: 16, type: 'string.quote.proto' }, { startIndex: 17, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'package foo . /**/ bar;', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'comment.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 20, type: 'identifier.proto' }, { startIndex: 23, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'import public "options.proto";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'keyword.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'string.quote.proto' }, { startIndex: 15, type: 'string.proto' }, { startIndex: 28, type: 'string.quote.proto' }, { startIndex: 29, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'option java_package = "com.example.foo";', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'annotation.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'operator.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'string.quote.proto' }, { startIndex: 23, type: 'string.proto' }, { startIndex: 38, type: 'string.quote.proto' }, { startIndex: 39, type: 'delimiter.proto' } ] }, { line: '', tokens: [] }, { line: 'message Foo {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.curly.proto' } ] }, { line: ' required foo.bar.Bar nested_message = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'identifier.proto' }, { startIndex: 37, type: 'white.proto' }, { startIndex: 38, type: 'delimiter.proto' }, { startIndex: 39, type: 'white.proto' }, { startIndex: 40, type: 'number.proto' }, { startIndex: 41, type: 'delimiter.proto' } ] }, { line: ' repeated int32 samples = 3 [packed=true];', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 24, type: 'white.proto' }, { startIndex: 25, type: 'delimiter.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'number.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'delimiter.square.proto' }, { startIndex: 30, type: 'annotation.proto' }, { startIndex: 36, type: 'operator.proto' }, { startIndex: 37, type: 'keyword.constant.proto' }, { startIndex: 41, type: 'delimiter.square.proto' }, { startIndex: 42, type: 'delimiter.proto' } ] }, { line: ' oneof foo {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.curly.proto' } ] }, { line: ' string name = 4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'number.proto' }, { startIndex: 19, type: 'delimiter.proto' } ] }, { line: ' Bar sub_message = 6;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'type.identifier.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'delimiter.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'number.proto' }, { startIndex: 23, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: ' reserved 5, 15, 20 to 30;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'number.proto' }, { startIndex: 12, type: 'delimiter.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'number.proto' }, { startIndex: 16, type: 'delimiter.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'number.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'keyword.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'number.proto' }, { startIndex: 26, type: 'delimiter.proto' } ] }, { line: ' reserved \'bar\' "baz";', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'string.quote.proto' }, { startIndex: 12, type: 'string.proto' }, { startIndex: 15, type: 'string.quote.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'string.quote.proto' }, { startIndex: 18, type: 'string.proto' }, { startIndex: 21, type: 'string.quote.proto' }, { startIndex: 22, type: 'delimiter.proto' } ] }, { line: ' extensions 50 to 99;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'number.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'keyword.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'number.proto' }, { startIndex: 21, type: 'delimiter.proto' } ] }, { line: ' reserved 100 to max ;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'number.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'keyword.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'keyword.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.proto' } ] }, { line: ' optional string baz = 10;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'identifier.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'number.proto' }, { startIndex: 26, type: 'delimiter.proto' } ] }, { line: ' repeated group Result = 1 {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'operator.proto' }, { startIndex: 25, type: 'white.proto' }, { startIndex: 26, type: 'number.proto' }, { startIndex: 27, type: 'white.proto' }, { startIndex: 28, type: 'delimiter.curly.proto' } ] }, { line: ' required string url = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'identifier.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'delimiter.proto' }, { startIndex: 25, type: 'white.proto' }, { startIndex: 26, type: 'number.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' optional string title = 3;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'identifier.proto' }, { startIndex: 25, type: 'white.proto' }, { startIndex: 26, type: 'delimiter.proto' }, { startIndex: 27, type: 'white.proto' }, { startIndex: 28, type: 'number.proto' }, { startIndex: 29, type: 'delimiter.proto' } ] }, { line: ' repeated string snippets = 4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'identifier.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'delimiter.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'number.proto' }, { startIndex: 32, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'extend Foo {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 6, type: 'white.proto' }, { startIndex: 7, type: 'type.identifier.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'delimiter.curly.proto' } ] }, { line: ' optional int32 bar = 50;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'delimiter.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'number.proto' }, { startIndex: 25, type: 'delimiter.proto' } ] }, { line: ' repeated group More = 51 {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'operator.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'number.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'delimiter.curly.proto' } ] }, { line: ' required string url = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'identifier.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'delimiter.proto' }, { startIndex: 25, type: 'white.proto' }, { startIndex: 26, type: 'number.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message', tokens: [{ startIndex: 0, type: 'keyword.proto' }] }, { line: 'map {}', tokens: [ { startIndex: 0, type: 'type.identifier.proto' }, { startIndex: 3, type: 'white.proto' }, { startIndex: 4, type: 'delimiter.curly.proto' } ] }, { line: '', tokens: [] }, { line: 'message Bar {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'delimiter.curly.proto' } ] }, { line: ' optional int32 x = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'delimiter.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'number.proto' }, { startIndex: 22, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message int32 {}', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.curly.proto' } ] }, { line: '', tokens: [] }, { line: 'enum EnumAllowingAlias {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 4, type: 'white.proto' }, { startIndex: 5, type: 'type.identifier.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'delimiter.curly.proto' } ] }, { line: ' option allow_alias = true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'operator.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'keyword.constant.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' uNkNoWN2 = 0;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'operators.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'number.octal.proto' }, { startIndex: 14, type: 'delimiter.proto' } ] }, { line: ' ENUM_ALLOWING_ALIAS_UNKNOWN = 0;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 29, type: 'white.proto' }, { startIndex: 30, type: 'operators.proto' }, { startIndex: 31, type: 'white.proto' }, { startIndex: 32, type: 'number.octal.proto' }, { startIndex: 33, type: 'delimiter.proto' } ] }, { line: ' STARTED = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'delimiter.proto' } ] }, { line: " running = 2 [( /***/ custom_option) = 'hello world'];", tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'identifier.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'operators.proto' }, { startIndex: 11, type: 'white.proto' }, { startIndex: 12, type: 'number.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.square.proto' }, { startIndex: 15, type: 'annotation.brackets.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'comment.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'annotation.proto' }, { startIndex: 36, type: 'annotation.brackets.proto' }, { startIndex: 37, type: 'white.proto' }, { startIndex: 38, type: 'operator.proto' }, { startIndex: 39, type: 'white.proto' }, { startIndex: 40, type: 'string.quote.proto' }, { startIndex: 41, type: 'string.proto' }, { startIndex: 52, type: 'string.quote.proto' }, { startIndex: 53, type: 'delimiter.square.proto' }, { startIndex: 54, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message Outer {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 13, type: 'white.proto' }, { startIndex: 14, type: 'delimiter.curly.proto' } ] }, { line: ' option (my_option).a= true;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 8, type: 'white.proto' }, { startIndex: 9, type: 'annotation.proto' }, { startIndex: 22, type: 'operator.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'keyword.constant.proto' }, { startIndex: 28, type: 'delimiter.proto' } ] }, { line: ' message Inner { // Level 2', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 9, type: 'white.proto' }, { startIndex: 10, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 20, type: 'comment.proto' } ] }, { line: ' required int64 ival = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'keyword.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'identifier.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'delimiter.proto' }, { startIndex: 25, type: 'white.proto' }, { startIndex: 26, type: 'number.proto' }, { startIndex: 27, type: 'delimiter.proto' } ] }, { line: ' }', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' } ] }, { line: ' repeated Inner inner_message = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'identifier.proto' }, { startIndex: 30, type: 'white.proto' }, { startIndex: 31, type: 'delimiter.proto' }, { startIndex: 32, type: 'white.proto' }, { startIndex: 33, type: 'number.proto' }, { startIndex: 34, type: 'delimiter.proto' } ] }, { line: ' optional foo .bar', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' } ] }, { line: ' /**/ .EnumAllowingAlias enum_field =3;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 3, type: 'comment.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'identifier.proto' }, { startIndex: 37, type: 'white.proto' }, { startIndex: 38, type: 'delimiter.proto' }, { startIndex: 39, type: 'number.proto' }, { startIndex: 40, type: 'delimiter.proto' } ] }, { line: ' optional map my_map = 4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'identifier.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.proto' }, { startIndex: 23, type: 'white.proto' }, { startIndex: 24, type: 'number.proto' }, { startIndex: 25, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message message {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' } ] }, { line: ' repeated Foo enum = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'identifier.proto' }, { startIndex: 19, type: 'white.proto' }, { startIndex: 20, type: 'delimiter.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'number.proto' }, { startIndex: 23, type: 'delimiter.proto' } ] }, { line: ' optional Foo int32 = 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 14, type: 'white.proto' }, { startIndex: 15, type: 'identifier.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'delimiter.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'number.proto' }, { startIndex: 24, type: 'delimiter.proto' } ] }, { line: ' optional service x = 3;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'type.identifier.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'identifier.proto' }, { startIndex: 20, type: 'white.proto' }, { startIndex: 21, type: 'delimiter.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'number.proto' }, { startIndex: 24, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message service {}', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 15, type: 'white.proto' }, { startIndex: 16, type: 'delimiter.curly.proto' } ] }, { line: '', tokens: [] }, { line: '/** SearchService does nothing and returns the string "foo"', tokens: [{ startIndex: 0, type: 'comment.proto' }] }, { line: '*/', tokens: [{ startIndex: 0, type: 'comment.proto' }] }, { line: 'service SearchService {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'identifier.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.curly.proto' } ] }, { line: ' rpc Search (SearchRequest) returns (SearchResponse) {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 5, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 12, type: 'white.proto' }, { startIndex: 13, type: 'delimiter.parenthesis.proto' }, { startIndex: 14, type: 'type.identifier.proto' }, { startIndex: 27, type: 'delimiter.parenthesis.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'keyword.proto' }, { startIndex: 36, type: 'white.proto' }, { startIndex: 37, type: 'delimiter.parenthesis.proto' }, { startIndex: 38, type: 'type.identifier.proto' }, { startIndex: 52, type: 'delimiter.parenthesis.proto' }, { startIndex: 53, type: 'white.proto' }, { startIndex: 54, type: 'delimiter.curly.proto' } ] }, { line: ' option (method_option) = {', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'annotation.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'operator.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'delimiter.curly.proto' } ] }, { line: ' method_id: 2;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 15, type: 'delimiter.proto' }, { startIndex: 16, type: 'white.proto' }, { startIndex: 17, type: 'number.proto' }, { startIndex: 18, type: 'delimiter.proto' } ] }, { line: ' method_name: "hello";', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 17, type: 'delimiter.proto' }, { startIndex: 18, type: 'white.proto' }, { startIndex: 19, type: 'string.quote.proto' }, { startIndex: 20, type: 'string.proto' }, { startIndex: 25, type: 'string.quote.proto' }, { startIndex: 26, type: 'delimiter.proto' } ] }, { line: ' method_sla: 9.807E+4;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 6, type: 'identifier.proto' }, { startIndex: 16, type: 'delimiter.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'number.proto' }, { startIndex: 19, type: 'number.float.proto' }, { startIndex: 26, type: 'delimiter.proto' } ] }, { line: ' };', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 4, type: 'delimiter.curly.proto' }, { startIndex: 5, type: 'delimiter.proto' } ] }, { line: ' };', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'delimiter.curly.proto' }, { startIndex: 3, type: 'delimiter.proto' } ] }, { line: '}', tokens: [{ startIndex: 0, type: 'delimiter.curly.proto' }] }, { line: '', tokens: [] }, { line: 'message SearchRequest {};', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 21, type: 'white.proto' }, { startIndex: 22, type: 'delimiter.curly.proto' }, { startIndex: 24, type: 'delimiter.proto' } ] }, { line: 'message SearchResponse {', tokens: [ { startIndex: 0, type: 'keyword.proto' }, { startIndex: 7, type: 'white.proto' }, { startIndex: 8, type: 'type.identifier.proto' }, { startIndex: 22, type: 'white.proto' }, { startIndex: 23, type: 'delimiter.curly.proto' } ] }, { line: ' optional string response = 1;', tokens: [ { startIndex: 0, type: 'white.proto' }, { startIndex: 2, type: 'keyword.proto' }, { startIndex: 10, type: 'white.proto' }, { startIndex: 11, type: 'keyword.proto' }, { startIndex: 17, type: 'white.proto' }, { startIndex: 18, type: 'identifier.proto' }, { startIndex: 26, type: 'white.proto' }, { startIndex: 27, type: 'delimiter.proto' }, { startIndex: 28, type: 'white.proto' }, { startIndex: 29, type: 'number.proto' }, { startIndex: 30, type: 'delimiter.proto' } ] }, { line: '};', tokens: [ { startIndex: 0, type: 'delimiter.curly.proto' }, { startIndex: 1, type: 'delimiter.proto' } ] } ] ]);
the_stack
import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, Observable } from 'rxjs'; import { Authorization, ServerAPI } from '../core/api'; import { Completer } from '../utils/completer'; import { removeItem } from "../utils/local-storage"; import { getItem, setItem } from "../utils/aes-local-storage"; import { getUnix } from '../utils/utils'; import { md5String } from '../utils/md5'; import { aesDecrypt, aesEncrypt } from '../utils/aes'; import { Codes, NetError } from '../core/restful'; const Key = 'session' const Platform = 'web' export interface Userdata { readonly id: string readonly name?: string readonly nickname?: string readonly authorization?: Array<number> } export class Session { constructor(public access: string, public refresh: string, public userdata: Userdata) { } get who(): string { if (!this.userdata || !this.userdata.id) { return '' } let name = this.userdata.name ?? '' const nickname = this.userdata.nickname ?? '' return nickname.length == 0 ? name : `${nickname} [${name}]` } get root(): boolean { return this.anyAuth(Authorization.Root) } get write(): boolean { return this.anyAuth(Authorization.Write) } get read(): boolean { return this.anyAuth(Authorization.Read) } get authorization(): Array<number> { if (!this.userdata || !this.userdata.authorization || !Array.isArray(this.userdata.authorization)) { return [] } return this.userdata.authorization } /** * if has all authorization return true */ testAuth(...vals: Array<number>): boolean { if (!this.userdata || !this.userdata.id) { return false } let found: boolean const authorization = this.authorization for (let i = 0; i < vals.length; i++) { found = false const val = vals[i] for (let j = 0; j < authorization.length; j++) { if (val == authorization[j]) { found = true break } } if (!found) { return false } } return true } /** * if not has any authorization return true */ noneAuth(...vals: Array<number>): boolean { if (!this.userdata || !this.userdata.id) { return false } const authorization = this.authorization for (let i = 0; i < authorization.length; i++) { for (let j = 0; j < vals.length; j++) { const val = vals[j] if (authorization[i] == val) { return false } } } return true } /** * if has any authorization return true */ anyAuth(...vals: Array<number>): boolean { if (!this.userdata || !this.userdata.id) { return false } const authorization = this.authorization for (let i = 0; i < authorization.length; i++) { for (let j = 0; j < vals.length; j++) { const val = vals[j] if (authorization[i] == val) { return true } } } return false } } interface Store { userdata: Userdata access: string refresh: string deadline?: number } interface SigninResponse { access: string refresh: string id: string name: string nickname: string authorization: Array<number> } interface RefreshResponse { access: string refresh: string } export class Manager { static instance_ = new Manager() static get instance(): Manager { return Manager.instance_ } private constructor() { } private remember_ = false get session(): Session | undefined { return this.subject_.value } private readonly subject_ = new BehaviorSubject<Session | undefined>(undefined) get observable(): Observable<Session | undefined> { return this.subject_ } private _load(httpClient?: HttpClient): Session | undefined { const str = getItem(Key) if (typeof str !== "string") { return } try { const obj: Store = JSON.parse(aesDecrypt(str)) if (obj !== null && typeof obj === "object") { const access = obj.access const refresh = obj.refresh const userdata = obj.userdata if (typeof access === "string" && access.length > 0 && typeof refresh === "string" && refresh.length > 0 && userdata !== null && typeof userdata === "object" && userdata.id) { this.remember_ = true const session = new Session(access, refresh, userdata) const deadline = obj.deadline if (httpClient && typeof deadline == "number" && deadline < Date.now()) { this._refreshUserdata(httpClient, session) } return session } } } catch (e) { console.warn(`load token error`, e) } return } private _refreshUserdata(httpClient: HttpClient, session: Session) { ServerAPI.v1.sessions.child('access').get<Userdata>(httpClient, { params: { at: Date.now().toString(), }, headers: { Interceptor: 'none', Authorization: `Bearer ${session.access}`, } }, ).toPromise().then((_) => { if (session == this.session) { this._save(session) } }, (e) => { if (e instanceof NetError) { if (e.grpc == Codes.Unauthenticated) { this.refresh(httpClient, session, e).catch((e) => { }) } else if (e.grpc == Codes.PermissionDenied && e.message == 'token not exists') { this.clear(session) } } }) } load(httpClient: HttpClient) { this.subject_.next(this._load(httpClient)) } private _save(session: Session) { try { const data = JSON.stringify({ userdata: session.userdata, access: session.access, refresh: session.refresh, deadline: Date.now() + 1000 * 60 * 5,//5 minute }) console.log(`save token`, data) setItem(Key, aesEncrypt(data)) } catch (e) { console.log('save token error', e) } } refresh_: Completer<Session | undefined> | undefined private readonly signining_ = new BehaviorSubject<boolean>(false) get signining(): Observable<boolean> { return this.signining_ } async signin(httpClient: HttpClient, name: string, password: string, remember: boolean, ): Promise<Session | undefined> { if (this.signining_.value) { console.warn('wait signing completed') return } this.signining_.next(true) this.remember_ = remember let completer: Completer<Session | undefined> | undefined let session: Session | undefined try { // wait refresh completed while (this.refresh_) { const completer = this.refresh_ try { await completer.promise } catch (error) { } if (completer == this.refresh_) { this.refresh_ = undefined } } completer = new Completer<Session | undefined>() this.refresh_ = completer const unix = getUnix() password = md5String(password) password = md5String(`${Platform}.${password}.${unix}`) const response = await ServerAPI.v1.sessions.post<SigninResponse>(httpClient, { platform: Platform, name: name, password: password, unix: unix, }, { headers: { 'Interceptor': 'none', }, }, ).toPromise() session = new Session(response.access, response.refresh, { id: response.id, name: response.name, nickname: response.nickname, authorization: response.authorization, }) if (remember) { this._save(session) } this.subject_.next(session) } finally { if (completer) { completer.resolve(session) if (completer == this.refresh_) { this.refresh_ = undefined } } this.signining_.next(false) } return } signout(httpClient: HttpClient) { const session = this.subject_.value if (session) { if (this.remember_) { removeItem(Key) } this.subject_.next(undefined) ServerAPI.v1.sessions.child('access').delete(httpClient, { headers: { Interceptor: 'none', Authorization: `Bearer ${session.access}` } }).toPromise().then(() => { console.info(`signout who=${session.who}`) }, (e) => { console.warn(`signout who=${session.who} error=${e}`) }) } } async refresh(httpClient: HttpClient, session: Session, err?: NetError): Promise<Session | undefined> { if (this.refresh_) { // refreshing return this.refresh_.promise } const current = this.subject_.value if (!current) { // already signout return } else if (session != current) { // already refresh return current } if (err && err.grpc != Codes.Unauthenticated) { throw err } // refresh const completer = new Completer<Session | undefined>() this.refresh_ = completer ServerAPI.v1.sessions.child('refresh').post<RefreshResponse>(httpClient, { access: session.access, refresh: session.refresh, }, { headers: { Interceptor: 'none', } }, ).toPromise().then((resp) => { const s = new Session(resp.access, resp.refresh, session.userdata) if (this.remember_) { this._save(s) } this.subject_.next(s) completer.resolve(s) }, (e) => { completer.reject(e) }).finally(() => { this.refresh_ = undefined }) return completer.promise } clear(session: Session) { if (session == this.subject_.value) { this.subject_.next(undefined) if (this.remember_) { const current = this._load() if (current && current.access == session.access) { removeItem(Key) } } } } }
the_stack