repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/domain/PrimitiveType.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { PRIMITIVE_TYPE } from '../../../../../MetaModelConst'; import { DataType } from './DataType'; import type { PackageableElementVisitor } from '../../../model/packageableElements/PackageableElement'; import type { Type } from './Type'; export class PrimitiveType extends DataType { isSuperType(type: Type): boolean { if (!(type instanceof PrimitiveType)) { return false; } if (this.name === PRIMITIVE_TYPE.NUMBER) { return ( type.name === PRIMITIVE_TYPE.INTEGER || type.name === PRIMITIVE_TYPE.FLOAT || type.name === PRIMITIVE_TYPE.DECIMAL ); } if (this.name === PRIMITIVE_TYPE.DATE) { return ( type.name === PRIMITIVE_TYPE.STRICTDATE || type.name === PRIMITIVE_TYPE.DATETIME || type.name === PRIMITIVE_TYPE.LATESTDATE ); } return false; } isSubType(type: Type): boolean { if (!(type instanceof PrimitiveType)) { return false; } if (type.name === PRIMITIVE_TYPE.NUMBER) { return ( this.name === PRIMITIVE_TYPE.INTEGER || this.name === PRIMITIVE_TYPE.FLOAT || this.name === PRIMITIVE_TYPE.DECIMAL ); } if (type.name === PRIMITIVE_TYPE.DATE) { return ( this.name === PRIMITIVE_TYPE.STRICTDATE || this.name === PRIMITIVE_TYPE.DATETIME || this.name === PRIMITIVE_TYPE.LATESTDATE ); } return false; } accept_PackageableElementVisitor<T>( visitor: PackageableElementVisitor<T>, ): T { return visitor.visit_PrimitiveType(this); } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/model/packageableElements/store/relational/model/V1_RelationalDataType.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { Hashable } from '@finos/legend-studio-shared'; import { hashArray } from '@finos/legend-studio-shared'; import { CORE_HASH_STRUCTURE } from '../../../../../../../../MetaModelConst'; export abstract class V1_RelationalDataType implements Hashable { private readonly _$nominalTypeBrand!: 'V1_RelationalDataType'; abstract get hashCode(): string; } export class V1_VarChar extends V1_RelationalDataType implements Hashable { size!: number; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_VARCHAR, this.size.toString(), ]); } } export class V1_Char extends V1_RelationalDataType implements Hashable { size!: number; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_CHAR, this.size.toString(), ]); } } export class V1_VarBinary extends V1_RelationalDataType implements Hashable { size!: number; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_VARBINARY, this.size.toString(), ]); } } export class V1_Binary extends V1_RelationalDataType implements Hashable { size!: number; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_BINARY, this.size.toString(), ]); } } export class V1_Bit extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_BIT]); } } export class V1_Integer extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_INTEGER]); } } export class V1_BigInt extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_BIGINT]); } } export class V1_SmallInt extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_SMALLINT]); } } export class V1_TinyInt extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_TINYINT]); } } export class V1_Numeric extends V1_RelationalDataType implements Hashable { precision!: number; scale!: number; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_NUMERIC, this.precision.toString(), this.scale.toString(), ]); } } export class V1_Decimal extends V1_RelationalDataType implements Hashable { precision!: number; scale!: number; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_DECIMAL, this.precision.toString(), this.scale.toString(), ]); } } export class V1_Double extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_DOUBLE]); } } export class V1_Float extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_FLOAT]); } } export class V1_Real extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_REAL]); } } export class V1_Date extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_DATE]); } } export class V1_Timestamp extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_TIMESTAMP]); } } export class V1_Other extends V1_RelationalDataType implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.RELATIONAL_DATATYPE_VARCHAR]); } }
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/stores/QueryBuilderLambdaBuilder.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { guaranteeNonNullable, UnsupportedOperationError, } from '@finos/legend-studio-shared'; import type { Class, ValueSpecification } from '@finos/legend-studio'; import { Multiplicity, UnknownValue, V1_GraphTransformerContextBuilder, V1_serializeRawValueSpecification, V1_transformRawLambda, extractElementNameFromPath, InstanceValue, PackageableElementExplicitReference, CollectionInstanceValue, CORE_ELEMENT_PATH, FunctionType, GenericType, GenericTypeExplicitReference, LambdaFunction, PrimitiveInstanceValue, PRIMITIVE_TYPE, RootGraphFetchTreeInstanceValue, SimpleFunctionExpression, TYPICAL_MULTIPLICITY_TYPE, } from '@finos/legend-studio'; import { isGraphFetchTreeDataEmpty } from './QueryBuilderGraphFetchTreeUtil'; import type { QueryBuilderState } from './QueryBuilderState'; import { SUPPORTED_FUNCTIONS } from '../QueryBuilder_Const'; import { buildFilterExpression } from './QueryBuilderFilterState'; import { QueryBuilderDerivationProjectionColumnState, QueryBuilderSimpleProjectionColumnState, } from './QueryBuilderProjectionState'; import { buildGenericLambdaFunctionInstanceValue } from './QueryBuilderValueSpecificationBuilderHelper'; export const buildGetAllFunction = ( _class: Class, multiplicity: Multiplicity, ): SimpleFunctionExpression => { const _func = new SimpleFunctionExpression( extractElementNameFromPath(SUPPORTED_FUNCTIONS.GET_ALL), multiplicity, ); const classInstance = new InstanceValue( multiplicity, GenericTypeExplicitReference.create(new GenericType(_class)), ); classInstance.values[0] = PackageableElementExplicitReference.create(_class); _func.parametersValues.push(classInstance); return _func; }; export const buildLambdaFunction = ( queryBuilderState: QueryBuilderState, options?: { /** * Set queryBuilderState to `true` when we construct query for execution within the app. * queryBuilderState will make the lambda function building process overrides several query values, such as the row limit. */ isBuildingExecutionQuery?: boolean; keepSourceInformation?: boolean; }, ): LambdaFunction => { const _class = guaranteeNonNullable( queryBuilderState.querySetupState._class, 'Class is required to build query', ); const multiplicityOne = queryBuilderState.editorStore.graphState.graph.getTypicalMultiplicity( TYPICAL_MULTIPLICITY_TYPE.ONE, ); const typeString = queryBuilderState.editorStore.graphState.graph.getPrimitiveType( PRIMITIVE_TYPE.STRING, ); const typeAny = queryBuilderState.editorStore.graphState.graph.getType( CORE_ELEMENT_PATH.ANY, ); const lambdaFunction = new LambdaFunction( new FunctionType(typeAny, multiplicityOne), ); // build getAll() const getAllFunction = buildGetAllFunction(_class, multiplicityOne); lambdaFunction.expressionSequence[0] = getAllFunction; // build filter() const filterFunction = buildFilterExpression( queryBuilderState.filterState, getAllFunction, ); if (filterFunction) { lambdaFunction.expressionSequence[0] = filterFunction; } // build fetch structure if (queryBuilderState.fetchStructureState.isProjectionMode()) { if ( queryBuilderState.fetchStructureState.projectionState.aggregationState .columns.length ) { // aggregation const groupByFunction = new SimpleFunctionExpression( extractElementNameFromPath(SUPPORTED_FUNCTIONS.TDS_GROUP_BY), multiplicityOne, ); const colLambdas = new CollectionInstanceValue( new Multiplicity( queryBuilderState.fetchStructureState.projectionState.columns.length - queryBuilderState.fetchStructureState.projectionState .aggregationState.columns.length, queryBuilderState.fetchStructureState.projectionState.columns.length - queryBuilderState.fetchStructureState.projectionState .aggregationState.columns.length, ), ); const aggregateLambdas = new CollectionInstanceValue( new Multiplicity( queryBuilderState.fetchStructureState.projectionState.aggregationState.columns.length, queryBuilderState.fetchStructureState.projectionState.aggregationState.columns.length, ), ); const colAliases = new CollectionInstanceValue( new Multiplicity( queryBuilderState.fetchStructureState.projectionState.columns.length, queryBuilderState.fetchStructureState.projectionState.columns.length, ), ); queryBuilderState.fetchStructureState.projectionState.columns.forEach( (projectionColumnState) => { // column alias const colAlias = new PrimitiveInstanceValue( GenericTypeExplicitReference.create(new GenericType(typeString)), multiplicityOne, ); colAlias.values.push(projectionColumnState.columnName); colAliases.values.push(colAlias); const aggregateColumnState = queryBuilderState.fetchStructureState.projectionState.aggregationState.columns.find( (column) => column.projectionColumnState === projectionColumnState, ); // column projection let columnLambda: ValueSpecification; if ( projectionColumnState instanceof QueryBuilderSimpleProjectionColumnState ) { columnLambda = buildGenericLambdaFunctionInstanceValue( projectionColumnState.lambdaParameterName, [ projectionColumnState.propertyExpressionState .propertyExpression, ], queryBuilderState.editorStore.graphState.graph, ); } else if ( projectionColumnState instanceof QueryBuilderDerivationProjectionColumnState ) { columnLambda = new UnknownValue( V1_serializeRawValueSpecification( V1_transformRawLambda( projectionColumnState.lambda, new V1_GraphTransformerContextBuilder( // TODO?: do we need to include the plugins here? [], ) .withKeepSourceInformationFlag( Boolean(options?.keepSourceInformation), ) .build(), ), ), ); } else { throw new UnsupportedOperationError( `Can't build project() column expression: unsupported projection column state`, projectionColumnState, ); } // column aggregation if (aggregateColumnState) { const aggregateFunctionExpression = new SimpleFunctionExpression( extractElementNameFromPath(SUPPORTED_FUNCTIONS.TDS_AGG), multiplicityOne, ); const aggregateLambda = buildGenericLambdaFunctionInstanceValue( aggregateColumnState.lambdaParameterName, [ aggregateColumnState.operator.buildAggregateExpressionFromState( aggregateColumnState, ), ], aggregateColumnState.editorStore.graphState.graph, ); aggregateFunctionExpression.parametersValues = [ columnLambda, aggregateLambda, ]; aggregateLambdas.values.push(aggregateFunctionExpression); } else { colLambdas.values.push(columnLambda); } }, ); const expression = lambdaFunction.expressionSequence[0]; groupByFunction.parametersValues = [ expression, colLambdas, aggregateLambdas, colAliases, ]; lambdaFunction.expressionSequence[0] = groupByFunction; } else if ( queryBuilderState.fetchStructureState.projectionState.columns.length ) { // projection const projectFunction = new SimpleFunctionExpression( extractElementNameFromPath(SUPPORTED_FUNCTIONS.TDS_PROJECT), multiplicityOne, ); const colLambdas = new CollectionInstanceValue( new Multiplicity( queryBuilderState.fetchStructureState.projectionState.columns.length, queryBuilderState.fetchStructureState.projectionState.columns.length, ), ); const colAliases = new CollectionInstanceValue( new Multiplicity( queryBuilderState.fetchStructureState.projectionState.columns.length, queryBuilderState.fetchStructureState.projectionState.columns.length, ), ); queryBuilderState.fetchStructureState.projectionState.columns.forEach( (projectionColumnState) => { // column alias const colAlias = new PrimitiveInstanceValue( GenericTypeExplicitReference.create(new GenericType(typeString)), multiplicityOne, ); colAlias.values.push(projectionColumnState.columnName); colAliases.values.push(colAlias); // column projection let columnLambda: ValueSpecification; if ( projectionColumnState instanceof QueryBuilderSimpleProjectionColumnState ) { columnLambda = buildGenericLambdaFunctionInstanceValue( projectionColumnState.lambdaParameterName, [ projectionColumnState.propertyExpressionState .propertyExpression, ], queryBuilderState.editorStore.graphState.graph, ); } else if ( projectionColumnState instanceof QueryBuilderDerivationProjectionColumnState ) { columnLambda = new UnknownValue( V1_serializeRawValueSpecification( V1_transformRawLambda( projectionColumnState.lambda, new V1_GraphTransformerContextBuilder( // TODO?: do we need to include the plugins here? [], ) .withKeepSourceInformationFlag( Boolean(options?.keepSourceInformation), ) .build(), ), ), ); } else { throw new UnsupportedOperationError( `Can't build project() column expression: unsupported projection column state`, projectionColumnState, ); } colLambdas.values.push(columnLambda); }, ); const expression = lambdaFunction.expressionSequence[0]; projectFunction.parametersValues = [expression, colLambdas, colAliases]; lambdaFunction.expressionSequence[0] = projectFunction; } } else if ( queryBuilderState.fetchStructureState.isGraphFetchMode() && queryBuilderState.fetchStructureState.graphFetchTreeState.treeData && !isGraphFetchTreeDataEmpty( queryBuilderState.fetchStructureState.graphFetchTreeState.treeData, ) ) { const graphFetchInstance = new RootGraphFetchTreeInstanceValue( multiplicityOne, ); graphFetchInstance.values = [ queryBuilderState.fetchStructureState.graphFetchTreeState.treeData.tree, ]; const serializeFunction = new SimpleFunctionExpression( extractElementNameFromPath(SUPPORTED_FUNCTIONS.SERIALIZE), multiplicityOne, ); const graphFetchFunc = new SimpleFunctionExpression( queryBuilderState.fetchStructureState.graphFetchTreeState.isChecked ? extractElementNameFromPath(SUPPORTED_FUNCTIONS.GRAPH_FETCH_CHECKED) : extractElementNameFromPath(SUPPORTED_FUNCTIONS.GRAPH_FETCH), multiplicityOne, ); const expression = lambdaFunction.expressionSequence[0]; graphFetchFunc.parametersValues = [expression, graphFetchInstance]; serializeFunction.parametersValues = [graphFetchFunc, graphFetchInstance]; lambdaFunction.expressionSequence[0] = serializeFunction; } // build result set modifiers queryBuilderState.resultSetModifierState.processModifiersOnLambda( lambdaFunction, { overridingLimit: options?.isBuildingExecutionQuery ? queryBuilderState.resultState.previewLimit : undefined, }, ); return lambdaFunction; };
nayanika2/legend-studio
packages/legend-studio/src/models/sdlc/models/configuration/ProjectConfiguration.ts
<filename>packages/legend-studio/src/models/sdlc/models/configuration/ProjectConfiguration.ts<gh_stars>1-10 /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { list, createModelSchema, primitive, optional } from 'serializr'; import { observable, action, computed, makeObservable } from 'mobx'; import type { ProjectType } from '../project/Project'; import { ProjectStructureVersion } from '../configuration/ProjectStructureVersion'; import { ProjectDependency } from '../configuration/ProjectDependency'; import { hashArray, addUniqueEntry, deleteEntry, SerializationFactory, usingModelSchema, } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import { ENTITY_PATH_DELIMITER } from '../../SDLCUtils'; const PROJECT_CONFIGURATION_HASH_STRUCTURE = 'PROJECT_CONFIGURATION'; export class ProjectConfiguration implements Hashable { projectId!: string; projectType!: ProjectType; // TODO: check why these 2 fields are optional, they are not in SDLC server groupId?: string; artifactId?: string; projectStructureVersion!: ProjectStructureVersion; projectDependencies: ProjectDependency[] = []; constructor() { makeObservable(this, { groupId: observable, artifactId: observable, projectStructureVersion: observable, projectDependencies: observable, setGroupId: action, setArtifactId: action, deleteProjectDependency: action, addProjectDependency: action, dependencyKey: computed, hashCode: computed, }); } static readonly serialization = new SerializationFactory( createModelSchema(ProjectConfiguration, { artifactId: optional(primitive()), groupId: optional(primitive()), projectDependencies: list( usingModelSchema(ProjectDependency.serialization.schema), ), projectId: primitive(), projectStructureVersion: usingModelSchema( ProjectStructureVersion.serialization.schema, ), projectType: primitive(), }), ); setGroupId(val: string | undefined): void { this.groupId = val; } setArtifactId(val: string | undefined): void { this.artifactId = val; } deleteProjectDependency(val: ProjectDependency): void { deleteEntry(this.projectDependencies, val); } addProjectDependency(val: ProjectDependency): void { addUniqueEntry(this.projectDependencies, val); } get dependencyKey(): string { return `${(this.groupId ?? '').replace( /\./g, ENTITY_PATH_DELIMITER, )}${ENTITY_PATH_DELIMITER}${this.artifactId}`; } get hashCode(): string { return hashArray([ PROJECT_CONFIGURATION_HASH_STRUCTURE, this.groupId ?? '', this.artifactId ?? '', this.projectType, this.projectStructureVersion.version.toString(), this.projectStructureVersion.extensionVersion?.toString() ?? '', hashArray(this.projectDependencies), ]); } }
nayanika2/legend-studio
packages/legend-studio/src/models/protocols/pure/v1/engine/execution/V1_ExecutionResult.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { createModelSchema, list, primitive, raw } from 'serializr'; import type { PlainObject } from '@finos/legend-studio-shared'; import { SerializationFactory, usingModelSchema, } from '@finos/legend-studio-shared'; import { TdsRow, OtherExecutionResult, ClassExecutionResult, JsonExecutionResult, RelationalExecutionActivity, TdsExecutionResult, TdsBuilder, TDSColumn, BuilderType, } from '../../../../../metamodels/pure/action/execution/ExecutionResult'; import type { ExecutionResult } from '../../../../../metamodels/pure/action/execution/ExecutionResult'; // ------------------------------------------------------------------------------------------------------------------ // TODO: when we move these models out into ../models. We should have serialization and building logic separated // out of the protocol models. // ------------------------------------------------------------------------------------------------------------------ export class V1_ResultBuilder { _type!: string; // to be removed when we handle this the same way as other protocol models static readonly builderSerialization = new SerializationFactory( createModelSchema(V1_ResultBuilder, { _type: primitive(), }), ); } export abstract class V1_ExecutionActivity { _type!: string; // to be removed when we handle this the same way as other protocol models } export abstract class V1_ExecutionResult { _type!: string; // to be removed when we handle this the same way as other protocol models builder!: V1_ResultBuilder; activities?: V1_ExecutionActivity[]; abstract build(): ExecutionResult; } // JSON export class V1_JsonExecutionResult extends V1_ExecutionResult { values!: object; static readonly serialization = new SerializationFactory( createModelSchema(V1_JsonExecutionResult, { _type: primitive(), builder: usingModelSchema(V1_ResultBuilder.builderSerialization.schema), values: raw(), }), ); build(): JsonExecutionResult { const result = new JsonExecutionResult(this.values); return result; } } // V1_RelationalExecutionActivity export class V1_RelationalExecutionActivity extends V1_ExecutionActivity { sql!: string; static readonly serialization = new SerializationFactory( createModelSchema(V1_RelationalExecutionActivity, { _type: primitive(), sql: primitive(), }), ); build(): RelationalExecutionActivity { const result = new RelationalExecutionActivity(); result.sql = this.sql; return result; } } // TDS export class V1_TDSColumn { name!: string; type!: string; relationalType!: string; static readonly serialization = new SerializationFactory( createModelSchema(V1_TDSColumn, { name: primitive(), type: primitive(), relationalType: primitive(), }), ); build(): TDSColumn { return new TDSColumn(this.name, this.type, this.relationalType); } } export class V1_TdsBuilder extends V1_ResultBuilder { columns: V1_TDSColumn[] = []; static readonly serialization = new SerializationFactory( createModelSchema(V1_TdsBuilder, { _type: primitive(), columns: list(usingModelSchema(V1_TDSColumn.serialization.schema)), }), ); build(): TdsBuilder { const result = new TdsBuilder(); result.columns = this.columns.map((e) => e.build()); return result; } } export class V1_TdsExecutionResult extends V1_ExecutionResult { declare builder: V1_TdsBuilder; declare activities: V1_RelationalExecutionActivity[]; result!: object; static readonly serialization = new SerializationFactory( createModelSchema(V1_TdsExecutionResult, { _type: primitive(), builder: usingModelSchema(V1_TdsBuilder.serialization.schema), activities: list( usingModelSchema(V1_RelationalExecutionActivity.serialization.schema), ), result: raw(), }), ); build(): TdsExecutionResult { const tdsExecutionResult = new TdsExecutionResult(this.result); tdsExecutionResult.builder = this.builder.build(); tdsExecutionResult.activities = this.activities.map((e) => e.build()); tdsExecutionResult.result.columns = ( this.result as { columns: string[]; } ).columns; tdsExecutionResult.result.rows = ( this.result as { rows: { values: (string | number)[] }[]; } ).rows.map((r) => { const val = new TdsRow(); val.values = r.values; return val; }); return tdsExecutionResult; } } // Class export class V1_ClassExecutionResult extends V1_ExecutionResult { override activities: V1_RelationalExecutionActivity[] = []; objects!: object; static readonly serialization = new SerializationFactory( createModelSchema(V1_ClassExecutionResult, { _type: primitive(), builder: usingModelSchema(V1_ResultBuilder.builderSerialization.schema), activities: list( usingModelSchema(V1_RelationalExecutionActivity.serialization.schema), ), objects: raw(), }), ); build(): ClassExecutionResult { const result = new ClassExecutionResult(this.objects); result.activities = this.activities.map((e) => e.build()); return result; } } // Other class V1_OtherExecutionResult extends V1_ExecutionResult { values: object; constructor(values: object) { super(); this.values = values; } build(): OtherExecutionResult { return new OtherExecutionResult(this.values); } } export const V1_serializeExecutionResult = ( value: PlainObject<V1_ExecutionResult>, ): V1_ExecutionResult => { switch ((value.builder as PlainObject<V1_ResultBuilder>)._type) { case BuilderType.CLASS_BUILDER: return V1_ClassExecutionResult.serialization.fromJson(value); case BuilderType.TDS_BUILDER: return V1_TdsExecutionResult.serialization.fromJson(value); case BuilderType.JSON_BUILDER: return V1_JsonExecutionResult.serialization.fromJson(value); default: return new V1_OtherExecutionResult(value as object); } };
nayanika2/legend-studio
packages/legend-studio/src/stores/__tests__/roundtrip/DiagramRoundtripTestData.ts
<reponame>nayanika2/legend-studio /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // References to resolve in Diagram // - ClassView - class // - PropertyView - property // - AssociationView - association export const testDiagramRoundtrip = [ { path: 'test::tClass2', content: { _type: 'class', name: 'tClass2', package: 'test', }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'test::tClass', content: { _type: 'class', name: 'tClass', package: 'test', properties: [ { multiplicity: { lowerBound: 0, }, name: 'prop1', type: 'test::tClass2', }, ], superTypes: ['test::tClass2'], }, classifierPath: 'meta::pure::metamodel::type::Class', }, { path: 'test::tDiag', content: { _type: 'diagram', classViews: [ { class: 'tClass', id: '709b74cb-2605-4f4d-bf5d-8996b543279b', position: { x: 338, y: 114, }, rectangle: { height: 44, width: 109.8583984375, }, }, { class: 'tClass2', id: '1841211c-09d7-4293-ab87-f8155377cdf9', position: { x: 191, y: 311, }, rectangle: { height: 30, width: 62.69140625, }, }, ], generalizationViews: [ { line: { points: [ { x: 392.92919921875, y: 136, }, { x: 418, y: 311, }, { x: 222.345703125, y: 326, }, ], }, sourceView: '709b74cb-2605-4f4d-bf5d-8996b543279b', targetView: '1841211c-09d7-4293-ab87-f8155377cdf9', }, ], name: 'tDiag', package: 'test', propertyViews: [ { line: { points: [ { x: 392.92919921875, y: 136, }, { x: 222.345703125, y: 326, }, ], }, property: { class: 'tClass', property: 'prop1', }, sourceView: '709b74cb-2605-4f4d-bf5d-8996b543279b', targetView: '1841211c-09d7-4293-ab87-f8155377cdf9', }, ], }, classifierPath: 'meta::pure::metamodel::diagram::Diagram', }, { path: '__internal__::SectionIndex', content: { _type: 'sectionIndex', name: 'SectionIndex', package: '__internal__', sections: [ { _type: 'importAware', imports: [], elements: ['test::tClass2', 'test::tClass'], parserName: 'Pure', }, { _type: 'importAware', imports: ['test'], elements: ['test::tDiag'], parserName: 'Diagram', }, ], }, classifierPath: 'meta::pure::metamodel::section::SectionIndex', }, ];
nayanika2/legend-studio
packages/legend-studio/src/models/sdlc/models/workspace/Workspace.ts
<filename>packages/legend-studio/src/models/sdlc/models/workspace/Workspace.ts /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { createModelSchema, primitive } from 'serializr'; import { SerializationFactory } from '@finos/legend-studio-shared'; export const PROJECT_LATEST_VIEWER_WORKSPACE = '-PROJECT_LATEST_VIEWER_WORKSPACE'; export enum WORKSPACE_TYPE { STANDARD = 'STANDARD', CONFLICT_RESOLUTION = 'CONFLICT_RESOLUTION', // BACKUP = 'BACKUP', } export class Workspace { projectId!: string; workspaceId!: string; userId!: string; type = WORKSPACE_TYPE.STANDARD; static readonly serialization = new SerializationFactory( createModelSchema(Workspace, { projectId: primitive(), userId: primitive(), workspaceId: primitive(), }), ); static createProjectLatestViewerWorkspace(projectId: string): Workspace { const workspace = new Workspace(); workspace.projectId = projectId; workspace.workspaceId = PROJECT_LATEST_VIEWER_WORKSPACE; return workspace; } get isWorkspaceWithConflictResolution(): boolean { return this.type === WORKSPACE_TYPE.CONFLICT_RESOLUTION; } get selectOption(): WorkspaceSelectOption { return { label: this.workspaceId, value: this.workspaceId, }; } } export interface WorkspaceSelectOption { label: string; value: string; __isNew__?: boolean; }
nayanika2/legend-studio
packages/legend-studio/src/utils/Logger.ts
<filename>packages/legend-studio/src/utils/Logger.ts /** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export enum CORE_LOG_EVENT { // APPLICATION APPLICATION_LOADED = 'APPLICATION_LOADED', APPLICATION_LOAD_FAILED = 'APPLICATION_LOAD_FAILED', // CONFIG CONFIG_CONFIGURATION_FETCHING_PROBLEM = 'CONFIG_CONFIGURATION_FETCHING_PROBLEM', CONFIG_VERSION_INFO_FETCHING_PROBLEM = 'CONFIG_VERSION_INFO_FETCHING_PROBLEM', CONFIG_USER_ID_FETCHING_PROBLEM = 'CONFIG_USER_ID_FETCHING_PROBLEM', CONFIG_UNKNOWN_FEATURE_FLAG_PROBLEM = 'CONFIG_UNKNOWN_FEATURE_FLAG_PROBLEM', // GRAPH GRAPH_PROBLEM = 'GRAPH_PROBLEM', GRAPH_SYSTEM_BUILT = 'GRAPH_SYSTEM_BUILT', GRAPH_DEPENDENCIES_PREPROCESSED = 'GRAPH_DEPENDENCIES_PREPROCESSED', GRAPH_DEPENDENCIES_PROCESSED = 'GRAPH_DEPENDENCIES_PROCESSED', GRAPH_DEPENDENCIES_BUILT = 'GRAPH_DEPENDENCIES_BUILT', GRAPH_GENERATIONS_START = 'GRAPH_GENERATIONS_START', GRAPH_GENERATIONS_BUILT = 'GRAPH_GENERATIONS_BUILT', GRAPH_ENTITIES_FETCHED = 'GRAPH_ENTITIES_FETCHED', GRAPH_ENTITIES_GENERATED = 'GRAPH_ENTITIES_GENERATED', GRAPH_BUILD_STARTED = 'GRAPH_BUILD_STARTED', GRAPH_BUILD_INITIALIZED = 'GRAPH_BUILD_INITIALIZED', GRAPH_BUILD_DATA_MODEL_PARSED = 'GRAPH_BUILD_DATA_MODEL_PARSED', GRAPH_HASHES_PREPROCESSED = 'GRAPH_HASHES_PREPROCESSED', GRAPH_HASHES_DISPOSED = 'GRAPH_HASHES_DISPOSED', GRAPH_BUILT = 'GRAPH_BUILT', GRAPH_COMPILED = 'GRAPH_COMPILED', GRAPH_BUILD_FAILED = 'GRAPH_BUILD_FAILED', GRAPH_REBUILDING = 'GRAPH_REBUILDING', GRAPH_REBUILT = 'GRAPH_REBUILT', GRAPH_MODEL_TO_GRAMMAR_TRANSFORMED = 'GRAPH_MODEL_TO_GRAMMAR_TRANSFORMED', GRAPH_GRAMMAR_TO_MODEL_TRANSFORMED = 'GRAPH_GRAMMAR_TO_MODEL_TRANSFORMED', GRAPH_META_MODEL_TO_PROTOCOL_TRANSFORMED = 'GRAPH_META_MODEL_TO_PROTOCOL_TRANSFORMED', GRAPH_COMPILE_CONTEXT_COLLECTED = 'GRAPH_COMPILE_CONTEXT_COLLECTED', GRAPH_PROTOCOL_SERIALIZED = 'GRAPH_PROTOCOL_SERIALIZED', GRAPH_CHANGES_DETECTED = 'GRAPH_CHANGES_DETECTED', GRAPH_INITIALIZED = 'GRAPH_INITIALIZED', GRAPH_HASH_SNAPSHOTED = 'GRAPH_HASH_SNAPSHOTED', GRAPH_BUILD_ELEMENTS_INITIALIZED_AND_INDEXED = 'GRAPH_BUILD_ELEMENTS_INITIALIZED_AND_INDEXED', GRAPH_BUILD_SECTION_INDICES_BUILT = 'GRAPH_BUILD_SECTION_INDICES_BUILT', GRAPH_BUILD_DOMAIN_MODELS_BUILT = 'GRAPH_BUILD_DOMAIN_MODELS_BUILT', GRAPH_BUILD_STORES_BUILT = 'GRAPH_BUILD_STORES_BUILT', GRAPH_BUILD_MAPPINGS_BUILT = 'GRAPH_BUILD_MAPPINGS_BUILT', GRAPH_BUILD_CONNECTIONS_AND_RUNTIMES_BUILT = 'GRAPH_BUILD_CONNECTIONS_AND_RUNTIMES_BUILT', GRAPH_BUILD_RUNTIMES_BUILT = 'GRAPH_BUILD_RUNTIMES_BUILT', GRAPH_BUILD_DIAGRAMS_BUILT = 'GRAPH_BUILD_DIAGRAMS_BUILT', GRAPH_BUILD_FILE_GENERATIONS_BUILT = 'GRAPH_BUILD_FILE_GENERATIONS_BUILT', GRAPH_BUILD_GENERATION_TREE_BUILT = 'GRAPH_BUILD_GENERATION_TREE_BUILT', GRAPH_BUILD_OTHER_ELEMENTS_BUILT = 'GRAPH_BUILD_OTHER_ELEMENTS_BUILT', GRAPH_BUILD_SERVICES_BUILT = 'GRAPH_BUILD_SERVICES_BUILT', // CHANGE DETECTION CHANGE_DETECTION_RESTARTED = 'CHANGE_DETECTION_RESTARTED', CHANGE_DETECTION_LOCAL_HASHES_INDEX_BUILT = 'CHANGE_DETECTION_LOCAL_HASHES_INDEX_BUILT', CHANGE_DETECTION_WORKSPACE_HASHES_INDEX_BUILT = 'CHANGE_DETECTION_WORKSPACE_HASHES_INDEX_BUILT', CHANGE_DETECTION_PROJECT_LATEST_HASHES_INDEX_BUILT = 'CHANGE_DETECTION_PROJECT_LATEST_HASHES_INDEX_BUILT', CHANGE_DETECTION_WORKSPACE_UPDATE_CONFLICTS_COMPUTED = 'CHANGE_DETECTION_WORKSPACE_UPDATE_CONFLICTS_COMPUTED', CHANGE_DETECTION_CONFLICT_RESOLUTION_CONFLICTS_COMPUTED = 'CHANGE_DETECTION_CONFLICT_RESOLUTION_CONFLICTS_COMPUTED', // SDLC SDLC_UPDATE_WORKSPACE = 'SDLC_UPDATE_WORKSPACE', SDLC_SYNC_WORKSPACE = 'SDLC_SYNC_WORKSPACE', // GENERATION GENERATED_MODEL = 'GENERATED_MODEL', // PROBLEM SERVICE_REGISTRATION_PROBLEM = 'SERVICE_REGISTRATION_PROBLEM', GENERATION_PROBLEM = 'GENERATION_PROBLEM', MODEL_LOADER_PROBLEM = 'MODEL_LOADER_PROBLEM', PROJECT_DEPENDENCY_PROBLEM = 'PROJECT_DEPENDENCY_PROBLEM', EXECUTION_PROBLEM = 'EXECUTION_PROBLEM', COMPILATION_PROBLEM = 'COMPILATION_PROBLEM', PARSING_PROBLEM = 'PARSING_PROBLEM', CHANGE_DETECTION_PROBLEM = 'CHANGE_DETECTION_PROBLEM', SETUP_PROBLEM = 'SETUP_PROBLEM', SDLC_PROBLEM = 'SDLC_PROBLEM', CODE_GENERATION_PROBLEM = 'CODE_GENERATION_PROBLEM', PACKAGE_TREE_PROBLEM = 'PACKAGE_TREE_PROBLEM', SERVICE_TEST_PROBLEM = 'SERVICE_TEST_PROBLEM', UNSUPPORTED_ENTITY_DETECTED = 'UNSUPPORTED_ENTITY_DETECTED', ILLEGAL_APPLICATION_STATE_OCCURRED = 'ILLEGAL_APPLICATION_STATE_OCCURRED', // OTHER EDITOR_FONT_LOADED = 'EDITOR_FONT_LOADED', DEVELOPMENT_MODE = '[DEVELOPMENT]', NONE = 'NONE', } export const SKIP_LOGGING_INFO = Symbol('SKIP_LOGGING_INFO'); // We use numeric enum here for because we want to do comparison // In order to retrieve the name of the enum we can do reverse mapping, for example: LogLevel[LogLevel.INFO] -> INFO // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings export enum LOG_LEVEL { DEBUG = 1, INFO, WARN, ERROR, SILENT, } export class Logger { level: LOG_LEVEL = LOG_LEVEL.DEBUG; previousLevelBeforeMuting: LOG_LEVEL = LOG_LEVEL.DEBUG; setLogLevel = (level: LOG_LEVEL): void => { this.level = level; }; /** * Mute logging, if a level is specified, mute all event of lower severity than that level */ mute = (level?: LOG_LEVEL): void => { this.previousLevelBeforeMuting = this.level; this.level = level ?? LOG_LEVEL.SILENT; }; unmute = (): void => { this.level = this.previousLevelBeforeMuting; }; runInSilent = (fn: Function, level?: LOG_LEVEL): void => { this.mute(level); fn(); this.unmute(); }; debug = (eventType: CORE_LOG_EVENT, ...info: unknown[]): void => this.level > LOG_LEVEL.DEBUG ? undefined : // eslint-disable-next-line no-console console.debug( eventType !== CORE_LOG_EVENT.NONE ? info.filter((i) => i !== SKIP_LOGGING_INFO).length ? `${eventType}:` : eventType : '', ...info.filter((i) => i !== SKIP_LOGGING_INFO), ); info = (eventType: CORE_LOG_EVENT, ...info: unknown[]): void => this.level > LOG_LEVEL.INFO ? undefined : // eslint-disable-next-line no-console console.info( eventType !== CORE_LOG_EVENT.NONE ? info.filter((i) => i !== SKIP_LOGGING_INFO).length ? `${eventType}:` : eventType : '', ...info.filter((i) => i !== SKIP_LOGGING_INFO), ); warn = (eventType: CORE_LOG_EVENT, ...info: unknown[]): void => this.level > LOG_LEVEL.WARN ? undefined : // eslint-disable-next-line no-console console.warn( eventType !== CORE_LOG_EVENT.NONE ? info.filter((i) => i !== SKIP_LOGGING_INFO).length ? `${eventType}:` : eventType : '', ...info.filter((i) => i !== SKIP_LOGGING_INFO), ); error = (eventType: CORE_LOG_EVENT, ...info: unknown[]): void => this.level > LOG_LEVEL.ERROR ? undefined : // eslint-disable-next-line no-console console.error( eventType !== CORE_LOG_EVENT.NONE ? info.filter((i) => i !== SKIP_LOGGING_INFO).length ? `${eventType}:` : eventType : '', ...info.filter((i) => i !== SKIP_LOGGING_INFO), ); }
nayanika2/legend-studio
packages/legend-studio-preset-query-builder/src/components/__tests__/QueryBuilder_TestFilterQueriesWithExists.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const lambda_input_filterWithExists = { _type: 'lambda', body: [ { _type: 'func', function: 'filter', parameters: [ { _type: 'func', function: 'getAll', parameters: [ { _type: 'packageableElementPtr', fullPath: 'model::target::_Firm', }, ], }, { _type: 'lambda', body: [ { _type: 'func', function: 'exists', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'x', }, ], property: 'employees', }, { _type: 'lambda', body: [ { _type: 'func', function: 'exists', parameters: [ { _type: 'property', parameters: [ { _type: 'var', name: 'x_1', }, ], property: 'fullName', }, { _type: 'lambda', body: [ { _type: 'func', function: 'equal', parameters: [ { _type: 'var', name: 'c', }, { _type: 'string', multiplicity: { lowerBound: 1, upperBound: 1, }, values: [''], }, ], }, ], parameters: [{ _type: 'var', name: 'c' }], }, ], }, ], parameters: [{ _type: 'var', name: 'x_1' }], }, ], }, ], parameters: [{ _type: 'var', name: 'x' }], }, ], }, ], parameters: [], }; export const lambda_output_filterWithExists = { _type: 'lambda', body: [ { _type: 'func', function: 'filter', parameters: [ { _type: 'func', function: 'getAll', parameters: [ { _type: 'packageableElementPtr', fullPath: 'model::target::_Firm', }, ], }, { _type: 'lambda', body: [ { _type: 'func', function: 'exists', parameters: [ { _type: 'property', property: 'employees', parameters: [ { _type: 'var', name: 'x', }, ], }, { _type: 'lambda', body: [ { _type: 'func', function: 'equal', parameters: [ { _type: 'property', property: 'fullName', parameters: [ { _type: 'var', name: 'x_1', }, ], }, { _type: 'string', values: [''], multiplicity: { lowerBound: 1, upperBound: 1, }, }, ], }, ], parameters: [ { _type: 'var', name: 'x_1', }, ], }, ], }, ], parameters: [ { _type: 'var', name: 'x', }, ], }, ], }, ], parameters: [], };
nayanika2/legend-studio
packages/legend-studio-preset-dsl-text/src/stores/__tests__/DSLText_Roundtrip.test.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { Entity } from '@finos/legend-studio'; import { getTestApplicationConfig, PluginManager, getTestEditorStore, checkBuildingElementsRoundtrip, } from '@finos/legend-studio'; import { unitTest } from '@finos/legend-studio-shared'; import { DSLText_Preset } from '../../DSLText_Preset'; import { roundtripTestData } from './DSLText_RoundtripTestData'; const pluginManager = PluginManager.create(); pluginManager.usePresets([new DSLText_Preset()]).install(); test(unitTest('Text import resolution roundtrip'), async () => { await checkBuildingElementsRoundtrip( roundtripTestData as Entity[], getTestEditorStore(getTestApplicationConfig(), pluginManager), ); });
nayanika2/legend-studio
packages/legend-studio/src/stores/__tests__/buildGraph/GraphBuildFailure.test.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { EditorStore } from '../../EditorStore'; import { testMissingSuperType, testMissingProfile, testMissingProperty, testMissingStereoType, testMissingTagValue, testMissingTargetClassinMapping, testMissingSetImp, testMissingClassInDiagram, testMissingClassMapping, testMissingClassMappingWithTargetId, } from './GraphBuildFailureTestData'; import type { Entity } from '../../../models/sdlc/models/entity/Entity'; import { unitTest } from '@finos/legend-studio-shared'; import { getTestEditorStore } from '../../StoreTestUtils'; let editorStore: EditorStore; beforeEach(async () => { editorStore = getTestEditorStore(); }); test(unitTest('Missing super type'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingSuperType as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find supertype 'ui::test1::Organism' of class 'ui::test1::Animal'`, ); }); test(unitTest('Missing profile'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingProfile as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find profile 'ui::test1::ProfileTest'`, ); }); test(unitTest('Missing class property'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingProperty as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find type 'ui::test1::NotFound'`, ); }); test(unitTest('Missing stereotype'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingStereoType as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find stereotype 'missingStereotype' in profile 'ui::meta::pure::profiles::TestProfile'`, ); }); test(unitTest('Missing tagged value'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingTagValue as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find tag 'missingTag' in profile 'ui::meta::pure::profiles::TestProfile'`, ); }); test(unitTest('Missing class in Pure Instance class mapping'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingTargetClassinMapping as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find type 'ui::test1::Target_Something'`, ); }); test(unitTest('Missing class mapping'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingClassMapping as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find any class mapping for class 'ui::Employeer' in mapping 'ui::myMap'`, ); }); test(unitTest('Missing class mapping with ID'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingClassMappingWithTargetId as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find class mapping with ID 'notFound' in mapping 'ui::myMap'`, ); }); // TODO This test is skipped because we don't support include mappings. We don't fail yet // Unskip when include mappings support is added test.skip(unitTest('Missing set implementation'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingSetImp as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find set implementation 'targetClassAMissing'`, ); }); test(unitTest('Missing class in diagram class view'), async () => { const buildGraph = editorStore.graphState.graphManager.buildGraph( editorStore.graphState.graph, testMissingClassInDiagram as Entity[], ); await expect(buildGraph).rejects.toThrowError( `Can't find type 'ui::test1::NotFound'`, ); });
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/model/packageableElements/domain/Package.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { observable, action, makeObservable, override } from 'mobx'; import { CORE_HASH_STRUCTURE, ELEMENT_PATH_DELIMITER, } from '../../../../../MetaModelConst'; import { hashArray, assertTrue, addUniqueEntry, } from '@finos/legend-studio-shared'; import type { Hashable } from '@finos/legend-studio-shared'; import { GraphError } from '../../../../../MetaModelUtils'; import type { PackageableElementVisitor } from '../../../model/packageableElements/PackageableElement'; import { PackageableElement } from '../../../model/packageableElements/PackageableElement'; export const RESERVERD_PACKAGE_NAMES = ['$implicit']; export class Package extends PackageableElement implements Hashable { children: PackageableElement[] = []; constructor(name: string) { super(name); makeObservable(this, { children: observable, addChild: action, addElement: action, hashCode: override, }); } static createPackageFromParent(name: string, parent: Package): Package { assertTrue( !RESERVERD_PACKAGE_NAMES.includes(name), `Can't create package with reserved name '${name}'`, ); const newPackage = new Package(name); newPackage.setPackage(parent); return newPackage; } addChild(value: PackageableElement): void { addUniqueEntry(this.children, value); } addElement(element: PackageableElement): void { this.addChild(element); element.setPackage(this); } get fullPath(): string { if (!this.package) { return ''; } const parentPackageName = this.package.fullPath; return !parentPackageName ? this.name : `${parentPackageName}${ELEMENT_PATH_DELIMITER}${this.name}`; } deleteElement(packageableElement: PackageableElement): void { this.children = this.children.filter( (child) => child !== packageableElement, ); } /** * If package name is a path, continue to recursively traverse the package chain to find the leaf package * NOTE: if we do not allow insertion, error could be thrown if a package in the path is not found */ static getOrCreatePackage( parent: Package, packagePath: string, insert: boolean, ): Package { const index = packagePath.indexOf(ELEMENT_PATH_DELIMITER); const str = index === -1 ? packagePath : packagePath.substring(0, index); let node: Package | undefined; node = parent.children.find( (child: PackageableElement): child is Package => child instanceof Package && child.name === str, ); if (!node) { if (!insert) { throw new GraphError( `Can't find packageable element '${str}' in package '${packagePath}'`, ); } // create the node if it is not in parent package node = Package.createPackageFromParent(str, parent); parent.addChild(node); } if (index !== -1) { return Package.getOrCreatePackage( node, packagePath.substring(index + 2), insert, ); } return node; } override get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.PACKAGE, this.path, hashArray(this.children.map((child) => child.path)), ]); } accept_PackageableElementVisitor<T>( visitor: PackageableElementVisitor<T>, ): T { return visitor.visit_Package(this); } }
nayanika2/legend-studio
packages/legend-studio/src/models/metamodels/pure/action/generation/ImportConfigurationDescription.ts
/** * Copyright (c) 2020-present, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { guaranteeNonNullable } from '@finos/legend-studio-shared'; export enum ImportMode { CODE_IMPORT = 'codeImport', SCHEMA_IMPORT = 'schemaImport', } export const getImportMode = (value: string): ImportMode => guaranteeNonNullable( Object.values(ImportMode).find((mode) => mode === value), `Encountered unsupported import mode '${value}'`, ); export class ImportConfigurationDescription { key!: string; label!: string; modelImportMode!: ImportMode; }
sugarshin/rollup-plugin-assets-replace
src/index.ts
<reponame>sugarshin/rollup-plugin-assets-replace<filename>src/index.ts import { createFilter } from '@rollup/pluginutils'; import type { OutputAsset, OutputChunk, Plugin } from 'rollup'; import type { FilterPattern } from '@rollup/pluginutils'; export type Options = { include?: FilterPattern; exclude?: FilterPattern; map(assetName: string, asset: OutputAsset): OutputAsset; }; export function assetsReplace(options: Options): Plugin { const filter = createFilter(options.include, options.exclude); const { map = identify } = options; return { name: 'assets-replace', generateBundle(_, bundle) { const entries = Object.entries(bundle).filter(onlyAsset); for (const entry of entries) { const assetName = entry[0]; if (!filter(assetName)) { continue; } const result = map(...entry); if (assetName !== result.fileName) { delete bundle[assetName]; } bundle[result.fileName] = result; } }, }; } function identify<T>(_: string, asset: T): T { return asset; } function onlyAsset(entry: [string, OutputAsset | OutputChunk]): entry is [string, OutputAsset] { return isAsset(entry[1]); } function isAsset(output: OutputAsset | OutputChunk): boolean { return output.type === 'asset'; }
sugarshin/rollup-plugin-assets-replace
test/fixtures/bar.d.ts
import { Foo } from '@sugarshin/foo'; import { Bar } from '@sugarshin/bar'; export interface Buz { foo: Foo; bar: Bar; dummy: 'aaa@sugarshin/foo'; dolor: string; }
sugarshin/rollup-plugin-assets-replace
rollup.config.ts
import typescript from '@rollup/plugin-typescript'; const plugins = [typescript()]; export default [ { input: 'src/index.ts', output: { file: 'lib/index.cjs.js', format: 'cjs', }, plugins, }, { input: 'src/index.ts', output: { file: 'lib/index.es.js', format: 'es', }, plugins, }, ];
sugarshin/rollup-plugin-assets-replace
test/index.ts
import fs from 'fs'; import path from 'path'; import test from 'ava'; import { SetRequired } from 'type-fest'; import type { NormalizedOutputOptions, OutputBundle, OutputAsset, PluginContext } from 'rollup'; import { assetsReplace, Options } from '../src'; type AssetsReplacePlugin = SetRequired<ReturnType<typeof assetsReplace>, 'generateBundle'>; const pluginContext = {} as PluginContext; const normalizedOutputOptions = {} as NormalizedOutputOptions; const fixture: OutputBundle = { 'foo.txt': { fileName: 'foo.txt', source: fs.readFileSync(path.resolve(__dirname, './fixtures/foo.txt'), 'utf8'), type: 'asset', isAsset: true, name: undefined, }, 'bar.d.ts': { fileName: 'bar.d.ts', source: fs.readFileSync(path.resolve(__dirname, './fixtures/bar.d.ts'), 'utf8'), type: 'asset', isAsset: true, name: undefined, }, 'other.img': { code: 'code', type: 'chunk', exports: [], facadeModuleId: null, isDynamicEntry: false, isEntry: false, isImplicitEntry: false, modules: {}, name: 'other.img', dynamicImports: [], fileName: 'other.img', implicitlyLoadedBefore: [], importedBindings: {}, imports: [], referencedFiles: [], }, }; test('should be replaced .txt', (t) => { const options: Options = { include: [/\.txt$/], map(_: string, asset: OutputAsset): OutputAsset { if (asset.source instanceof Uint8Array) { return asset; } asset.source = asset.source.replace(/dolor/g, 'replaced'); return asset; }, }; const plugin = assetsReplace(options) as AssetsReplacePlugin; plugin.generateBundle.call(pluginContext, normalizedOutputOptions, fixture, true); t.snapshot(fixture); }); test('should be replaced .d.ts', (t) => { const options: Options = { include: [/\.d\.ts$/], map(_: string, asset: OutputAsset): OutputAsset { if (asset.source instanceof Uint8Array) { return asset; } asset.source = asset.source.replace( /('|"|`)@sugarshin\/([^/'"`])/g, (_, p1, p2) => `${p1}@ins0/sugarshin_${p2}` ); return asset; }, }; const plugin = assetsReplace(options) as AssetsReplacePlugin; plugin.generateBundle.call(pluginContext, normalizedOutputOptions, fixture, true); t.snapshot(fixture); });
wikipathways/wp-super-search
csv-streamify.d.ts
<reponame>wikipathways/wp-super-search declare interface CsvOptions { objectMode: boolean, delimiter: string } declare function csv(csvOptions: CsvOptions): NodeJS.ReadWriteStream; declare module 'csv-streamify' { export = csv; }
wikipathways/wp-super-search
build/xlsx.d.ts
declare interface Utils { sheet_to_json: (input: any) => any } //declare class ReactPivot extends React.Component<any, any> {} declare module 'xlsx' { export function read(data: string, read_opts?: any): any; export function readFile(filename: string, read_opts?: any): any; export const utils: Utils; //export = any; //export default ReactPivot; }
wikipathways/wp-super-search
public/pivot-table-experiments/pivot-pivot.d.ts
declare class ReactPivot extends React.Component<any, any> {} declare module 'pivot-pivot' { export = ReactPivot; }
wikipathways/wp-super-search
public/src/main.tsx
<filename>public/src/main.tsx import { defaults, flatten, forOwn, keys, isEmpty, omit, padStart, toPairs, union, values } from "lodash"; import * as React from "react"; import * as ReactDOM from "react-dom"; import { Observable } from "rxjs/Observable"; import { AjaxRequest } from "rxjs/observable/dom/AjaxObservable"; import "rxjs/add/observable/dom/ajax"; import "rxjs/add/operator/do"; import "rxjs/add/operator/let"; import "rxjs/add/operator/map"; import MuiThemeProvider from "material-ui/styles/MuiThemeProvider"; import TextField from "material-ui/TextField"; //import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton'; //import FlatButton from 'material-ui/FlatButton'; import RaisedButton from "material-ui/RaisedButton"; import * as queryString from "query-string"; import StarterDataTable from "material-ui-datatables"; import { DataTable, Column } from "./DataTable"; import { TargetHighlighter } from "./TargetHighlighter"; import { autorun, computed, observable, IObservableArray, toJS } from "mobx"; import { observer } from "mobx-react"; import { fromStream } from "mobx-utils"; import { multiSort } from "./sort"; const geneToPathways = require("../../build/gene-to-pathways.json"); //const miRNAToTargets = require("../../build/miRNA-to-targets.json"); const miRNAToTargets = require("../../build/inputs-to-targets.json"); const pathwayDetails = require("../../build/pathway-details.json"); // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 import * as injectTapEventPlugin from "react-tap-event-plugin"; injectTapEventPlugin(); const SAMPLE_ID_TO_LABEL_MAPPING = { "10768": "AHCYL1", "10797": "MTHFD2", "1491": "CTH", "1719": "DHFR", //"1719": "MTHFD1L", "1786": "DNMT1", "1788": "DNMT3A", "1789": "DNMT3B", "191": "AHCY", "200895": "DHFRL1", "23382": "AHCYL2", "25902": "MTHFD1L", "26227": "PHGDH", "2729": "GCLC", "2730": "GCLM", "27430": "MAT2B", "275": "AMT", "2937": "GSS", "29947": "DNMT3L", "29968": "PSAT1", "4143": "MAT1A", "4144": "MAT2A", "441024": "MTHFD2L", "4522": "MTHFD1", "4524": "MTHFR", "4548": "MTR", "5723": "PSPH", "635": "BHMT", "6470": "SHMT1", "6472": "SHMT2", "7298": "TYMS", "875": "CBS", "998": "CDC42", "9855": "FARP2", "9564": "BCAR1", "9475": "ROCK2", "896": "CCND3", "894": "CCND2", "8711": "TNK1", "87": "ACTN1", "859": "CAV3", "858": "CAV2", "857": "CAV1", "85366": "MYLK2", "8516": "ITGA8", "8515": "ITGA10", "829662": "PIP3", "823": "CAPN1", "80310": "PDGFD", "7791": "ZYX", "7450": "VWF", "7448": "VTN", "7424": "VEGFC", "7423": "VEGFB", "7422": "VEGF", "7414": "VCL", "7409": "VAV1", "7408": "VASP", "7294": "TXK", "7148": "TNXB", "7143": "TNR", "71": "ACTG1", "7094": "TLN1", "7060": "THBS4", "7059": "THBS3", "7058": "THBS2", "7057": "THBS1", "673": "BRAF", "6725": "SRMS", "6714": "SRC", "6696": "SPP1", "6654": "SOS1", "6464": "SHC1", "6414": "SEPP1", "640": "BLK", "63923": "TNN", "6300": "MAPK12", "6093": "ROCK1", "60": "ACTB", "596": "BCL2", "595": "CCND1", "5908": "RAP1B", "5906": "RAP1A", "5894": "RAF1", "5881": "RAC3", "5880": "RAC2", "5879": "RAC1", "5829": "PXN", "5753": "PTK6", "5747": "PTK2", "5728": "PTEN", "572": "BAD", "57144": "PAK7", "56924": "PAK6", "5649": "RELN", "5608": "MAP2K6", "5607": "MAP2K5", "5606": "MAP2K3", "5605": "MAP2K2", "5604": "MAP2K1", "56034": "PDGFC", "5601": "MAPK9", "5599": "MAPK8", "5598": "MAPK7", "5597": "MAPK6", "5596": "MAPK4", "5594": "MAPK1", "55359": "STYK1", "53918": "PELO", "53358": "SHC3", "5296": "PIK3R2", "5295": "PIK3R1", "5294": "PIK3CG", "5293": "PIK3CD", "5291": "PIK3CB", "5290": "PIK3CA", "5228": "PGF", "5170": "PDPK1", "5159": "PDGFRB", "5156": "PDGFRA", "5155": "PDGFB", "5154": "PDGFA", "5063": "PAK3", "5062": "PAK2", "5058": "PAK1", "50509": "COL5A3", "4659": "PPP1R12A", "4638": "MYLK", "4637": "MYL6", "4233": "MET", "394": "ARHGAP5", "3918": "LAMC2", "3915": "LAMC1", "3914": "LAMB3", "3913": "LAMB2", "3912": "LAMB1", "3911": "LAMA5", "3910": "LAMA4", "3909": "LAMA3", "3908": "LAMA2", "388": "RHOB", "387": "RHOA", "3791": "KDR", "3725": "JUN", "3696": "ITGB8", "3695": "ITGB7", "3694": "ITGB6", "3693": "ITGB5", "3691": "ITGB4", "3690": "ITGB3", "369": "ARAF", "3689": "ITGB2", "3688": "ITGB1", "3687": "ITGAX", "3685": "ITGAV", "3684": "ITGAM", "3683": "ITGAL", "3682": "ITGAE", "3681": "ITGAD", "3680": "ITGA9", "3679": "ITGA7", "3678": "ITGA5", "3676": "ITGA4", "3675": "ITGA3", "3674": "ITGA2B", "3673": "ITGA2", "3655": "ITGA6", "3611": "ILK", "3480": "IGF1R", "3479": "IGF1", "3381": "IBSP", "3371": "TNC", "331": "BIRC4", "330": "BIRC3", "329": "BIRC2", "3265": "Ha-Ras", "30849": "PIK3R4", "3082": "HGF", "3055": "HCK", "29780": "PARVB", "2932": "GSK3B", "2889": "RAPGEF1", "2885": "GRB2", "284217": "LAMA1", "2534": "FYN", "23533": "PIK3R5", "23396": "PIP5K1C", "2335": "FN1", "2321": "FLT1", "2316": "FLNA", "22801": "ITGA11", "2277": "FIGF", "2268": "FGR", "208": "AKT2", "207": "AKT1", "2064": "ERBB2", "2002": "ELK1", "1956": "EGFR", "1950": "EGF", "1793": "DOCK1", "1729": "Diap1", "1499": "Catnb", "1398": "CRK", "1311": "COMP", "1302": "COL11A2", "1301": "COL11A1", "1292": "COL6A2", "1290": "COL5A2", "1289": "COL5A1", "1288": "COL4A6", "1286": "COL4A4", "1284": "COL4A2", "1282": "COL4A1", "1281": "COL3A1", "1280": "COL2A1", "1278": "COL1A2", "1277": "COL1A1", "1101": "CHAD", "10420": "TESK2", "10319": "LAMC3", "10298": "PAK4", "10188": "TNK2", "10000": "AKT3" }; const styles = { block: { maxWidth: 250 }, radioButton: { marginBottom: 16 } }; class PathwayStore { id = Math.random(); @observable elements = []; @observable organism = ""; @observable name = ""; } export class PathwayFinderStore { id = Math.random(); @observable customStyle: any; @observable database: string; @observable identifiers: string[]; @observable pvjson: any; @observable columns: IObservableArray<Column>; @observable selectedPathway: any; @observable labels: string[] = []; @observable targetHighlighterSelected: any; constructor({ id, customStyle = {} }) { this.customStyle = customStyle; const parsedQS = queryString.parse(location.search); if (!isEmpty(parsedQS)) { const identifiers = (this.identifiers = ( parsedQS.identifiers || "" ).split(",")); this.database = parsedQS.database; } this.columns = observable([ { /* key: 'pathway', label: 'ID', sortable: false, style: { width: '30px', }, }, { //*/ key: "pathwayName", label: "Pathway Name", sortable: true }, { key: "miRNACount", label: "input Count", sortable: true, style: { width: "100px" } }, { key: "targetCount", label: "Target Count", sortable: true, style: { width: "100px" } } ]); this.pvjson = new PathwayStore(); //autorun(() => console.log(this.data)); } @computed get pathwaysMiRNAsTargets() { return this.identifiers.reduce(function(acc, identifier) { const targets = miRNAToTargets[identifier]; if (!!targets) { targets.forEach(function(target) { const pathways = geneToPathways[target]; if (!!pathways) { pathways.forEach(function(pathway) { acc[pathway] = acc[pathway] || {}; acc[pathway][identifier] = acc[pathway][identifier] || []; acc[pathway][identifier] = union(acc[pathway][identifier], [ target ]); }); } }); } return acc; }, {}); } @computed get data() { return ( toPairs(this.pathwaysMiRNAsTargets) .map(function([pathway, pathwayItems]) { const targetGroups = values(pathwayItems); return { pathway: pathway, pathwayName: pathwayDetails[pathway], miRNACount: targetGroups.length, targetCount: flatten(targetGroups).length }; }) // TODO should this be handled by the DataTable initialSort property instead? .sort( multiSort.bind(undefined, [ { key: "miRNACount", direction: "asc" }, { key: "targetCount", direction: "asc" }, { key: "pathway", direction: "asc" } ]) ) ); } @computed get targetHighlighterData() { const { pathwaysMiRNAsTargets, selectedPathway } = this; const pathwayItems = pathwaysMiRNAsTargets[selectedPathway]; return toPairs(pathwayItems).map(function([key, value]) { return { id: key, children: value }; }); } } @observer class PathwayFinder extends React.Component<any, any> { store: any; constructor(props) { super(props); this.store = new PathwayFinderStore(props); this.state = { identifiers: this.store.identifiers }; } handleRowSelection = selectedItems => { this.store.selectedPathway = selectedItems[0].pathway; }; handleIdentifiersInputChange = (event, newValue) => { // TODO should we use Rx Observable with debounce? this.setState({ identifiers: newValue.split("\n").filter(x => x !== "") }); }; submitQuery = () => { this.store.identifiers = this.state.identifiers; }; handleControlClick = item => { // TODO fix this by using new Pvjs this.store.labels = item.children.map(c => SAMPLE_ID_TO_LABEL_MAPPING[c]); this.store.genes = item.children.reduce((acc, c) => { return acc.concat(c); }, []); this.store.targetHighlighterSelected = item.id; }; render() { let that = this; const state = that.state; const store = that.store; const { columns, data, targetHighlighterData, pvjson, id, identifiers, customStyle, targetHighlighterSelected, selectedPathway, labels, genes = [] } = store; const labelAttribute = labels.map(l => `&label[]=${l}`).join(""); const xrefAttribute = genes .map(gene => `&xref[]=${gene},Entrez Gene`) .join(""); return ( <MuiThemeProvider> <div> <div style={{ display: "flex", flexFlow: "row" }} > {/* // we only have one identifier at present, so this isn't needed <RadioButtonGroup name="inputType" defaultSelected="mirtarbase"> <RadioButton value="mirtarbase" label="mirtarbase" style={styles.radioButton} /> <RadioButton value="ncbigene" label="Entrez Gene" style={styles.radioButton} /> </RadioButtonGroup> */} <div style={{ display: "flex", flexFlow: "column wrap" }} > <TextField hintText="Enter your inputs, one per line, e.g, hsa-miR-21-5p &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hsa-miR-20a-5p" multiLine={true} rows={20} rowsMax={100} inputStyle={{ backgroundColor: "#efefef" }} floatingLabelText="Inputs (one per line)" onChange={this.handleIdentifiersInputChange} defaultValue={ !isEmpty(identifiers) ? identifiers.join("\n") : null } /> <RaisedButton style={{ marginTop: "8px", marginBottom: "8px" }} onClick={this.submitQuery} label="Search" /> </div> {!data ? null : ( <DataTable columns={toJS(columns)} data={data} selectable={true} showCheckboxes={false} showRowHover={true} handleRowSelection={this.handleRowSelection} /> )} </div> {!data ? null : ( <div style={{ display: "flex", flexFlow: "row" }} > {!selectedPathway ? null : ( <iframe src={`https://www.wikipathways.org/wpi/PathwayWidget.php?id=${selectedPathway}${xrefAttribute}&colors=red`} width="800px" height="400px" style={{ overflow: "hidden" }} /> )} {!!targetHighlighterData ? ( <TargetHighlighter data={targetHighlighterData} onControlClick={this.handleControlClick} selected={targetHighlighterSelected} /> ) : null} </div> )} </div> </MuiThemeProvider> ); } } export default PathwayFinder;
wikipathways/wp-super-search
build/src/build-hash.ts
<filename>build/src/build-hash.ts /// <reference path="../../csv-streamify.d.ts" /> /// <reference path="../xlsx.d.ts" /> // tsc --project tsconfig.build-hash.json && node ./build-hash.js declare global { // Augment Node.js `global` namespace NodeJS { interface Global { XMLHttpRequest: XMLHttpRequest; } } // Augment Browser `window` //interface Window extends NodeJS.Global { } // Augment Web Worker `self` //interface WorkerGlobalScope extends NodeJS.Global { } } if (!global.hasOwnProperty("XMLHttpRequest")) { global.XMLHttpRequest = require("xhr2"); } import * as fs from "fs"; import { keys, toPairs, union } from "lodash"; const csv = require("csv-streamify"); import * as XLSX from "xlsx"; import { Observable } from "rxjs/Observable"; import { AjaxRequest } from "rxjs/observable/dom/AjaxObservable"; import "rxjs/add/observable/dom/ajax"; import "rxjs/add/observable/bindNodeCallback"; import "rxjs/add/observable/concat"; import "rxjs/add/observable/merge"; import "rxjs/add/observable/from"; import "rxjs/add/observable/pairs"; import "rxjs/add/operator/do"; import "rxjs/add/operator/let"; import "rxjs/add/operator/map"; import "rxjs/add/operator/mergeAll"; import "rxjs/add/operator/mergeMap"; import "rxjs/add/operator/reduce"; import "rxjs/add/operator/shareReplay"; import "rxjs/add/operator/toArray"; import "rx-extra/add/operator/throughNodeStream"; const fileExists = require("file-exists"); const JSONStream = require("JSONStream"); const path = require("path"); /***************** * Inputs ***************/ const ORGANISMS = ["Homo sapiens", "Mus musculus"]; const KINASE_TARGETS = path.resolve(__dirname, "../PF_I2T_Kinases.tsv"); const MIRTARBASE_MTI_URL = "http://mirtarbase.mbc.nctu.edu.tw/cache/download/7.0/miRTarBase_MTI.xlsx"; const GMT_HUMAN_URL = "http://data.wikipathways.org/current/gmt/wikipathways-20180210-gmt-Homo_sapiens.gmt"; const GMT_MOUSE_URL = "http://data.wikipathways.org/current/gmt/wikipathways-20180210-gmt-Mus_musculus.gmt"; /***************** * Outputs ***************/ const MIRTARBASE_MTI_FILEPATH = path.resolve( __dirname, "../miRTarBase_MTI_7.0.xlsx" ); const GMT_FILEPATH = path.resolve(__dirname, "../gmt.json"); const MIRNA_TO_TARGETS_FILEPATH = path.resolve( __dirname, "../miRNA-to-targets.json" ); const GENE_TO_PATHWAYS_FILEPATH = path.resolve( __dirname, "../gene-to-pathways.json" ); const PATHWAY_DETAILS_FILEPATH = path.resolve( __dirname, "../pathway-details.json" ); const INPUTS_TO_TARGETS_FILEPATH = path.resolve( __dirname, "../inputs-to-targets.json" ); const CSV_OPTIONS = { objectMode: true, delimiter: "\t", columns: true, newline: "\r\n" }; // TODO improve this to be more specify than "any" // TODO move this into rx-extra declare module "rxjs/Observable" { interface Observable<T> { toNodeStream: any; } } Observable.prototype.toNodeStream = function(stream) { const obs = this; obs.subscribe( function(x) { stream.write(x); }, function(err) { console.error("err"); console.error(err); //stream.error(err); }, function() { stream.end(); } ); }; let miRNAToTargetsSource; if (!fileExists.sync(MIRNA_TO_TARGETS_FILEPATH)) { let miRTarBase_MTISource; if (fileExists.sync(MIRTARBASE_MTI_FILEPATH)) { miRTarBase_MTISource = Observable.bindNodeCallback(function(fp, cb) { fs.readFile(fp, cb); })(MIRTARBASE_MTI_FILEPATH); } else { const ajaxRequest: AjaxRequest = { url: MIRTARBASE_MTI_URL, method: "GET", responseType: "arraybuffer", timeout: 1 * 1000, // ms crossDomain: true }; miRTarBase_MTISource = Observable.ajax(ajaxRequest) .map((ajaxResponse): Buffer => Buffer.from(ajaxResponse.xhr.response)) .toArray() .map(function(buffers) { return Buffer.concat(buffers); }) .shareReplay(); // cache spreadsheet so we don't have to download it again miRTarBase_MTISource.toNodeStream( fs.createWriteStream(MIRTARBASE_MTI_FILEPATH) ); } miRNAToTargetsSource = miRTarBase_MTISource .toArray() .map(function(buffers) { return Buffer.concat(buffers); }) .map(function(buffer) { /* Call XLSX */ return XLSX.read(buffer, { type: "buffer", cellFormula: false, cellHTML: false, cellStyles: false }); }) .mergeMap(function(workbook) { const sheetName = workbook.SheetNames[0]; const workSheet = workbook.Sheets[sheetName]; return Observable.from( XLSX.utils .sheet_to_json(workSheet) // only include "Functional MTI", not // "Functional MTI (Weak)", "Non-Functional MTI" or "Non-Functional MTI (Weak)" .filter(row => row["Support Type"] === "Functional MTI") .map(row => ({ organism: row["Species (miRNA)"], miRNA: row.miRNA, target: row["Target Gene (Entrez ID)"] })) .filter(x => ORGANISMS.indexOf(x.organism) > -1) ); }) .shareReplay(); const stringifyMiRNATargets = JSONStream.stringify(); miRNAToTargetsSource .throughNodeStream(stringifyMiRNATargets) .toNodeStream(fs.createWriteStream(MIRNA_TO_TARGETS_FILEPATH)); } else { miRNAToTargetsSource = Observable.bindNodeCallback(function(fp, options, cb) { fs.readFile(fp, options, cb); })(MIRNA_TO_TARGETS_FILEPATH, "utf8").throughNodeStream( JSONStream.parse("*") ); } const kinaseToTargetSource = Observable.bindNodeCallback(function( fp, options, cb ) { fs.readFile(fp, options, cb); })(KINASE_TARGETS, "utf8") .throughNodeStream(csv(CSV_OPTIONS)) .map(function({ input, target }) { return { miRNA: input, target }; }); const stringifyInputsToTargets = JSONStream.stringifyObject(); Observable.merge(kinaseToTargetSource, miRNAToTargetsSource) .reduce(function(acc: any, { miRNA, target }) { const targets = (acc[miRNA] = acc[miRNA] || []); if (targets.indexOf(target) === -1) { targets.push(target); } return acc; }, {}) .mergeMap(function(x) { return Observable.from(toPairs(x)); }) .throughNodeStream(stringifyInputsToTargets) .toNodeStream(fs.createWriteStream(INPUTS_TO_TARGETS_FILEPATH)); let gmtSource; if (fileExists.sync(GMT_FILEPATH)) { gmtSource = Observable.bindNodeCallback(function(fp, options, cb) { fs.readFile(fp, options, cb); })(GMT_FILEPATH, "utf8").throughNodeStream(JSONStream.parse("*")); } else { const ajaxRequestHuman: AjaxRequest = { url: GMT_HUMAN_URL, method: "GET", responseType: "text", timeout: 1 * 1000, // ms crossDomain: true }; const ajaxRequestMouse: AjaxRequest = { url: GMT_MOUSE_URL, method: "GET", responseType: "text", timeout: 1 * 1000, // ms crossDomain: true }; gmtSource = Observable.concat( Observable.ajax(ajaxRequestHuman).map( (ajaxResponse): string => ajaxResponse.xhr.responseText ), Observable.ajax(ajaxRequestMouse).map( (ajaxResponse): string => ajaxResponse.xhr.responseText ) ) .reduce( function(acc: { lines: string[]; rem: string }, text: string) { let { lines, rem } = acc; const splitByNewline = (rem + text).split("\n"); splitByNewline .splice(0, splitByNewline.length - 1) .forEach(function(line) { lines.push(line); }); acc.rem = splitByNewline[0]; return acc; }, { lines: [], rem: "" } ) .mergeMap(x => Observable.from(x.lines)) .map(function(line) { const [title, date, identifier, rest] = line.split("%"); const [organism, id, ...genes] = rest.split("\t"); return { title, date, identifier, organism, id, genes }; }); const stringifyGMT = JSONStream.stringify(); gmtSource .throughNodeStream(stringifyGMT) .toNodeStream(fs.createWriteStream(GMT_FILEPATH)); /* .subscribe(function(gmt, i) { if (i === 0) { fs.writeFileSync(GMT_FILEPATH, gmt); } else { fs.appendFileSync(GMT_FILEPATH, gmt); } }) //*/ } const stringifyPathwayDetails = JSONStream.stringifyObject(); gmtSource .reduce(function( acc, { title, date, identifier, organism, id, genes }: { title: string; date: string; identifier: string; organism: string; id: string; genes: string[]; } ) { acc[identifier] = title; return acc; }, {}) .mergeMap(function(x) { return Observable.from(toPairs(x)); }) .throughNodeStream(stringifyPathwayDetails) .toNodeStream(fs.createWriteStream(PATHWAY_DETAILS_FILEPATH)); const stringifyGeneToPathways = JSONStream.stringifyObject(); gmtSource .map(function({ title, date, identifier, organism, id, genes }) { return { pathway: identifier, genes }; }) .reduce(function(acc, x: { pathway: string; genes: string[] }) { const pathway = x.pathway; x.genes.forEach(function(gene) { let genes = (acc[gene] = acc[gene] || []); genes.push(pathway); }); return acc; }, {}) .mergeMap(function(x) { return Observable.from(toPairs(x)); }) .throughNodeStream(stringifyGeneToPathways) .toNodeStream(fs.createWriteStream(GENE_TO_PATHWAYS_FILEPATH));
wikipathways/wp-super-search
public/src/sort.ts
export type Direction = "asc" | "desc"; export interface SortCriterion { key: string; direction: Direction; } export function singleSort(direction: Direction, a, b) { if (a < b) { return direction === "asc" ? 1 : -1; } else if (a > b) { return direction === "asc" ? -1 : 1; } else { return 0; } } export function multiSort(sortCriteria: SortCriterion[], a, b) { return sortCriteria.reduce(function(acc, { key, direction }) { return acc !== 0 ? acc : singleSort(direction, a[key], b[key]); }, 0); }
wikipathways/wp-super-search
public/test/demo.tsx
<filename>public/test/demo.tsx<gh_stars>1-10 // NOTE: mock-server must be started before running this. import * as React from 'react'; import * as ReactDOM from 'react-dom'; import {values} from 'lodash'; import PathwayFinder from '../src/main'; // React says not to render directly into document.body, so here's a container. var container = document.querySelector('#pathway-finder-container'); if (!container) { container = document.createElement('div'); container.setAttribute('width', '100%'); container.setAttribute('height', '1000px'); document.body.appendChild(container) } const customStyle = ` .background { fill: white; } .shadow { filter: drop-shadow( 2px 2px 2px #000 ); /* Same syntax as box-shadow */ -webkit-filter: drop-shadow( 2px 2px 2px #000 ); } text { font-size: 14px; pointer-events: none; font-family: Arial, Helvetica, sans-serif; } .InfoBox { fill: #444; } .citation { fill: gray; font-size: 10px; } .InfoBox .citation { font-size: 0px; } .CellularComponent { stroke: #808080; stroke-width:3; fill: #fff; } .Cell { stroke: #808080; stroke-width:3; fill: #fff; } .DataNode .shapeType { clip-path: url(#rounded-rectangle); fill: #518569; } .DataNode .textlabel { fill: #fff; } .Rna .shapeType { fill: #9453A7; } .Metabolite .shapeType { fill: #0059b3; clip-path: none; } .Pathway .shapeType { fill: white; clip-path: none; } .Pathway .textlabel { fill: #75C95C; } .Group-Complex { fill: #B4B464; fill-opacity: 0.1; stroke: #808080; } .Group-None { fill: #B4B464; fill-opacity: 0.1; stroke: #808080; } .Group-Pathway { fill: #008000; fill-opacity: 0.05; stroke: #808080; } .Interaction { stroke: #000000; } .Inhibition { stroke: red; stroke-width: 1.3; } `; // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript function getParameterByName(name, url?) { if (!url) { url = window.location.href; } name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } const id = getParameterByName('id') || 'WP554'; ReactDOM.render( <PathwayFinder id={'wikipathways:' + id} customStyle={customStyle} bridgedbBaseUrl="http://localhost:9000" />, container );
wikipathways/wp-super-search
public/src/App.tsx
<filename>public/src/App.tsx<gh_stars>1-10 import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { connect, Provider } from 'react-redux'; import {store} from './store'; let App = ({ isPinging, ping }) => ( <div> <h1>is pinging: {isPinging.toString()}</h1> <button onClick={ping}>Start PING</button> </div> ); const PING = 'PING'; const ping = () => ({ type: PING }); App = connect( ({ isPinging }) => ({ isPinging }), { ping } )(App); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
wikipathways/wp-super-search
public/src/DataTable.tsx
<reponame>wikipathways/wp-super-search<gh_stars>1-10 import { defaults, forOwn } from "lodash"; import * as React from "react"; import * as ReactDOM from "react-dom"; // TODO should we use the theme provider here? //import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import StarterDataTable from "material-ui-datatables"; import { multiSort } from "./sort"; export interface Column { key: string; label: string; sortable?: boolean; // TODO add the rest } export class DataTable extends React.Component<any, any> { constructor(props) { super(props); this.state = defaults( { sortCriteria: [], // TODO showRowSizeControls cannot currently be disabled. Below does not work: //showRowSizeControls: false, onRowSizeChange: this.handleOnRowSizeChange, rowSize: 10, rowSizeList: [10, 30, 50, 100], onNextPageClick: this.handleNextPageClick, onPreviousPageClick: this.handlePreviousPageClick, onSortOrderChange: this.handleSortOrderChange }, props, { selectedRows: [0], height: "auto", onCellClick: this.handleCellClick, onRowSelection: this.handleRowSelection, page: 1 } ); } componentDidMount() { const { selectedRows } = this.state; this.handleRowSelection(selectedRows); }; componentWillReceiveProps(nextProps) { const that = this; const prevProps = this.props; const propsToUpdate = ["data", "count"]; forOwn(nextProps, function(prop, key) { if (propsToUpdate.indexOf(key) > -1) { that.setState({ [key]: prop }); } }); }; handleOnRowSizeChange = rowSizeListIndex => { const { rowSizeList } = this.state; this.setState({ rowSize: rowSizeList[rowSizeListIndex] }); }; handleSortOrderChange = (key, direction) => { const { data, sortCriteria } = this.state; const newSortCriteria = [{ key, direction }].concat( sortCriteria.filter(so => so.key !== key) ); // Can we just sort the data here, or do we // need to pass this change up to the parent // instead or in addition? this.setState({ data: this.state.data.sort(multiSort.bind(undefined, newSortCriteria)), sortCriteria: newSortCriteria }); }; handleFilterValueChange = value => { //console.log('filter value: ' + value); }; handleCellClick = (rowIndex, columnIndex, row, column) => { //console.log('selectedCell:'); //console.log('DataTable: rowIndex: ' + rowIndex + ' columnIndex: ' + columnIndex); }; handleCellDoubleClick = (rowIndex, columnIndex, row, column) => { //console.log('rowIndex: ' + rowIndex + ' columnIndex: ' + columnIndex); }; handleRowSelection = (selectedRows: number[]) => { const { props, state } = this; const { data, page, rowSize } = state; // NOTE // page: 1-based // rows: 0-based this.setState({ selectedRows: selectedRows }); // TODO: this.handleRowSelection is for multiple rows, // but props.handleRowSelection is for just one. // How to best handle this mismatch? const selectedRow = selectedRows[0]; if (props.hasOwnProperty("handleRowSelection")) { props.handleRowSelection( selectedRows.map( rowIndex => this.state.data[(page - 1) * rowSize + rowIndex] ) ); } }; handlePreviousPageClick = () => { const { count, data, page, rowSize } = this.state; const newPage = Math.max(page - 1, 1); this.setState({ page: newPage }); }; handleNextPageClick = () => { const { count, data, page, rowSize } = this.state; const lastPage = Math.ceil((count || data.length) / rowSize); const newPage = Math.min(page + 1, lastPage); this.setState({ page: newPage }); }; render() { const props = this.props; const state = this.state; const { data, page, rowSize } = state; const pageData = data.slice((page - 1) * rowSize, page * rowSize); const starterDataTableProps = defaults( { data: pageData, count: data.length }, state ); return <StarterDataTable {...starterDataTableProps} />; } }
wikipathways/wp-super-search
public/pivot-table-experiments/react-pivot.d.ts
declare class ReactPivot extends React.Component<any, any> {} declare module 'react-pivot' { export = ReactPivot; //export default ReactPivot; }
wikipathways/wp-super-search
public/src/TargetHighlighter.tsx
<reponame>wikipathways/wp-super-search import { defaults, forOwn } from "lodash"; import * as React from "react"; import * as ReactDOM from "react-dom"; import Subheader from "material-ui/Subheader"; import RaisedButton from "material-ui/RaisedButton"; /** * Show/hide targets of specified miRNAs. */ export class TargetHighlighter extends React.Component<any, any> { styles: any; data: any; constructor(props) { super(props); this.styles = { buttons: { margin: 4 }, wrapper: { display: "flex", flexFlow: "column wrap" } }; } handleClick = item => { const props = this.props; props.onControlClick(item); }; renderButton(item) { const { selected } = this.props; return ( <RaisedButton key={item.id} style={this.styles.buttons} label={item.id} primary={item.id === selected} onClick={this.handleClick.bind(this, item)} /> ); } render() { const { data } = this.props; return ( <div style={this.styles.wrapper}> <Subheader>Select to highlight target(s)</Subheader> {data.map(this.renderButton, this)} </div> ); } }
wikipathways/wp-super-search
public/src/store.ts
<filename>public/src/store.ts import { createStore, applyMiddleware } from 'redux'; import { createEpicMiddleware } from 'redux-observable'; const PING = 'PING'; const PONG = 'PONG'; const pingEpic = action$ => action$.ofType(PING) .delay(1000) // Asynchronously wait 1000ms then continue .mapTo({ type: PONG }); const pingReducer = (state = { isPinging: false }, action) => { switch (action.type) { case PING: return { isPinging: true }; case PONG: return { isPinging: false }; default: return state; } }; const epicMiddleware = createEpicMiddleware(pingEpic); export const store = createStore(pingReducer, applyMiddleware(epicMiddleware) );
pouyakary/TypeScript
src/lib/es2020.intl.d.ts
<reponame>pouyakary/TypeScript declare namespace Intl { /** * [BCP 47 language tag](http://tools.ietf.org/html/rfc5646) definition. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). * * [Wikipedia](https://en.wikipedia.org/wiki/IETF_language_tag). */ type BCP47LanguageTag = string; /** * Unit to use in the relative time internationalized message. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format#Parameters). * * [Specification](https://tc39.es/ecma402/#sec-singularrelativetimeunit). */ type RelativeTimeFormatUnit = | "year" | "years" | "quarter" | "quarters" | "month" | "months" | "week" | "weeks" | "day" | "days" | "hour" | "hours" | "minute" | "minutes" | "second" | "seconds" ; /** * The locale matching algorithm to use. * * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). * * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat). */ type RelativeTimeFormatLocaleMatcher = "lookup" | "best fit"; /** * The format of output message. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). * * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat). */ type RelativeTimeFormatNumeric = "always" | "auto"; /** * The length of the internationalized message. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). * * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat). */ type RelativeTimeFormatStyle = "long" | "short" | "narrow"; /** * Unicode Calendar Identifier * * [Reference](http://unicode.org/reports/tr35/#UnicodeCalendarIdentifier) * * [Source](https://github.com/unicode-org/cldr/blob/b805d0b/common/bcp47/calendar.xml) */ type Calendar = // Thai Buddhist calendar | "buddhist" // Traditional Chinese calendar | "chinese" // Coptic calendar | "coptic" // Traditional Korean calendar | "dangi" // Ethiopic calendar, Amete Alem (epoch approx. 5493 B.C.E) | "ethiopic-amete-alem" | "ethioaa" // Ethiopic calendar, Amete Mihret (epoch approx, 8 C.E.) | "ethiopic" // Gregorian calendar | "gregorian" // Gregorian calendar (alias) | "gregory" // Traditional Hebrew calendar | "hebrew" // Indian calendar | "indian" // Islamic calendar | "islamic" // Islamic calendar, Umm al-Qura | "islamic-umalqura" // Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch) | "islamic-tbla" // Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch) | "islamic-civil" | "islamicc" // Deprecated alias // Islamic calendar, Saudi Arabia sighting | "islamic-rgsa" // ISO calendar (Gregorian calendar using the ISO 8601 calendar week rules) | "iso8601" // Japanese Imperial calendar | "japanese" // Persian calendar | "persian" // Republic of China calendar | "roc" ; /** * Unicode Number System Identifier * * [Reference](http://unicode.org/reports/tr35/#UnicodeNumberSystemIdentifier) * * [Source](https://github.com/unicode-org/cldr/blob/be7a953/common/bcp47/number.xml) */ type NumberingSystem = // Adlam digits | "adlm" // Ahom digits | "ahom" // Arabic-Indic digits | "arab" // Extended Arabic-Indic digits | "arabext" // Armenian upper case numerals — algorithmic | "armn" // Armenian lower case numerals — algorithmic | "armnlow" // Balinese digits | "bali" // Bengali digits | "beng" // Bhaiksuki digits | "bhks" // Brahmi digits | "brah" // Chakma digits | "cakm" // Cham digits | "cham" // Cyrillic numerals — algorithmic | "cyrl" // Devanagari digits | "deva" // Dives Akuru digits | "diak" // Ethiopic numerals — algorithmic | "ethi" // Financial numerals — may be algorithmic | "finance" // Full width digits | "fullwide" // Georgian numerals — algorithmic | "geor" // Gunjala Gondi digits | "gong" // Masaram Gondi digits | "gonm" // Greek upper case numerals — algorithmic | "grek" // Greek lower case numerals — algorithmic | "greklow" // Gujarati digits | "gujr" // Gurmukhi digits | "guru" // Han-character day-of-month numbering for lunar/other traditional calendars" | "hanidays" // Positional decimal system using Chinese number ideographs as digits | "hanidec" // Simplified Chinese numerals — algorithmic | "hans" // Simplified Chinese financial numerals — algorithmic | "hansfin" // Traditional Chinese numerals — algorithmic | "hant" // Traditional Chinese financial numerals — algorithmic | "hantfin" // Hebrew numerals — algorithmic | "hebr" // Pahawh Hmong digits | "hmng" // Nyiakeng Puachue Hmong digits | "hmnp" // Javanese digits | "java" // Japanese numerals — algorithmic | "jpan" // Japanese financial numerals — algorithmic | "jpanfin" // Japanese first-year Gannen numbering for Japanese calendar | "jpanyear" // Kayah Li digits | "kali" // Khmer digits | "khmr" // Kannada digits | "knda" // Tai Tham Hora (secular) digits | "lana" // Tai Tham Tham (ecclesiastical) digits | "lanatham" // Lao digits | "laoo" // Latin digits | "latn" // Lepcha digits | "lepc" // Limbu digits | "limb" // Mathematical bold digits | "mathbold" // Mathematical double-struck digits | "mathdbl" // Mathematical monospace digits | "mathmono" // Mathematical sans-serif bold digits | "mathsanb" // Mathematical sans-serif digits | "mathsans" // Malayalam digits | "mlym" // Modi digits | "modi" // Mongolian digits | "mong" // Mro digits | "mroo" // Meetei Mayek digits | "mtei" // Myanmar digits | "mymr" // Myanmar Shan digits | "mymrshan" // Myanmar Tai Laing digits | "mymrtlng" // Native digits | "native" // Newa digits | "newa" // N'Ko digits | "nkoo" // Ol Chiki digits | "olck" // Oriya digits | "orya" // Osmanya digits | "osma" // Hanifi Rohingya digits | "rohg" // Roman upper case numerals — algorithmic | "roman" // Roman lowercase numerals — algorithmic | "romanlow" // Saurashtra digits | "saur" // Sharada digits | "shrd" // Khudawadi digits | "sind" // Sinhala Lith digits | "sinh" // Sora_Sompeng digits | "sora" // Sundanese digits | "sund" // Takri digits | "takr" // New Tai Lue digits | "talu" // Tamil numerals — algorithmic | "taml" // Modern Tamil decimal digits | "tamldec" // Telugu digits | "telu" // Thai digits | "thai" // Tirhuta digits | "tirh" // Tibetan digits | "tibt" // Traditional numerals — may be algorithmic | "traditional" | "traditio" // Vai digits | "vaii" // Warang Citi digits | "wara" // Wancho digits | "wcho" ; /** * An object with some or all of properties of `options` parameter * of `Intl.RelativeTimeFormat` constructor. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). * * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat). */ interface RelativeTimeFormatOptions { localeMatcher?: RelativeTimeFormatLocaleMatcher; numeric?: RelativeTimeFormatNumeric; style?: RelativeTimeFormatStyle; } /** * An object with properties reflecting the locale * and formatting options computed during initialization * of the `Intel.RelativeTimeFormat` object * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions#Description). * * [Specification](https://tc39.es/ecma402/#table-relativetimeformat-resolvedoptions-properties) */ interface ResolvedRelativeTimeFormatOptions { locale: BCP47LanguageTag; style: RelativeTimeFormatStyle; numeric: RelativeTimeFormatNumeric; numberingSystem: string; } /** * An object representing the relative time format in parts * that can be used for custom locale-aware formatting. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). * * [Specification](https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts). */ interface RelativeTimeFormatPart { type: string; value: string; unit?: RelativeTimeFormatUnit; } interface RelativeTimeFormat { /** * Formats a value and a unit according to the locale * and formatting options of the given * [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) * object. * * While this method automatically provides the correct plural forms, * the grammatical form is otherwise as neutral as possible. * It is the caller's responsibility to handle cut-off logic * such as deciding between displaying "in 7 days" or "in 1 week". * This API does not support relative dates involving compound units. * e.g "in 5 days and 4 hours". * * @param value - Numeric value to use in the internationalized relative time message * * @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) * to use in the relative time internationalized message. * Possible values are: `"year"`, `"quarter"`, `"month"`, `"week"`, * `"day"`, `"hour"`, `"minute"`, `"second"`. * Plural forms are also permitted. * * @throws `RangeError` if `unit` was given something other than `unit` possible values * * @returns Internationalized relative time message as string * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format). * * [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.format). */ format( value: number, unit: RelativeTimeFormatUnit, ): string; /** * A version of the format method which it returns an array of objects * which represent "parts" of the object, * separating the formatted number into its constituent parts * and separating it from other surrounding text. * These objects have two properties: * `type` a NumberFormat formatToParts type, and `value`, * which is the String which is the component of the output. * If a "part" came from NumberFormat, * it will have a unit property which indicates the `unit` being formatted; * literals which are part of the larger frame will not have this property. * * @param value - Numeric value to use in the internationalized relative time message * * @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) * to use in the relative time internationalized message. * Possible values are: `"year"`, `"quarter"`, `"month"`, `"week"`, * `"day"`, `"hour"`, `"minute"`, `"second"`. * Plural forms are also permitted. * * @throws `RangeError` if `unit` was given something other than `unit` possible values * * @returns Array of [FormatRelativeTimeToParts](https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts) * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts). * * [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.formatToParts). */ formatToParts( value: number, unit: RelativeTimeFormatUnit, ): RelativeTimeFormatPart[]; /** * Provides access to the locale and options computed during initialization of this `Intl.RelativeTimeFormat` object. * * @returns A new object with properties reflecting the locale * and formatting options computed during initialization * of the `Intel.RelativeTimeFormat` object. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions). * * [Specification](https://tc39.es/ecma402/#sec-intl.relativetimeformat.prototype.resolvedoptions) */ resolvedOptions(): ResolvedRelativeTimeFormatOptions; } /** * The [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) * object is a constructor for objects that enable language-sensitive relative time formatting. * * Part of [Intl object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) * namespace and the [ECMAScript Internationalization API](https://www.ecma-international.org/publications/standards/Ecma-402.htm). * * [Compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat#Browser_compatibility). * * [Polyfills](https://github.com/tc39/proposal-intl-relative-time#polyfills). */ const RelativeTimeFormat: { /** * Constructor creates [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) * objects * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the locales argument, * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters) * with some or all of options of the formatting. * An object with some or all of the following properties: * - `localeMatcher` - The locale matching algorithm to use. * Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. * For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). * - `numeric` - The format of output message. * Possible values are: `"always"` (default, e.g., `1 day ago`) or `"auto"` (e.g., `yesterday`). * The `"auto"` value allows to not always have to use numeric values in the output. * - `style` - The length of the internationalized message. Possible values are: * `"long"` (default, e.g., in 1 month), * `"short"` (e.g., in 1 mo.) * or `"narrow"` (e.g., in 1 mo.). The narrow style could be similar to the short style for some locales. * * @returns [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) object. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat). * * [Specification](https://tc39.es/ecma402/#sec-intl-relativetimeformat-constructor). */ new( locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: RelativeTimeFormatOptions, ): RelativeTimeFormat; /** * Returns an array containing those of the provided locales * that are supported in date and time formatting * without having to fall back to the runtime's default locale. * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the locales argument, * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters) * with some or all of options of the formatting. * An object with some or all of the following properties: * - `localeMatcher` - The locale matching algorithm to use. * Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. * For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). * - `numeric` - The format of output message. * Possible values are: `"always"` (default, e.g., `1 day ago`) or `"auto"` (e.g., `yesterday`). * The `"auto"` value allows to not always have to use numeric values in the output. * - `style` - The length of the internationalized message. Possible values are: * `"long"` (default, e.g., in 1 month), * `"short"` (e.g., in 1 mo.) * or `"narrow"` (e.g., in 1 mo.). The narrow style could be similar to the short style for some locales. * * @returns An array containing those of the provided locales * that are supported in date and time formatting * without having to fall back to the runtime's default locale. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf). * * [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.supportedLocalesOf). */ supportedLocalesOf( locales: BCP47LanguageTag | BCP47LanguageTag[], options?: RelativeTimeFormatOptions, ): BCP47LanguageTag[]; }; interface NumberFormatOptions { compactDisplay?: string; notation?: string; signDisplay?: string; unit?: string; unitDisplay?: string; } interface ResolvedNumberFormatOptions { compactDisplay?: string; notation?: string; signDisplay?: string; unit?: string; unitDisplay?: string; } interface DateTimeFormatOptions { dateStyle?: "full" | "long" | "medium" | "short"; timeStyle?: "full" | "long" | "medium" | "short"; calendar?: Calendar; dayPeriod?: "narrow" | "short" | "long"; numberingSystem?: NumberingSystem; hourCycle?: "h11" | "h12" | "h23" | "h24"; fractionalSecondDigits?: 0 | 1 | 2 | 3; } }
pouyakary/TypeScript
tests/cases/fourslash/completionsSelfDeclaring2.ts
<gh_stars>1-10 /// <reference path="fourslash.ts" /> //// function f1<T>(x: T) {} //// f1({ abc/*1*/ }); //// function f2<T extends { xyz: number }>(x: T) {} //// f2({ x/*2*/ }); verify.completions({ marker: "1", exact: completion.globalsPlus(["f1", "f2"]) }); verify.completions({ marker: "2", exact: ["xyz"] });
pouyakary/TypeScript
tests/cases/fourslash/completionEntryForUnionMethod.ts
///<reference path="fourslash.ts" /> ////var y: Array<string>|Array<number>; ////y.map/**/( const text = "(method) Array<T>.map<unknown>(callbackfn: ((value: string, index: number, array: string[]) => unknown) & ((value: number, index: number, array: number[]) => unknown), thisArg: any): unknown[]"; const documentation = "Calls a defined callback function on each element of an array, and returns an array that contains the results."; verify.quickInfoAt("", text, documentation); verify.completions({ marker: "", includes: { name: "map", text, documentation, tags: [ { name: "param", text: "callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array." }, { name: "param", text: "thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value." } ], }, });
pouyakary/TypeScript
tests/cases/fourslash/quickInfoAlias.ts
/// <reference path='fourslash.ts'/> // @Filename: /a.ts /////** //// * Doc //// * @tag Tag text //// */ ////export const x = 0; // @Filename: /b.ts ////import { x } from "./a"; ////x/*b*/; // @Filename: /c.ts /////** //// * Doc 2 //// * @tag Tag text 2 //// */ ////import { //// /** //// * Doc 3 //// * @tag Tag text 3 //// */ //// x ////} from "./a"; ////x/*c*/; goTo.eachMarker((_, index) => { verify.verifyQuickInfoDisplayParts( "alias", "export", { start: index === 0 ? 25 : 117, length: 1 }, [ { text:"(",kind:"punctuation" }, { text:"alias",kind:"text" }, { text:")",kind:"punctuation" }, { text:" ",kind:"space" }, { text:"const",kind:"keyword" }, { text:" ",kind:"space" }, { text:"x",kind:"aliasName" }, { text:":",kind:"punctuation" }, { text:" ",kind:"space" }, { text:"0",kind:"stringLiteral" }, { text:"\n",kind:"lineBreak" }, { text:"import",kind:"keyword" }, { text:" ",kind:"space" }, { text:"x",kind:"aliasName" }, ], [{ text: "Doc", kind: "text" }], [{ name: "tag", text: "Tag text" }]); });
pouyakary/TypeScript
src/webServer/webServer.ts
<reponame>pouyakary/TypeScript /*@internal*/ namespace ts.server { export interface HostWithWriteMessage { writeMessage(s: any): void; } export interface WebHost extends HostWithWriteMessage { readFile(path: string): string | undefined; fileExists(path: string): boolean; } export class BaseLogger implements Logger { private seq = 0; private inGroup = false; private firstInGroup = true; constructor(protected readonly level: LogLevel) { } static padStringRight(str: string, padding: string) { return (str + padding).slice(0, padding.length); } close() { } getLogFileName(): string | undefined { return undefined; } perftrc(s: string) { this.msg(s, Msg.Perf); } info(s: string) { this.msg(s, Msg.Info); } err(s: string) { this.msg(s, Msg.Err); } startGroup() { this.inGroup = true; this.firstInGroup = true; } endGroup() { this.inGroup = false; } loggingEnabled() { return true; } hasLevel(level: LogLevel) { return this.loggingEnabled() && this.level >= level; } msg(s: string, type: Msg = Msg.Err) { switch (type) { case Msg.Info: perfLogger.logInfoEvent(s); break; case Msg.Perf: perfLogger.logPerfEvent(s); break; default: // Msg.Err perfLogger.logErrEvent(s); break; } if (!this.canWrite()) return; s = `[${nowString()}] ${s}\n`; if (!this.inGroup || this.firstInGroup) { const prefix = BaseLogger.padStringRight(type + " " + this.seq.toString(), " "); s = prefix + s; } this.write(s, type); if (!this.inGroup) { this.seq++; } } protected canWrite() { return true; } protected write(_s: string, _type: Msg) { } } export type MessageLogLevel = "info" | "perf" | "error"; export interface LoggingMessage { readonly type: "log"; readonly level: MessageLogLevel; readonly body: string } export class MainProcessLogger extends BaseLogger { constructor(level: LogLevel, private host: HostWithWriteMessage) { super(level); } protected write(body: string, type: Msg) { let level: MessageLogLevel; switch (type) { case Msg.Info: level = "info"; break; case Msg.Perf: level = "perf"; break; case Msg.Err: level = "error"; break; default: Debug.assertNever(type); } this.host.writeMessage(<LoggingMessage>{ type: "log", level, body, }); } } export function createWebSystem(host: WebHost, args: string[], getExecutingFilePath: () => string): ServerHost { const returnEmptyString = () => ""; const getExecutingDirectoryPath = memoize(() => memoize(() => ensureTrailingDirectorySeparator(getDirectoryPath(getExecutingFilePath())))); // Later we could map ^memfs:/ to do something special if we want to enable more functionality like module resolution or something like that const getWebPath = (path: string) => startsWith(path, directorySeparator) ? path.replace(directorySeparator, getExecutingDirectoryPath()) : undefined; return { args, newLine: "\r\n", // This can be configured by clients useCaseSensitiveFileNames: false, // Use false as the default on web since that is the safest option readFile: path => { const webPath = getWebPath(path); return webPath && host.readFile(webPath); }, write: host.writeMessage.bind(host), watchFile: returnNoopFileWatcher, watchDirectory: returnNoopFileWatcher, getExecutingFilePath: () => directorySeparator, getCurrentDirectory: returnEmptyString, // For inferred project root if projectRoot path is not set, normalizing the paths /* eslint-disable no-restricted-globals */ setTimeout, clearTimeout, setImmediate: x => setTimeout(x, 0), clearImmediate: clearTimeout, /* eslint-enable no-restricted-globals */ require: () => ({ module: undefined, error: new Error("Not implemented") }), exit: notImplemented, // Debugging related getEnvironmentVariable: returnEmptyString, // TODO:: Used to enable debugging info // tryEnableSourceMapsForHost?(): void; // debugMode?: boolean; // For semantic server mode fileExists: path => { const webPath = getWebPath(path); return !!webPath && host.fileExists(webPath); }, directoryExists: returnFalse, // Module resolution readDirectory: notImplemented, // Configured project, typing installer getDirectories: () => [], // For automatic type reference directives createDirectory: notImplemented, // compile On save writeFile: notImplemented, // compile on save resolvePath: identity, // Plugins // realpath? // Module resolution, symlinks // getModifiedTime // File watching // createSHA256Hash // telemetry of the project // Logging related // /*@internal*/ bufferFrom?(input: string, encoding?: string): Buffer; // gc?(): void; // getMemoryUsage?(): number; }; } export interface StartSessionOptions { globalPlugins: SessionOptions["globalPlugins"]; pluginProbeLocations: SessionOptions["pluginProbeLocations"]; allowLocalPluginLoads: SessionOptions["allowLocalPluginLoads"]; useSingleInferredProject: SessionOptions["useSingleInferredProject"]; useInferredProjectPerProjectRoot: SessionOptions["useInferredProjectPerProjectRoot"]; suppressDiagnosticEvents: SessionOptions["suppressDiagnosticEvents"]; noGetErrOnBackgroundUpdate: SessionOptions["noGetErrOnBackgroundUpdate"]; syntaxOnly: SessionOptions["syntaxOnly"]; serverMode: SessionOptions["serverMode"]; } export class WorkerSession extends Session<{}> { constructor(host: ServerHost, private webHost: HostWithWriteMessage, options: StartSessionOptions, logger: Logger, cancellationToken: ServerCancellationToken, hrtime: SessionOptions["hrtime"]) { super({ host, cancellationToken, ...options, typingsInstaller: nullTypingsInstaller, byteLength: notImplemented, // Formats the message text in send of Session which is overriden in this class so not needed hrtime, logger, canUseEvents: false, }); } public send(msg: protocol.Message) { if (msg.type === "event" && !this.canUseEvents) { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`Session does not support events: ignored event: ${JSON.stringify(msg)}`); } return; } if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`${msg.type}:${indent(JSON.stringify(msg))}`); } this.webHost.writeMessage(msg); } protected parseMessage(message: {}): protocol.Request { return <protocol.Request>message; } protected toStringMessage(message: {}) { return JSON.stringify(message, undefined, 2); } } }
pouyakary/TypeScript
tests/cases/conformance/jsdoc/declarations/jsDeclarationsParameterTagReusesInputNodeInEmit1.ts
// @allowJs: true // @checkJs: true // @target: es6 // @outDir: ./out // @declaration: true // @filename: base.js class Base { constructor() {} } const BaseFactory = () => { return new Base(); }; BaseFactory.Base = Base; module.exports = BaseFactory; // @filename: file.js /** @typedef {import('./base')} BaseFactory */ /** * * @param {InstanceType<BaseFactory["Base"]>} base * @returns {InstanceType<BaseFactory["Base"]>} */ const test = (base) => { return base; };
pouyakary/TypeScript
src/lib/esnext.intl.d.ts
declare namespace Intl { type NumberFormatPartTypes = "compact" | "currency" | "decimal" | "exponentInteger" | "exponentMinusSign" | "exponentSeparator" | "fraction" | "group" | "infinity" | "integer" | "literal" | "minusSign" | "nan" | "plusSign" | "percentSign" | "unit" | "unknown"; interface NumberFormatPart { type: NumberFormatPartTypes; value: string; } interface NumberFormat { formatToParts(number?: number): NumberFormatPart[]; } }
pouyakary/TypeScript
src/testRunner/unittests/tsserver/webServer.ts
namespace ts.projectSystem { describe("unittests:: tsserver:: webServer", () => { class TestWorkerSession extends server.WorkerSession { constructor(host: server.ServerHost, webHost: server.HostWithWriteMessage, options: Partial<server.StartSessionOptions>, logger: server.Logger) { super( host, webHost, { globalPlugins: undefined, pluginProbeLocations: undefined, allowLocalPluginLoads: undefined, useSingleInferredProject: true, useInferredProjectPerProjectRoot: false, suppressDiagnosticEvents: false, noGetErrOnBackgroundUpdate: true, syntaxOnly: undefined, serverMode: undefined, ...options }, logger, server.nullCancellationToken, () => emptyArray ); } getProjectService() { return this.projectService; } } function setup(logLevel: server.LogLevel | undefined) { const host = createServerHost([libFile], { windowsStyleRoot: "c:/" }); const messages: any[] = []; const webHost: server.WebHost = { readFile: s => host.readFile(s), fileExists: s => host.fileExists(s), writeMessage: s => messages.push(s), }; const webSys = server.createWebSystem(webHost, emptyArray, () => host.getExecutingFilePath()); const logger = logLevel !== undefined ? new server.MainProcessLogger(logLevel, webHost) : nullLogger; const session = new TestWorkerSession(webSys, webHost, { serverMode: LanguageServiceMode.PartialSemantic }, logger); return { getMessages: () => messages, clearMessages: () => messages.length = 0, session }; } describe("open files are added to inferred project and semantic operations succeed", () => { function verify(logLevel: server.LogLevel | undefined) { const { session, clearMessages, getMessages } = setup(logLevel); const service = session.getProjectService(); const file: File = { path: "^memfs:/sample-folder/large.ts", content: "export const numberConst = 10; export const arrayConst: Array<string> = [];" }; session.executeCommand({ seq: 1, type: "request", command: protocol.CommandTypes.Open, arguments: { file: file.path, fileContent: file.content } }); checkNumberOfProjects(service, { inferredProjects: 1 }); const project = service.inferredProjects[0]; checkProjectActualFiles(project, ["/lib.d.ts", file.path]); // Lib files are rooted verifyQuickInfo(); verifyGotoDefInLib(); function verifyQuickInfo() { clearMessages(); const start = protocolFileLocationFromSubstring(file, "numberConst"); session.onMessage({ seq: 2, type: "request", command: protocol.CommandTypes.Quickinfo, arguments: start }); assert.deepEqual(last(getMessages()), { seq: 0, type: "response", command: protocol.CommandTypes.Quickinfo, request_seq: 2, success: true, performanceData: undefined, body: { kind: ScriptElementKind.constElement, kindModifiers: "export", start: { line: start.line, offset: start.offset }, end: { line: start.line, offset: start.offset + "numberConst".length }, displayString: "const numberConst: 10", documentation: "", tags: [] } }); verifyLogger(); } function verifyGotoDefInLib() { clearMessages(); const start = protocolFileLocationFromSubstring(file, "Array"); session.onMessage({ seq: 3, type: "request", command: protocol.CommandTypes.DefinitionAndBoundSpan, arguments: start }); assert.deepEqual(last(getMessages()), { seq: 0, type: "response", command: protocol.CommandTypes.DefinitionAndBoundSpan, request_seq: 3, success: true, performanceData: undefined, body: { definitions: [{ file: "/lib.d.ts", ...protocolTextSpanWithContextFromSubstring({ fileText: libFile.content, text: "Array", contextText: "interface Array<T> { length: number; [n: number]: T; }" }) }], textSpan: { start: { line: start.line, offset: start.offset }, end: { line: start.line, offset: start.offset + "Array".length }, } } }); verifyLogger(); } function verifyLogger() { const messages = getMessages(); assert.equal(messages.length, logLevel === server.LogLevel.verbose ? 4 : 1, `Expected ${JSON.stringify(messages)}`); if (logLevel === server.LogLevel.verbose) { verifyLogMessages(messages[0], "info"); verifyLogMessages(messages[1], "perf"); verifyLogMessages(messages[2], "info"); } clearMessages(); } function verifyLogMessages(actual: any, expectedLevel: server.MessageLogLevel) { assert.equal(actual.type, "log"); assert.equal(actual.level, expectedLevel); } } it("with logging enabled", () => { verify(server.LogLevel.verbose); }); it("with logging disabled", () => { verify(/*logLevel*/ undefined); }); }); }); }
pouyakary/TypeScript
tests/cases/fourslash/completionListInObjectLiteral5.ts
<gh_stars>1-10 /// <reference path="fourslash.ts" /> ////const o = 'something' ////const obj = { //// prop: o/*1*/, //// pro() { //// const obj1 = { //// p:{ //// s: { //// h: { //// hh: o/*2*/ //// }, //// someFun() { //// o/*3*/ //// } //// } //// } //// } //// }, //// o/*4*/ ////} verify.completions({ marker: ["1"], excludes: ['obj'], includes: ['o'] }); verify.completions({ marker: ["2"], excludes: ['obj1'], includes: ['o', 'obj'] }); verify.completions({ marker: ["3"], includes: ['o', 'obj', 'obj1'] }); verify.completions({ marker: ["4"], includes: ['o'], excludes: ['obj'] });
alekitto/atlante-js
lib/Requester/Decorator/Authentication/HttpBasicAuthenticator.ts
import Request from '../../Request'; const encode = (() => { if ('undefined' !== typeof Buffer) { // Node.JS return (str: string) => Buffer.from(str).toString('base64'); } /* Base64 string to array encoding */ const uint6ToB64 = (n: number) => { switch (true) { case 26 > n: return n + 65; case 52 > n: return n + 71; case 62 > n: return n - 4; case 62 === n: return 43; case 63 === n: return 47; default: return 65; } }; return (str: string) => { const arr = new Uint16Array(str.length); Array.prototype.forEach.call(arr, (_: any, idx: number) => arr[idx] = str.charCodeAt(idx)); const eqLen = (3 - (arr.length % 3)) % 3; let sB64Enc = ''; for (let nMod3, nLen = arr.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; nUint24 |= arr[nIdx] << (16 >>> nMod3 & 24); if (2 === nMod3 || 1 === arr.length - nIdx) { sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); nUint24 = 0; } } return 0 === eqLen ? sB64Enc : sB64Enc.substring(0, sB64Enc.length - eqLen) + (1 === eqLen ? '=' : '=='); }; })(); export default class HttpBasicAuthenticator { private readonly _auth: string; /** * Constructor. */ constructor(encodedAuth: string); constructor(username: string, password: string); constructor(usernameOrEncodedAuth: string, password: string = null) { this._auth = null === password ? usernameOrEncodedAuth : encode(usernameOrEncodedAuth + (password ? ':' + password : '')); } /** * Decorates the request adding basic authentication header. */ decorate(request: Request): Request { const { body = undefined, method, url, headers } = request; if (! headers.has('Authorization')) { headers.set('Authorization', 'Basic ' + this._auth); } return { body, method, url, headers }; } }
alekitto/atlante-js
lib/Storage/CookieStorage.ts
import AbstractStorage from './AbstractStorage'; const getCookie = (key: string) => { const name = key + '='; const decodedCookie = decodeURIComponent(document.cookie); const ca = decodedCookie.split(';') .map(str => str.trim()); for (const c of ca) { if (0 === c.indexOf(name)) { return c.substring(name.length, c.length); } } return undefined; }; export default class CookieStorage extends AbstractStorage { private readonly _cookieDomain: string; constructor(cookieDomain?: string, defaultLifetime?: number) { super(defaultLifetime); this._cookieDomain = cookieDomain; } /** * @inheritdoc */ async hasItem(key: string): Promise<boolean> { return !! document.cookie.match(new RegExp('(^|;)\\s*'+key+'=')); } /** * @inheritdoc */ async deleteItem(key: string): Promise<boolean> { document.cookie = key + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/' + (this._cookieDomain ? ';domain='+this._cookieDomain : ''); return true; } /** * @inheritdoc */ protected async _getItem(key: string): Promise<string> { return getCookie(key); } /** * @inheritdoc */ protected async _save(key: string, value: string, expiry: Date): Promise<boolean> { const d = new Date(); d.setTime(expiry.getTime()); document.cookie = key + '=' + value + ';' + 'expires='+ d.toUTCString() + ';path=/' + (this._cookieDomain ? ';domain='+this._cookieDomain : '') ; return true; } }
alekitto/atlante-js
index.ts
/// <reference path="lib/Exception/AbstractException.ts" /> /// <reference path="lib/Exception/AccessDeniedException.ts" /> /// <reference path="lib/Exception/BadRequestException.ts" /> /// <reference path="lib/Exception/InvalidRequestException.ts" /> /// <reference path="lib/Exception/NotFoundException.ts" /> /// <reference path="lib/Exception/NoTokenAvailableException.ts" /> /// <reference path="lib/Http/Client.ts" /> /// <reference path="lib/Http/ClientInterface.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/OAuth/ClientTokenAuthenticator.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/OAuth/TokenPasswordAuthenticator.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/OAuth/TokenResponseDataInterface.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/OpenID/BaseAuthenticator.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/OpenID/CodeFlowAuthenticator.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/OpenID/ImplicitFlowAuthenticator.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/OpenID/ServerConfiguration.ts" /> /// <reference path="lib/Requester/Decorator/Authentication/HttpBasicAuthenticator.ts" /> /// <reference path="lib/Requester/Decorator/BodyConverterDecorator.ts" /> /// <reference path="lib/Requester/Decorator/DecoratorInterface.ts" /> /// <reference path="lib/Requester/Decorator/UrlDecorator.ts" /> /// <reference path="lib/Requester/Decorator/VersionSetterDecorator.ts" /> /// <reference path="lib/Requester/Header/Accept.ts" /> /// <reference path="lib/Requester/Header/BaseAccept.ts" /> /// <reference path="lib/Requester/Response/AbstractResponse.ts" /> /// <reference path="lib/Requester/Response/AbstractResponseFactory.ts" /> /// <reference path="lib/Requester/Response/AccessDeniedResponse.ts" /> /// <reference path="lib/Requester/Response/BadResponse.ts" /> /// <reference path="lib/Requester/Response/BadResponsePropertyTree.ts" /> /// <reference path="lib/Requester/Response/InvalidResponse.ts" /> /// <reference path="lib/Requester/Response/NotFoundResponse.ts" /> /// <reference path="lib/Requester/Response/Response.ts" /> /// <reference path="lib/Requester/Response/ResponseFactoryInterface.ts" /> /// <reference path="lib/Requester/Response/ResponseInterface.ts" /> /// <reference path="lib/Requester/Response/XhrResponseFactory.ts" /> /// <reference path="lib/Requester/Headers.ts" /> /// <reference path="lib/Requester/HttpMessage.ts" /> /// <reference path="lib/Requester/Request.ts" /> /// <reference path="lib/Requester/RequesterInterface.ts" /> /// <reference path="lib/Requester/WebRequester.ts" /> /// <reference path="lib/Storage/Marshaller/JSONMarshaller.ts" /> /// <reference path="lib/Storage/Marshaller/MarshallerInterface.ts" /> /// <reference path="lib/Storage/Marshaller/NullMarshaller.ts" /> /// <reference path="lib/Storage/AbstractStorage.ts" /> /// <reference path="lib/Storage/ChainStorage.ts" /> /// <reference path="lib/Storage/CookieStorage.ts" /> /// <reference path="lib/Storage/InMemoryStorage.ts" /> /// <reference path="lib/Storage/Item.ts" /> /// <reference path="lib/Storage/ItemInterface.ts" /> /// <reference path="lib/Storage/ProvidedTokenStorage.ts" /> /// <reference path="lib/Storage/StorageInterface.ts" /> /// <reference path="lib/Storage/WebLocalStorage.ts" /> /// <reference path="lib/Utils/ArrayUtils.d.ts" />
alekitto/atlante-js
lib/Requester/Response/AbstractResponse.ts
import IResponse, { ResponseInterface } from './ResponseInterface'; import Headers from '../Headers'; export default abstract class AbstractResponse extends implementationOf(IResponse) implements ResponseInterface { constructor(protected statusCode: number, protected headers: Headers, protected data: unknown) { super(); } getData<T>(): T; getData(): unknown[] | Record<string, unknown> | string { return this.data as any; } getHeaders(): Headers { return this.headers; } getStatusCode(): number { return this.statusCode; } }
alekitto/atlante-js
lib/Requester/Decorator/Authentication/OpenID/ServerConfiguration.ts
<reponame>alekitto/atlante-js export interface ServerConfigurationProps { issuer: string; authorization_endpoint: string; token_endpoint: string; end_session_endpoint: string; userinfo_endpoint: string; jwks_uri: string; } export default class ServerConfiguration { public readonly issuer: string; public readonly authorizationEndpoint: string; public readonly tokenEndpoint: string; public readonly logoutEndpoint: string; public readonly userinfoEndpoint: string; private _jwks_uri: string; constructor(config: ServerConfigurationProps) { this.issuer = config.issuer; this.authorizationEndpoint = config.authorization_endpoint; this.tokenEndpoint = config.token_endpoint; this.logoutEndpoint = config.end_session_endpoint; this.userinfoEndpoint = config.userinfo_endpoint; this._jwks_uri = config.jwks_uri; } }
alekitto/atlante-js
lib/Exception/AccessDeniedException.ts
<filename>lib/Exception/AccessDeniedException.ts import AbstractException from './AbstractException'; import AccessDeniedResponse from '../Requester/Response/AccessDeniedResponse'; export default class AccessDeniedException extends AbstractException { constructor(response?: AccessDeniedResponse) { super(response); } get response(): AccessDeniedResponse { return super.response as AccessDeniedResponse; } }
alekitto/atlante-js
lib/Storage/Marshaller/MarshallerInterface.ts
<gh_stars>1-10 export interface MarshallerInterface { } export class MarshallerInterface { /** * Serializes a value into a string. */ // @ts-ignore marshall(value: any): string { } /** * Converts a serialized value into its original representation. */ unmarshall(value: string): any { } } export default getInterface(MarshallerInterface);
alekitto/atlante-js
integrations/angular/requester.ts
<filename>integrations/angular/requester.ts<gh_stars>0 import { HttpClient, HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaders, HttpRequest } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { RequesterInterface } from '../../lib/Requester/RequesterInterface'; import { ResponseFactoryInterface } from '../../lib/Requester/Response/ResponseFactoryInterface'; import { ResponseInterface } from '../../lib/Requester/Response/ResponseInterface'; const isError = (event: HttpEvent<string> | HttpErrorResponse): event is HttpErrorResponse => { return 'undefined' !== typeof (<HttpErrorResponse>event).error; }; @Injectable() export default class Requester implements RequesterInterface { constructor( @Inject(HttpClient) private _http: HttpClient, @Inject(ResponseFactoryInterface) private _responseFactory: ResponseFactoryInterface ) { } request<S>(method: string, path: string, headers: any = {}, requestData?: any): Promise<ResponseInterface> { if ('function' === typeof requestData) { requestData = requestData(); } let contentTypeSet = false; for (const key of Object.keys(headers)) { if ('content-type' === key.toLowerCase()) { contentTypeSet = true; } } if (! contentTypeSet) { headers['Content-Type'] = 'application/json'; } const request: HttpRequest<S> = new HttpRequest<S>(method, path, requestData, { headers: new HttpHeaders(headers), responseType: 'text', }); return new Promise<ResponseInterface>((resolve): void => { const resolver: typeof resolve = (value) => { subscription.unsubscribe(); resolve(value); } const subscription = this._http .request(request) .subscribe( (event: HttpEvent<string>) => { this.generateResponse(event, resolver) }, (event: HttpErrorResponse) => { this.generateResponse(event, resolver) } ); }); } private generateResponse(event: HttpEvent<string> | HttpErrorResponse, resolver: (value?: ResponseInterface | PromiseLike<ResponseInterface>) => void): void { if (! isError(event) && event.type !== HttpEventType.Response) { return; } resolver(this._responseFactory.fromResponse(event)); } }
alekitto/atlante-js
lib/Requester/Response/Response.ts
<reponame>alekitto/atlante-js import AbstractResponse from './AbstractResponse'; export default class Response extends AbstractResponse { }
alekitto/atlante-js
lib/Exception/AbstractException.ts
import { ResponseInterface } from '../Requester/Response/ResponseInterface'; export default class AbstractException extends Error { private readonly _response: ResponseInterface; /** * Constructor. */ constructor(response: ResponseInterface | undefined, message?: string) { super(message ?? ('Unsuccessful response received. Status code = ' + response.getStatusCode())); this._response = response; } /** * Gets the response, if set. */ get response(): ResponseInterface { return this._response; } }
alekitto/atlante-js
lib/Exception/InvalidRequestException.ts
import AbstractException from './AbstractException'; import InvalidResponse from '../Requester/Response/InvalidResponse'; export default class InvalidRequestException extends AbstractException { constructor(response?: InvalidResponse) { super(response); } get response(): InvalidResponse { return super.response as InvalidResponse; } }
alekitto/atlante-js
lib/Exception/BadRequestException.ts
import AbstractException from './AbstractException'; import BadResponse from '../Requester/Response/BadResponse'; import BadResponsePropertyTree from '../Requester/Response/BadResponsePropertyTree'; export default class BadRequestException extends AbstractException { constructor(response?: BadResponse) { super(response); } get response(): BadResponse { return super.response as BadResponse; } get errors(): BadResponsePropertyTree { return this.response.getErrors(); } }
alekitto/atlante-js
lib/Utils/ArrayUtils.d.ts
declare class ArrayUtils { /** * Recursively converts all the keys to camel case. */ static toCamelCaseKeys<T = any>(input: T[]): T[]; static toCamelCaseKeys<T = any>(input: { [key: string]: T }): { [key: string]: T }; /** * Recursively converts all the keys to snake case. */ static toSnakeCaseKeys<T = any>(input: T[]): T[]; static toSnakeCaseKeys<T = any>(input: { [key: string]: T }): { [key: string]: T }; /** * Sort an object by keys. */ static ksort(input: { [key: string]: any }): { [key: string]: any }; /** * Shuffle array elements */ static shuffle(input: any[]): any[]; /** * Computes the difference between two objects. */ static computePatchObject(originalData: { [key: string]: any }, newData: { [key: string]: any }): { [key: string]: any }; } export default ArrayUtils;
alekitto/atlante-js
lib/Http/ClientInterface.ts
import Headers from '../Requester/Headers'; import { ResponseInterface } from '../Requester/Response/ResponseInterface'; export interface ClientInterface {} export class ClientInterface { /** * Performs a request to the API service using the given method. * * Request data should be either a string, an array or an object. * If not a string will be JSON-encoded. * The parameter is ignored on GET, HEAD and DELETE requests. * * In case of an error, the "error" event SHOULD be emitted. * If no handler has been registered the error MUST be thrown. * * @throws {NoTokenAvailableException} When no token could be provided for the request. */ // @ts-ignore request(method: string, path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { } /** * Performs a request to the API service using a GET method. */ // @ts-ignore get(path: string, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { } /** * Performs a request to the API service using a POST method. */ // @ts-ignore post(path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { } /** * Performs a request to the API service using a PUT method. */ // @ts-ignore put(path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { } /** * Performs a request to the API service using a PATCH method. */ // @ts-ignore patch(path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { } } export default getInterface(ClientInterface);
alekitto/atlante-js
lib/Requester/Decorator/UrlDecorator.ts
<reponame>alekitto/atlante-js import Decorator, { DecoratorInterface } from './DecoratorInterface'; import Request from '../Request'; export default class UrlDecorator extends implementationOf(Decorator) implements DecoratorInterface { private readonly _baseUrl: string; /** * Constructor. */ constructor(baseUrl: string) { super(); this._baseUrl = baseUrl; } /** * @inheritdoc */ decorate(request: Request<any>): Request<any> { let { body = undefined, method, url, headers } = request; if (-1 === url.indexOf('://')) { const parsedUrl = new URL(url, this._baseUrl); url = parsedUrl.href; } return { body, method, url, headers }; } }
alekitto/atlante-js
lib/Requester/Request.ts
<reponame>alekitto/atlante-js<gh_stars>1-10 import Headers from './Headers'; import HttpMessage from './HttpMessage'; export default interface Request<T = any> extends HttpMessage { readonly method: string; readonly url: string; readonly body: T | undefined; } export const createRequest = <T = any>( method: string, url: string, headers: Headers | Record<string, string | string[]> | null = null, body?: T | undefined ): Request<T> => { return { method, url, headers: new Headers(headers), body, }; };
alekitto/atlante-js
lib/Storage/Item.ts
import Interface, { ItemInterface } from './ItemInterface'; export default class Item extends implementationOf(Interface) implements ItemInterface { private readonly _key: string; private _value: any; private readonly _isHit: boolean; private _expiry: number; private readonly _defaultLifetime: undefined | number; constructor() { super(); this._key = undefined; this._value = undefined; this._isHit = false; this._expiry = undefined; this._defaultLifetime = undefined; } /** * @inheritdoc */ get(): any { return this._value; } /** * @inheritdoc */ set(value: any): this { this._value = value; return this; } /** * @inheritdoc */ get isHit(): boolean { return this._isHit; } /** * @inheritdoc */ get key(): string { return this._key; } /** * @inheritdoc */ expiresAt(expiration: Date | undefined | null): this { if (null === expiration || undefined === expiration) { this._expiry = 0 < this._defaultLifetime ? new Date().setTime(new Date().getTime() + (this._defaultLifetime * 1000)) : undefined; } else if (expiration instanceof Date) { this._expiry = expiration.getTime(); } else { throw new Error('Expiration date must an instance of Date or be null or undefined, "' + typeof expiration + '" given'); } return this; } /** * @inheritdoc */ expiresAfter(time: number | undefined): this { if (null === time || undefined === time) { this._expiry = 0 < this._defaultLifetime ? new Date().setTime(new Date().getTime() + (this._defaultLifetime * 1000)) : undefined; } else if ('number' === typeof time) { this._expiry = new Date().setTime(new Date().getTime() + (time * 1000)); } else { throw new Error('Expiration date must an instance of TimeSpan, a Number or be null or undefined, "' + typeof time + '" given'); } return this; } }
alekitto/atlante-js
lib/Requester/WebRequester.ts
<gh_stars>0 import Requester, { RequesterInterface } from './RequesterInterface'; import { ResponseFactoryInterface } from './Response/ResponseFactoryInterface'; import { ResponseInterface } from './Response/ResponseInterface'; import XhrResponseFactory from './Response/XhrResponseFactory'; export default class WebRequester extends implementationOf(Requester) implements RequesterInterface { private readonly _responseFactory: ResponseFactoryInterface; private readonly _xmlHttp: typeof XMLHttpRequest; /** * Constructor. */ constructor(responseFactory: ResponseFactoryInterface = new XhrResponseFactory(), xmlHttp: typeof XMLHttpRequest = XMLHttpRequest) { super(); this._responseFactory = responseFactory; this._xmlHttp = xmlHttp; } /** * @inheritdoc */ request(method: string, path: string, headers: any = {}, requestData?: any): Promise<ResponseInterface> { const xmlHttp: XMLHttpRequest = new this._xmlHttp(); let contentTypeSet = false; xmlHttp.open(method, path); if ('function' === typeof requestData) { requestData = requestData(); } for (const [ key, value ] of Object.entries(headers)) { xmlHttp.setRequestHeader(key, String(value)); if ('content-type' === key.toLowerCase()) { contentTypeSet = true; } } if (! contentTypeSet) { xmlHttp.setRequestHeader('Content-Type', 'application/json'); } return new Promise(resolve => { xmlHttp.onreadystatechange = () => { if(xmlHttp.readyState !== this._xmlHttp.DONE) { return; } resolve(this._responseFactory.fromResponse(xmlHttp)); }; xmlHttp.send(requestData); }); } }
alekitto/atlante-js
lib/Storage/ItemInterface.ts
/** * ItemInterface defines an interface for interacting with objects inside a storage. * * Each Item object MUST be associated with a specific key, which can be set * according to the implementing system and is typically passed by the * ItemInterface object. * * The ItemInterface object encapsulates the storage and retrieval of * items. Each ItemInterface is generated by a StorageInterface object, * which is responsible for any required setup as well as associating the object * with a unique Key. * ItemInterface objects MUST be able to store and retrieve any type * of value defined in the Data section of the specification. * * Calling Libraries MUST NOT instantiate Item objects themselves. They may only * be requested from a Storage object via the getItem() method. Calling Libraries * SHOULD NOT assume that an Item created by one Implementing Library is * compatible with a Pool from another Implementing Library. */ export class ItemInterface { // @ts-ignore /** * The key for the current item. * * The key is loaded by the Implementing Library, but should be available to * the higher level callers when needed. */ // @ts-ignore get key(): string { } /** * Retrieves the value of the item from the cache associated with this object's key. * * The value returned must be identical to the value originally stored by set(). * * If isHit is false, this method MUST return undefined. Note that undefined * is a legitimate cached value, so the isHit property SHOULD be used to * differentiate between "undefined value was found" and "no value was found." */ get(): any { } /** * Confirms if the item lookup resulted in an hit. * * Note: This method MUST NOT have a race condition between checking isHit * and calling get(). */ // @ts-ignore get isHit(): boolean { } /** * Sets the value represented by this item. * * The value argument may be any item that can be serialized by JSON.stringify, * although the method of serialization is left up to the Implementing * Library. */ // @ts-ignore set(value: any): this { } /** * Sets the expiration time for this item. */ // @ts-ignore expiresAt(expiration: Date | undefined | null): this { } /** * Sets the expiration time for this item. */ // @ts-ignore expiresAfter(time: number | undefined): this { } } export interface ItemInterface { } export default getInterface(ItemInterface);
alekitto/atlante-js
lib/Storage/InMemoryStorage.ts
import Storage, { StorageInterface } from './StorageInterface'; import Item from './Item'; import { ItemInterface } from './ItemInterface'; import JSONMarshaller from './Marshaller/JSONMarshaller'; import { MarshallerInterface } from './Marshaller/MarshallerInterface'; export default class InMemoryStorage extends implementationOf(Storage) implements StorageInterface { public marshaller: MarshallerInterface; /** * Create a cache item for the current adapter. */ private readonly _createCacheItem: (key: string, value: any, isHit: boolean) => ItemInterface; private _values: Record<string, string>; private _expiries: Record<string, number>; private _pruneInterval: any; constructor(defaultLifetime?: number) { super(); this._createCacheItem = (key, value, isHit) => { const item: any = new Item(); item._key = key; item._value = value; item._isHit = isHit; item._defaultLifetime = defaultLifetime; return item; }; this.marshaller = new JSONMarshaller(); this._values = {}; this._expiries = {}; this._pruneInterval = undefined; } /** * Deletes the expired items. */ async prune(): Promise<boolean> { const time = new Date().getTime(); let ok = true; for (const key of Object.keys(this._expiries)) { if (time < this._expiries[key]) { continue; } ok = await this.deleteItem(key) && ok; } return ok; } /** * @inheritdoc */ async getItem(key: string): Promise<ItemInterface> { let value; let isHit = await this.hasItem(key); try { if (! isHit || 'undefined' === (value = this._values[key])) { this._values[key] = value = undefined; } else if (undefined === (value = this.marshaller.unmarshall(value))) { this._values[key] = value = undefined; isHit = false; } } catch (e) { this._values[key] = value = undefined; isHit = false; } return this._createCacheItem(key, value, isHit); } /** * @inheritdoc */ async hasItem(key: string): Promise<boolean> { return undefined !== this._expiries[key] && this._expiries[key] >= new Date().getTime() || ! (await this.deleteItem(key)); } /** * @inheritdoc */ async clear(): Promise<boolean> { this._values = {}; this._expiries = {}; if (undefined !== this._pruneInterval) { clearInterval(this._pruneInterval); } return true; } /** * @inheritdoc */ async deleteItem(key: string): Promise<boolean> { delete this._values[key]; delete this._expiries[key]; if (undefined !== this._pruneInterval && 0 === Object.keys(this._expiries).length) { clearInterval(this._pruneInterval); this._pruneInterval = undefined; } return true; } /** * @inheritdoc */ async save(item: ItemInterface): Promise<boolean> { const key = (item as any)._key; let value = (item as any)._value; let expiry = (item as any)._expiry; if (expiry && expiry <= new Date().getTime()) { await this.deleteItem(key); return true; } try { value = this.marshaller.marshall(value); } catch (e) { return false; } if (undefined === expiry && 0 < (item as any)._defaultLifetime) { expiry = new Date().getTime() + ((item as any)._defaultLifetime * 1000); } this._values[key] = value; this._expiries[key] = undefined !== expiry ? expiry : Infinity; if (undefined === this._pruneInterval) { this._pruneInterval = setInterval(this.prune.bind(this), 60000); } return true; } }
alekitto/atlante-js
lib/Storage/ProvidedTokenStorage.ts
import AbstractStorage from './AbstractStorage'; import NullMarshaller from './Marshaller/NullMarshaller'; export default class ProvidedTokenStorage extends AbstractStorage { private _accessToken?: string; private _refreshToken?: string; /** * Constructor. */ constructor(accessToken?: string | undefined, refreshToken?: string | undefined) { super(); this._accessToken = accessToken; this._refreshToken = refreshToken; this.marshaller = new NullMarshaller(); } /** * @inheritdoc */ async hasItem(key: string): Promise<boolean> { return (('access_token' === key && undefined !== this._accessToken) || ('refresh_token' === key && undefined !== this._refreshToken)); } /** * @inheritdoc */ async clear(): Promise<boolean> { this._accessToken = undefined; this._refreshToken = undefined; return true; } /** * @inheritdoc */ async deleteItem(key: string): Promise<boolean> { switch (key) { case 'access_token': this._accessToken = undefined; break; case 'refresh_token': this._refreshToken = undefined; break; } return true; } /** * @inheritdoc */ async _getItem(key: string): Promise<any> { switch (key) { case 'access_token': return this._accessToken; case 'refresh_token': return this._refreshToken; } return undefined; } /** * @inheritdoc */ async _save(key: string, value: any, expiry: Date): Promise<boolean> { // eslint-disable-line no-unused-vars switch (key) { case 'access_token': this._accessToken = value; return true; case 'refresh_token': this._refreshToken = value; return true; } return false; } }
alekitto/atlante-js
lib/Requester/Decorator/BodyConverterDecorator.ts
import Decorator, { DecoratorInterface } from './DecoratorInterface'; import Request from '../Request'; const isBlob = 'undefined' !== typeof Blob ? v => v instanceof Blob : () => false; export default class BodyConverterDecorator extends implementationOf(Decorator) implements DecoratorInterface { /** * Converts the body to json if it is a js object. */ decorate(request: Request<any>): Request<any> { let { body = null, method, url, headers } = request; if (body && 'string' !== typeof body && ! isBlob(body)) { const contentType = headers.get('content-type'); // Add content-type if not specified if (contentType === undefined) { headers.set('content-type', 'application/json'); } const originalBody = body; body = () => { let body = this._prepare(originalBody); if (undefined !== body[Symbol.iterator] || isObjectLiteral(body)) { body = BodyConverterDecorator._encodeIterable(body, headers); } return body; }; } return { body, method, url, headers }; } /** * @private */ static _encodeIterable(body, headers) { const contentType = headers.get('content-type'); if (contentType.match(/^application\/(?:merge-patch\+)?json/)) { body = JSON.stringify(body); } else if (contentType.match(/^application\/(?:merge-patch\+)?x-www-form-urlencoded/)) { const p = {}; const encodeParams = (iterable, prefix = null) => { for (const [ k, v ] of Object.entries(iterable)) { const key = null === prefix ? k : prefix + '[' + k + ']'; if (Array.isArray(v) || isObjectLiteral(v)) { encodeParams(v, key); } else { p[key] = v; } } }; encodeParams(body); body = (new URLSearchParams(p)).toString(); } else { throw new UnexpectedValueException(`Unable to convert Request content body: expected "application/json", "application/x-www-form-urlencoded", "application/merge-patch+json" or "application/merge-patch+x-www-form-urlencoded" \`content-type\` header, "${contentType}" given`); } return body; } _prepare(body) { if (undefined === body || null === body || 'string' === typeof body || 'number' === typeof body || 'boolean' === typeof body) { return body; } if (body instanceof Date) { return body.toISOString(); } if (isFunction(body)) { return this._prepare(body()); } if (body[Symbol.iterator]) { const iterated = []; for (const field of body) { iterated.push(this._prepare(field)); } return iterated; } else if (isObjectLiteral(body)) { const iterated = {}; for (const [ k, field ] of Object.entries(body)) { iterated[k] = this._prepare(field); } return iterated; } throw new InvalidArgumentException('Argument #1 passed to BodyConverterDecorator._prepare has to be null, string, number, boolean, Date, Blob, iterable or function, "' + typeof body + '" given'); } }
alekitto/atlante-js
lib/Requester/Response/InvalidResponse.ts
import AbstractResponse from './AbstractResponse'; export default class InvalidResponse extends AbstractResponse { }
alekitto/atlante-js
lib/Requester/Response/BadResponse.ts
import BadResponsePropertyTree from './BadResponsePropertyTree'; import Headers from '../Headers'; import InvalidResponse from './InvalidResponse'; export default class BadResponse extends InvalidResponse { public static readonly HTTP_STATUS = 400; protected data: BadResponsePropertyTree; constructor(headers: Headers, data: unknown) { data = BadResponsePropertyTree.parse(data); super(BadResponse.HTTP_STATUS, headers, data); } /** * Alias of getData(). */ getErrors(): BadResponsePropertyTree { return this.getData(); } getData<T>(): never; getData(): BadResponsePropertyTree { return super.getData(); } }
alekitto/atlante-js
lib/Requester/Header/BaseAccept.ts
import '@jymfony/util/lib/String/trim'; import ArrayUtils from '../../Utils/ArrayUtils'; export default class BaseAccept { protected _type: string; private readonly _quality: number; private readonly _value: string; private _normalized: string; private readonly _parameters: Record<string, string>; /** * Constructor. * * @param {string} value */ protected constructor(value: string) { const [ type, parameters ] = this._parseParameters(value); if (parameters.q) { this._quality = parseFloat(parameters.q); delete parameters.q; } else { this._quality = 1.0; } this._value = value; this._type = type.trim().toLowerCase(); this._parameters = parameters; } /** * Gets the string representation of this header. */ toString(): string { return this.normalizedValue; } get normalizedValue(): string { return this._type + (0 < Object.keys(this._parameters).length ? '; ' + this._buildParametersString(this._parameters) : ''); } get value(): string { return this._value; } get type(): string { return this._type; } get quality(): number { return this._quality; } get parameters(): Record<string, string> { return { ...this._parameters }; } /** * Adds a parameter to the accept header. */ setParameter(key: string, value: string): void { if (undefined === value || null === value) { delete this._parameters[key]; return; } this._parameters[key] = String(value); } getParameter(key: string, default_?: any): string | any { return undefined !== this._parameters[key] ? this._parameters[key] : default_; } /** * Checks if a parameter is set. */ hasParameter(key: string): boolean { return undefined !== this._parameters[key]; } /** * Parses accept header parameters. */ private _parseParameters(acceptPart: string): [string, Record<string, string>] { const [ type, ...parts ] = acceptPart.split(';'); const parameters: Record<string, string> = {}; for (const part of parts) { const split = part.split('='); if (2 !== split.length) { continue; } const key = split[0].trim().toLowerCase(); parameters[key] = __jymfony.trim(part[1], ' "'); } return [ type, parameters ]; } private _buildParametersString(parameters: Record<string, string>): string { const parts = []; parameters = ArrayUtils.ksort(parameters); for (const [ key, val ] of Object.entries(parameters)) { parts.push(String(key) + '=' + String(val)); } return parts.join('; '); } }
alekitto/atlante-js
lib/Storage/WebLocalStorage.ts
import AbstractStorage from './AbstractStorage'; export default class WebLocalStorage extends AbstractStorage { /** * @inheritdoc */ async hasItem(key: string): Promise<boolean> { let item; try { item = localStorage.getItem(key); } catch (e) { return false; } if (null === item) { return false; } try { item = this.marshaller.unmarshall(item); const expiry = item.expiry; return null === expiry || expiry >= new Date().getTime(); } catch (e) { return false; } } async clear(): Promise<boolean> { localStorage.clear(); return true; } /** * @inheritdoc */ async deleteItem(key: string): Promise<boolean> { localStorage.removeItem(key); return true; } /** * @inheritdoc */ protected async _getItem(key: string): Promise<string> { let item; if (! (item = localStorage.getItem(key)) || ! (item = this.marshaller.unmarshall(item))) { return undefined; } return item.value; } /** * @inheritdoc */ protected async _save(key: string, value: string, expiry: Date): Promise<boolean> { localStorage.setItem(key, this.marshaller.marshall({ value, expiry })); return true; } }
alekitto/atlante-js
lib/Requester/Response/AbstractResponseFactory.ts
<filename>lib/Requester/Response/AbstractResponseFactory.ts import IResponseFactory, { ResponseFactoryInterface } from './ResponseFactoryInterface'; import AccessDeniedResponse from './AccessDeniedResponse'; import BadResponse from './BadResponse'; import Headers from '../Headers'; import InvalidResponse from './InvalidResponse'; import NotFoundResponse from './NotFoundResponse'; import Response from './Response'; import { ResponseInterface } from './ResponseInterface'; export default abstract class AbstractResponseFactory extends implementationOf(IResponseFactory) implements ResponseFactoryInterface { protected makeResponse(content: string, headers: Headers, statusCode: number): ResponseInterface { const data = AbstractResponseFactory.decodeData(content, headers); if (Array.isArray(data) || isObjectLiteral(data)) { if (300 > statusCode && 200 <= statusCode) { return new Response(statusCode, headers, data); } switch (statusCode) { case 400: return new BadResponse(headers, data); case 403: return new AccessDeniedResponse(headers, data); case 404: return new NotFoundResponse(headers, data); } } return new InvalidResponse(statusCode, headers, data); } private static decodeData(responseText: string, headers: Headers) { let data = responseText; if (((headers.get('content-type') || 'text/html') as string).match(/^application\/json/)) { try { data = JSON.parse(data); } catch (e) { // Do nothing } } return data; } }
alekitto/atlante-js
lib/Requester/Decorator/Authentication/OAuth/TokenPasswordAuthenticator.ts
import ClientTokenAuthenticator, { ClientTokenAuthenticatorConfiguration } from './ClientTokenAuthenticator'; import InvalidResponse from '../../../Response/InvalidResponse'; import NoTokenAvailableException from '../../../../Exception/NoTokenAvailableException'; import { RequesterInterface } from '../../../RequesterInterface'; import { ResponseInterface } from '../../../Response/ResponseInterface'; import { StorageInterface } from '../../../../Storage/StorageInterface'; import { TokenResponseDataInterface } from './TokenResponseDataInterface'; interface TokenPasswordAuthenticatorConfiguration extends ClientTokenAuthenticatorConfiguration { access_token_key?: string; refresh_token_key?: string; id_token_key?: string; } export default class TokenPasswordAuthenticator extends ClientTokenAuthenticator { protected _accessTokenKey: string; protected _idTokenKey: string; private readonly _refreshTokenKey: string; /** * Constructor. */ constructor( requester: RequesterInterface, tokenStorage: StorageInterface, { token_endpoint, client_id, client_secret = undefined, client_token_key = undefined, data_encoding = undefined, access_token_key = 'access_token', refresh_token_key = 'refresh_token', id_token_key = 'id_token', }: TokenPasswordAuthenticatorConfiguration ) { super(requester, tokenStorage, { token_endpoint, client_id, client_secret, client_token_key, data_encoding }); this._accessTokenKey = access_token_key; this._idTokenKey = id_token_key; this._refreshTokenKey = refresh_token_key; } /** * Authenticates user. */ authenticate(username: string, password: string): Promise<string> { this._tokenPromise = (async () => { const request = this._buildTokenRequest({ grant_type: 'password', username, password, }); const response = await this._request(request.body, request.headers.all); await this._storeTokenFromResponse(response); return response.getData<TokenResponseDataInterface>().access_token; })(); return this.token; } /** * Logs user out. */ async logout(): Promise<void> { await this._tokenStorage.deleteItem(this._accessTokenKey); await this._tokenStorage.deleteItem(this._refreshTokenKey); if (this._idTokenKey) { await this._tokenStorage.deleteItem(this._idTokenKey); } } /** * Request a token. */ protected async _getToken(): Promise<string> { const item = await this._tokenStorage.getItem(this._accessTokenKey); if (item.isHit) { return item.get(); } const refreshed = await this._refreshToken(); if (null === refreshed) { return await super._getToken(); } return refreshed; } /** * Tries to refresh a token. Returns a string if refresh succeeded. */ protected async _refreshToken(): Promise<string|null> { const refreshItem = await this._tokenStorage.getItem('refresh_token'); if (! refreshItem.isHit) { return null; } const request = this._buildTokenRequest({ grant_type: 'refresh_token', refresh_token: refreshItem.get(), }); const response = await this._request(request.body, request.headers.all); await this._storeTokenFromResponse(response, 'refresh'); return response.getData<TokenResponseDataInterface>().access_token; } /** * Stores the access/refresh tokens from response. */ protected async _storeTokenFromResponse(response: ResponseInterface, requestType: 'request' | 'refresh' = 'request'): Promise<void> { const item = await this._tokenStorage.getItem(this._accessTokenKey); const refreshItem = await this._tokenStorage.getItem(this._refreshTokenKey); if (response instanceof InvalidResponse) { throw new NoTokenAvailableException(`Token ${requestType} responded with status ${response.getStatusCode()}`); } const content = response.getData<TokenResponseDataInterface>(); item.set(content.access_token); item.expiresAfter(content.expires_in - 60); await this._tokenStorage.save(item); if (content.refresh_token) { refreshItem.set(content.refresh_token); await this._tokenStorage.save(refreshItem); } if (content.id_token) { const idItem = await this._tokenStorage.getItem(this._idTokenKey); idItem.set(content.id_token); await this._tokenStorage.save(idItem); } } }
alekitto/atlante-js
lib/Storage/AbstractStorage.ts
<gh_stars>1-10 import Storage, { StorageInterface } from './StorageInterface'; import Item from './Item'; import { ItemInterface } from './ItemInterface'; import JSONMarshaller from './Marshaller/JSONMarshaller'; import { MarshallerInterface } from './Marshaller/MarshallerInterface'; export default abstract class AbstractStorage extends implementationOf(Storage) implements StorageInterface { public marshaller: MarshallerInterface; private readonly _createItem: (key: string, value: any, isHit: boolean) => ItemInterface; constructor(defaultLifetime?: number) { super(); /** * Create a cache item for the current adapter. */ this._createItem = (key, value, isHit) => { const item: any = new Item(); item._key = key; item._value = value; item._isHit = isHit; item._defaultLifetime = defaultLifetime; return item; }; /** * @type {MarshallerInterface} */ this.marshaller = new JSONMarshaller(); } /** * @inheritdoc */ async getItem(key: string): Promise<ItemInterface> { let value; let isHit = await this.hasItem(key); try { if (! isHit || 'undefined' === (value = await this._getItem(key))) { value = undefined; } else if (undefined === (value = this.marshaller.unmarshall(value))) { value = undefined; isHit = false; } } catch (e) { console.warn('Failed to unserialize key "' + key + '"'); value = undefined; isHit = false; } return this._createItem(key, value, isHit); } /** * @inheritdoc */ abstract hasItem(key: string): Promise<boolean>; /** * @inheritdoc */ async clear(): Promise<boolean> { return false; } /** * @inheritdoc */ abstract deleteItem(key: string): Promise<boolean>; /** * @inheritdoc */ async save(item: ItemInterface): Promise<boolean> { const key = (item as any)._key; let value = (item as any)._value; let expiry = (item as any)._expiry; if (expiry && expiry <= ~~(new Date().getTime() / 1000)) { await this.deleteItem(key); return true; } try { value = this.marshaller.marshall(value); if (undefined === value) { value = 'undefined'; } } catch (e) { console.warn(`Failed to save key "${key}" (${typeof value})`); return false; } if (undefined === expiry && 0 < (item as any)._defaultLifetime) { expiry = new Date().setTime(new Date().getTime() + ((item as any)._defaultLifetime * 1000)); } else if (undefined === expiry) { expiry = null; } return await this._save(key, value, expiry); } /** * Gets an item from the storage, if not expired. */ protected abstract _getItem(key: string): Promise<string>; /** * Stores an item into the storage. */ protected abstract _save(key: string, value: string, expiry: Date): Promise<boolean>; }
alekitto/atlante-js
lib/Requester/Decorator/VersionSetterDecorator.ts
<gh_stars>1-10 import Decorator, { DecoratorInterface } from './DecoratorInterface'; import Accept from '../Header/Accept'; import Request from '../Request'; export default class VersionSetterDecorator extends implementationOf(Decorator) implements DecoratorInterface { private readonly _version: string; /** * Constructor. */ constructor(version: string) { super(); this._version = version; } /** * Decorates the request. */ decorate(request: Request<any>): Request<any> { const { body = undefined, method, url, headers } = request; const header = headers.get('Accept') ?? new Accept('application/json'); header.setParameter('version', this._version); headers.set('Accept', header); return { body, method, url, headers }; } }
alekitto/atlante-js
lib/Exception/NotFoundException.ts
import AbstractException from './AbstractException'; import NotFoundResponse from '../Requester/Response/NotFoundResponse'; export default class NotFoundException extends AbstractException { constructor(response?: NotFoundResponse) { super(response); } get response(): NotFoundResponse { return super.response as NotFoundResponse; } }
alekitto/atlante-js
integrations/angular/public-api.ts
export * from './atlante.module'; export * from './requester'; export * from './response-factory';
alekitto/atlante-js
lib/Requester/Header/Accept.ts
import BaseAccept from './BaseAccept'; export default class Accept extends BaseAccept { private readonly _basePart: string; private readonly _subPart: string; /** * Constructor. */ constructor(value: string) { super(value); if ('*' === this._type) { this._type = '*/*'; } const parts = this._type.split('/'); if (2 !== parts.length || ! parts[0] || ! parts[1]) { throw new Error('Invalid media type'); } this._basePart = parts[0]; this._subPart = parts[1]; } get subPart(): string { return this._subPart; } get basePart(): string { return this._basePart; } }
alekitto/atlante-js
lib/Http/Client.ts
import Interface, { ClientInterface } from './ClientInterface'; import AccessDeniedException from '../Exception/AccessDeniedException'; import AccessDeniedResponse from '../Requester/Response/AccessDeniedResponse'; import BadRequestException from '../Exception/BadRequestException'; import BadResponse from '../Requester/Response/BadResponse'; import { DecoratorInterface } from '../Requester/Decorator/DecoratorInterface'; import Headers from '../Requester/Headers'; import InvalidRequestException from '../Exception/InvalidRequestException'; import InvalidResponse from '../Requester/Response/InvalidResponse'; import NotFoundException from '../Exception/NotFoundException'; import NotFoundResponse from '../Requester/Response/NotFoundResponse'; import Request from '../Requester/Request'; import { RequesterInterface } from '../Requester/RequesterInterface'; import { ResponseInterface } from '../Requester/Response/ResponseInterface'; export default class Client extends implementationOf(Interface) implements ClientInterface { protected _decorators: DecoratorInterface[]; protected _requester: RequesterInterface; /** * Constructor. * * @param requester Object which performs http requests. * @param [requestDecorators = []] Decorators to apply to the request. */ constructor(requester: RequesterInterface, requestDecorators?: DecoratorInterface[]) { super(); this._requester = requester; this._decorators = requestDecorators; } /** * @inheritdoc */ get(path: string, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { return this.request('GET', path, null, headers); } /** * @inheritdoc */ post(path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { return this.request('POST', path, requestData, headers); } /** * @inheritdoc */ put(path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { return this.request('PUT', path, requestData, headers); } /** * @inheritdoc */ patch(path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { return this.request('PATCH', path, requestData, headers); } /** * @inheritdoc */ async request(method: string, path: string, requestData?: any, headers?: Record<string, string> | Headers): Promise<ResponseInterface> { if ('GET' === method || 'HEAD' === method || 'DELETE' === method) { requestData = undefined; } if (! (headers instanceof Headers)) { headers = new Headers(headers); } headers.set('Accept', 'application/json'); let request: Request = { body: requestData, method, url: path, headers, }; for (const decorator of this._decorators) { request = await decorator.decorate(request); } const response = await this._requester.request(request.method, request.url, request.headers.all, request.body); this._filterResponse(response); return response; } /** * Filters a response, eventually throwing an error in case response status is not successful. */ protected _filterResponse(response: ResponseInterface): void { switch (true) { case response instanceof BadResponse: throw new BadRequestException(response as BadResponse); case response instanceof AccessDeniedResponse: throw new AccessDeniedException(response as AccessDeniedResponse); case response instanceof NotFoundResponse: throw new NotFoundException(response as NotFoundResponse); case response instanceof InvalidResponse: throw new InvalidRequestException(response as InvalidResponse); } } }
alekitto/atlante-js
lib/Storage/Marshaller/NullMarshaller.ts
<gh_stars>1-10 import Marshaller, { MarshallerInterface } from './MarshallerInterface'; export default class NullMarshaller extends implementationOf(Marshaller) implements MarshallerInterface { /** * @inheritdoc */ marshall(value: any): string { return value.toString(); } /** * @inheritdoc */ unmarshall(value: string): any { return value; } }
alekitto/atlante-js
lib/Requester/HttpMessage.ts
import Headers from './Headers'; export default interface HttpMessage<T = any> { readonly headers: Headers; }
alekitto/atlante-js
lib/Requester/Response/ResponseInterface.ts
<filename>lib/Requester/Response/ResponseInterface.ts import Headers from '../Headers'; export interface ResponseInterface {} export class ResponseInterface { /** * Returns the API response content. */ getData<T>(): T; // @ts-ignore getData(): unknown[] | Record<string, unknown> | string { } /** * Gets the HTTP headers received in the response. */ // @ts-ignore getHeaders(): Headers { } /** * Gets the HTTP status code of the response. */ // @ts-ignore getStatusCode(): number { } } export default getInterface(ResponseInterface);
alekitto/atlante-js
lib/Requester/Decorator/DecoratorInterface.ts
import Request from '../Request'; export class DecoratorInterface { /** * Decorates the request object adding/removing headers, * authenticating the request, etc. */ // @ts-ignore decorate<T = any>(request: Request<T>): Request<T> | Promise<Request<T>> { } } export interface DecoratorInterface {} export default getInterface(DecoratorInterface);
alekitto/atlante-js
lib/Requester/Headers.ts
<reponame>alekitto/atlante-js import Accept from './Header/Accept'; import BaseAccept from './Header/BaseAccept'; export default class Headers { private _headers: Record<string, (string | Accept)[]> = {}; private _headersName: Record<string, string> = {}; /** * Constructor. */ constructor(headers: Record<string, string|string[]> | Headers = null) { if (headers instanceof Headers) { return headers; } if (null !== headers) { for (const [ key, value ] of Object.entries(headers)) { this.set(key, value); } } } /** * Sets an header. */ set(name: 'Accept', value: string | Accept): this; set(name: string, value: string | Accept | string[]): this; set(name: string, value: string | Accept | string[]): this { const lowerName = name.toLowerCase(); if ('accept' === lowerName && ! (value instanceof Accept)) { value = new Accept('string' === typeof value ? value : value[0]); } if (value instanceof BaseAccept && ! lowerName.startsWith('accept')) { throw new Error('Cannot set accept to non-Accept header'); } this._headers[lowerName] = Array.isArray(value) ? value : [ value ]; this._headersName[lowerName] = name; return this; } /** * Gets an header by name. */ get(name: 'Accept'): Accept | undefined; get(name: string): string | string[] | undefined; get(name: string): string | Accept | (string | Accept)[] | undefined { if (! this.has(name)) { return undefined; } const lowerName = name.toLowerCase(); const hdr = this._headers[lowerName]; return 1 === hdr.length ? hdr[0] : hdr; } /** * Checks whether an header is present. */ has(name: string): boolean { return Object.prototype.hasOwnProperty.call(this._headers, name.toLowerCase()); } /** * Removes an header. */ remove(name: string): this { const lowerName = name.toLowerCase(); delete this._headers[lowerName]; delete this._headersName[lowerName]; return this; } /** * Adds an header. */ add(name: 'Accept', value: string | Accept): Headers; add(name: string, value: string | Accept | string[]): Headers; add(name: string, value: string | Accept | string[]): Headers { if (! this.has(name)) { return this.set(name, value); } const lowerName = name.toLowerCase(); if ('accept' === lowerName && ! (value instanceof Accept)) { value = new Accept('string' === typeof value ? value : value[0]); } if (value instanceof BaseAccept) { return this.set(name, value); } value = ! Array.isArray(value) ? [ value ] : value; this._headers[lowerName] = [ ...this._headers[lowerName], ...value ]; return this; } get all(): Record<string, string | string[]> { const headers: Record<string, string | string[]> = {}; for (const name of Object.keys(this._headersName)) { const headerName = this._headersName[name]; let header: unknown = this._headers[name]; if (isArray(header) && 1 === header.length) { header = header[0].toString(); } headers[headerName] = isArray(header) ? header.map(String) : String(header); } return headers; } }
alekitto/atlante-js
lib/Requester/Response/XhrResponseFactory.ts
<filename>lib/Requester/Response/XhrResponseFactory.ts import AbstractResponseFactory from './AbstractResponseFactory'; import Headers from '../Headers'; import { ResponseInterface } from './ResponseInterface'; export default class XhrResponseFactory extends AbstractResponseFactory { fromResponse(response: XMLHttpRequest): ResponseInterface { const headers = response.getAllResponseHeaders() .split('\r\n') .reduce((res, val) => { if (! val) { return res; } const vals = val.split(': '); return res.add(vals[0], vals[1]); }, new Headers()) ; return this.makeResponse(response.responseText, headers, response.status); } }
alekitto/atlante-js
lib/Requester/Response/BadResponsePropertyTree.ts
/** * @final */ export default class BadResponsePropertyTree { private name: string; private errors: string[] = []; private children: BadResponsePropertyTree[] = []; static parse(content: Record<string, any> | string): BadResponsePropertyTree { const obj = new BadResponsePropertyTree(); if (isString(content)) { throw new InvalidArgumentException('Unexpected response type, object or array expected, string given'); } const errors = content.errors ?? null; if (null === errors) { throw new InvalidArgumentException('Unable to parse missing `errors` property'); } if (! Array.isArray(errors)) { throw new InvalidArgumentException(`Invalid \`errors\` property type, expected array, ${typeof errors} given`); } obj.errors = errors; const name = content.name ?? null; if (null === name) { throw new InvalidArgumentException('Missing `name` property'); } if (! isString(name)) { throw new InvalidArgumentException(`Invalid \`name\` property type, expected string, ${typeof name} given`); } obj.name = name; const children = content.children ?? []; if (! Array.isArray(children)) { throw new InvalidArgumentException(`Invalid \`children\` property type, expected array, ${typeof children} given`); } obj.children = children.map(BadResponsePropertyTree.parse); return obj; } getName(): string { return this.name; } getErrors(): string[] { return this.errors; } getChildren(): BadResponsePropertyTree[] { return this.children; } /** * @internal Use static `parse` method instead */ private constructor() { } }
alekitto/atlante-js
lib/Requester/Response/ResponseFactoryInterface.ts
import { ResponseInterface } from './ResponseInterface'; export interface ResponseFactoryInterface {} export class ResponseFactoryInterface { // @ts-ignore fromResponse(response: any): ResponseInterface { } } export default getInterface(ResponseFactoryInterface);
alekitto/atlante-js
lib/Storage/ChainStorage.ts
<reponame>alekitto/atlante-js import Storage, { StorageInterface } from './StorageInterface'; import { ItemInterface } from './ItemInterface'; export default class ChainStorage extends implementationOf(Storage) implements StorageInterface { private readonly _storages: StorageInterface[]; /** * Constructor. */ constructor(storages?: StorageInterface[]) { super(); this._storages = storages; } /** * Adds a storage to the chain. */ addStorage(storage: StorageInterface): void { this._storages.push(storage); } /** * @inheritdoc */ async getItem(key: string): Promise<ItemInterface> { let item; for (const storage of this._storages) { try { item = await storage.getItem(key); if (! item.isHit) { continue; } break; } catch (e) { // Continue to the next storage. } } if (undefined === item) { throw new Error('No available storage.'); } return item; } /** * @inheritdoc */ async hasItem(key: string): Promise<boolean> { for (const storage of this._storages) { try { if (await storage.hasItem(key)) { return true; } } catch (e) { // Continue to the next storage. } } return false; } /** * @inheritdoc */ clear(): Promise<boolean> { return this._call('clear'); } /** * @inheritdoc */ deleteItem(key: string): Promise<boolean> { return this._call('deleteItem', key); } /** * @inheritdoc */ save(item: ItemInterface): Promise<boolean> { return this._call('save', item); } /** * Chain-call storages. */ private async _call(method: 'clear' | 'deleteItem' | 'save', ...args: any[]): Promise<any> { for (const storage of this._storages) { try { // @ts-ignore return await storage[method](...args); } catch (e) { // Continue to the next storage. } } throw new Error('No available storage.'); } }
alekitto/atlante-js
lib/Requester/Response/NotFoundResponse.ts
import Headers from '../Headers'; import InvalidResponse from './InvalidResponse'; export default class NotFoundResponse extends InvalidResponse { public static readonly HTTP_STATUS = 404; constructor(headers: Headers, data: unknown) { super(NotFoundResponse.HTTP_STATUS, headers, data); } }
alekitto/atlante-js
lib/Exception/NoTokenAvailableException.ts
<gh_stars>0 export default class NoTokenAvailableException extends Error { }
alekitto/atlante-js
lib/Requester/Response/AccessDeniedResponse.ts
<reponame>alekitto/atlante-js import Headers from '../Headers'; import InvalidResponse from './InvalidResponse'; export default class AccessDeniedResponse extends InvalidResponse { public static readonly HTTP_STATUS = 403; constructor(headers: Headers, data: unknown) { super(AccessDeniedResponse.HTTP_STATUS, headers, data); } }
alekitto/atlante-js
lib/Requester/RequesterInterface.ts
import { ResponseInterface } from './Response/ResponseInterface'; export interface RequesterInterface { } export class RequesterInterface { /** * Performs a request. * Returns a response with parsed data, if no error is present. */ // @ts-ignore request(method: string, path: string, headers?: any, requestData?: any): Promise<ResponseInterface> { } } export default getInterface(RequesterInterface);
alekitto/atlante-js
lib/Storage/Marshaller/JSONMarshaller.ts
import Marshaller, { MarshallerInterface } from './MarshallerInterface'; export default class JSONMarshaller extends implementationOf(Marshaller) implements MarshallerInterface { /** * @inheritdoc */ marshall(value: any): string { return JSON.stringify(value); } /** * @inheritdoc */ unmarshall(value: string): unknown { return JSON.parse(value); } }
alekitto/atlante-js
lib/Requester/Decorator/Authentication/OAuth/TokenResponseDataInterface.ts
<reponame>alekitto/atlante-js export interface TokenResponseDataInterface { access_token: string; expires_in: number; refresh_token?: string; id_token?: string; }
good-monday/interview-ts
src/chart.ts
<gh_stars>0 import * as asciichart from 'asciichart' import chalk from 'chalk' type Lines = Record<string, number[]> export default function chart(lines: Lines) { const legends = Object.keys(lines) const values = Object.values(lines) const legendColors = [chalk.bgBlue, chalk.bgGreen, chalk.bgYellow, chalk.bgCyan] const chartColors = [asciichart.blue, asciichart.green, asciichart.yellow, asciichart.cyan] const config = { height: 65, colors: chartColors.slice(0, legends.length) } let legendOutput = "" for (let i = 0; i < legends.length; i++) { const color = legendColors[i] legendOutput = legendOutput + color(" " + legends[i] + " ") } console.log(legendOutput + "\n") console.log( asciichart.plot(values, config) ) }
fangqk1991/node-model
tests/ModelMainEx.ts
import { FCModel } from '../src' import ModelSubEx from './ModelSubEx' export default class ModelMainEx extends FCModel { public xyy: any public xxxYYY: any public subObj: any public subItems: any public noGiven: any fc_propertyMapper(): { [p: string]: string } { return { xyy: 'xyy', xxxYYY: 'xxx_yyy', subObj: 'sub_obj', subItems: 'sub_items', noGiven: 'no_given', } } fc_propertyClassMapper(): { [p: string]: { new (): FCModel } } { return { subObj: ModelSubEx, } } fc_arrayItemClassMapper(): { [p: string]: { new (): FCModel } } { return { subItems: ModelSubEx, } } }
fangqk1991/node-model
tests/FCModel.test.ts
import ModelMainEx from './ModelMainEx' import ModelSubEx from './ModelSubEx' import * as assert from 'assert' import { DiffMapper } from '@agora-lab/tools' const getTestData = () => { return { xyy: 1, xxx_yyy: 'hehehe', xxx: 'ttt', sub_obj: { name: 'Sub - Obj', }, sub_items: [{ name: 'Sub - Obj - 1', nick_name: 'xxx 123' }, { name: 'Sub - Obj - 2' }, { name: 'Sub - Obj - 3' }], } } describe('Test FCModel', (): void => { it(`Test Normal`, (): void => { const data = getTestData() const obj = new ModelMainEx() obj.fc_generate(data) assert.ok(obj.xyy === data['xyy']) assert.ok(obj.xxxYYY === data['xxx_yyy']) assert.ok(obj.subObj instanceof ModelSubEx && obj.subObj.name === data['sub_obj']['name']) assert.ok(Array.isArray(obj.subItems) && obj.subItems.length === data['sub_items'].length) const retMap = obj.fc_retMap() assert.ok(retMap['xyy'] === data['xyy']) assert.ok(retMap['xxx_yyy'] === data['xxx_yyy']) assert.ok(!retMap['xxx']) const pureModel = obj.fc_pureModel() assert.ok(pureModel['xyy'] === data['xyy']) assert.ok(pureModel['xxxYYY'] === data['xxx_yyy']) assert.ok(!pureModel['xxx']) console.info(obj) console.info(pureModel) }) it(`Test Modify Generate`, (): void => { const obj = new ModelMainEx() obj.fc_generate({}) Object.keys(obj.fc_propertyMapper()).forEach((key) => { const _obj = obj as any assert.ok(_obj[key] === undefined) }) obj.fc_generate({ a: 1, xyy: 2 }) assert.equal(obj.xyy, 2) assert.equal('a' in obj, false) }) it(`Test fc_generateWithModel`, (): void => { const data = getTestData() const obj = new ModelMainEx() obj.fc_generate(data) const obj2 = new ModelMainEx() obj2.fc_generateWithModel(obj) assert.ok(DiffMapper.checkEquals(obj, obj2)) }) })
fangqk1991/node-model
src/FCModel.ts
<reponame>fangqk1991/node-model interface MapProtocol { [p: string]: any } export class FCModel implements MapProtocol { /** * @description It will be executed in constructor */ fc_defaultInit(): void {} fc_afterGenerate(_data: MapProtocol = {}): void {} /** * @description Mapping table for (class-property => data-json-key) */ fc_propertyMapper(): { [p: string]: string } { throw new Error(`You must override the perform method.`) } constructor() { const _this = this as any const propertyList = Object.keys(this.fc_propertyMapper()) propertyList.forEach((property: string) => { _this[property] = undefined }) this.fc_defaultInit() } /** * @description Pass json data to build properties of the instance. * @param data */ public fc_generate(data: MapProtocol): void { this._generate(data, false) } /** * @description Pass model data to build properties of the instance. * @param data */ public fc_generateWithModel(data: MapProtocol): void { this._generate(data, true) } private _generate(data: MapProtocol, forProperties: boolean = false): void { const propertyMap = this.fc_propertyMapper() const propertyClassMap = this.fc_propertyClassMapper() const itemClassMap = this.fc_arrayItemClassMapper() for (const property in propertyMap) { const targetKey = forProperties ? property : propertyMap[property] if (property in propertyClassMap && data[targetKey] !== null && typeof data[targetKey] === 'object') { const obj = new propertyClassMap[property]() if (obj instanceof FCModel) { obj._generate(data[targetKey], forProperties) const _this = this as MapProtocol _this[property] = obj } } else if (property in itemClassMap && Array.isArray(data[targetKey])) { const arr: any[] = [] data[targetKey].forEach((dic: {}): void => { const obj = new itemClassMap[property]() if (obj instanceof FCModel) { obj._generate(dic, forProperties) arr.push(obj) } else { arr.push(null) } }) const _this = this as MapProtocol _this[property] = arr } else { const _this = this as MapProtocol if (targetKey in data) { _this[property] = data[targetKey] } else { if (!(property in _this)) { _this[property] = undefined } } } } this.fc_afterGenerate(data) } private _encode(forProperties: boolean = false) { const propertyMap = this.fc_propertyMapper() const propertyClassMap = this.fc_propertyClassMapper() const itemClassMap = this.fc_arrayItemClassMapper() const data: MapProtocol = {} for (const property in propertyMap) { const targetKey = forProperties ? property : propertyMap[property] if (property in this) { const entity = (this as MapProtocol)[property] if (property in propertyClassMap && entity instanceof FCModel) { data[targetKey] = forProperties ? entity.fc_pureModel() : entity.fc_encode() } else if (property in itemClassMap && Array.isArray(entity)) { data[targetKey] = entity.map((item): {} => { return forProperties ? item.fc_pureModel() : item.fc_encode() }) } else { data[targetKey] = entity } } } return data } /** * @description Export JSON data, keys as fc_propertyMapper()'s values */ public fc_encode(): MapProtocol { return this._encode(false) } /** * @description Export pure model data, keys as fc_propertyMapper()'s keys */ public fc_pureModel(): MapProtocol { return this._encode(true) } /** * @deprecated * @description Same as fc_encode */ public fc_retMap(): MapProtocol { return this.fc_encode() } /** * @description If some property is FCModel's sub class instance, declare the class in this mapper. */ public fc_propertyClassMapper(): { [p: string]: { new (): FCModel } } { return {} } /** * @description If some property is an array of FCModel's sub class instance, declare the class in this mapper. */ public fc_arrayItemClassMapper(): { [p: string]: { new (): FCModel } } { return {} } public toString() { return JSON.stringify(this.fc_pureModel(), null, 2) } }
fangqk1991/node-model
tests/ModelSubEx.ts
import { FCModel } from '../src' export default class ModelSubEx extends FCModel { public name: any public nickName: any fc_propertyMapper(): { [p: string]: string } { return { name: 'name', nickName: 'nick_name', } } }
fangqk1991/node-model
src/index.ts
<reponame>fangqk1991/node-model export * from './FCModel'
LocusSolutions/coverage-action
src/CoverageSummary.ts
<gh_stars>0 /* eslint-disable @typescript-eslint/no-explicit-any */ interface ICodeCoverageSummary { assemblies: number assembliesDelta: number classes: number classesDelta: number files: number filesDelta: number coveredlines: number coveredlinesDelta: number uncoveredlines: number uncoveredlinesDelta: number coverablelines: number coverablelinesDelta: number totallines: number totallinesDelta: number linecoverage: number linecoverageDelta: number coveredbranches: number coveredbranchesDelta: number totalbranches: number totalbranchesDelta: number branchcoverage: number branchcoverageDelta: number } function getCorrectSign(value: number): string { if (value > 0) return '+' return '' } export async function GetCoverageSummary(target: any, current: any): Promise<ICodeCoverageSummary> { if (target == null) { target = { assemblies: 0, assembliesDelta: 0, classes: 0, classesDelta: 0, files: 0, filesDelta: 0, coveredlines: 0, coveredlinesDelta: 0, uncoveredlines: 0, uncoveredlinesDelta: 0, coverablelines: 0, coverablelinesDelta: 0, totallines: 0, totallinesDelta: 0, linecoverage: 0, linecoverageDelta: 0, coveredbranches: 0, coveredbranchesDelta: 0, totalbranches: 0, totalbranchesDelta: 0, branchcoverage: 0, branchcoverageDelta: 0 } as ICodeCoverageSummary } const assembliesDelta = current.summary.assemblies - target.summary.assemblies const classesDelta = current.summary.classes - target.summary.classes const filesDelta = current.summary.files - target.summary.files const coveredlinesDelta = current.summary.coveredlines - target.summary.coveredlines const uncoveredlinesDelta = current.summary.uncoveredlines - target.summary.uncoveredlines const coverablelinesDelta = current.summary.coverablelines - target.summary.coverablelines const totallinesDelta = current.summary.totallines - target.summary.totallines const linecoverageDelta = current.summary.linecoverage - target.summary.linecoverage const coveredbranchesDelta = current.summary.coveredbranches - target.summary.coveredbranches const totalbranchesDelta = current.summary.totalbranches - target.summary.totalbranches const branchcoverageDelta = current.summary.branchcoverage - target.summary.branchcoverage return { assemblies: current.summary.assemblies, assembliesDelta, classes: current.summary.classes, classesDelta, files: current.summary.files, filesDelta, coveredlines: current.summary.coveredlines, coveredlinesDelta, uncoveredlines: current.summary.uncoveredlines, uncoveredlinesDelta, coverablelines: current.summary.coverablelines, coverablelinesDelta, totallines: current.summary.totallines, totallinesDelta, linecoverage: current.summary.linecoverage, linecoverageDelta, coveredbranches: current.summary.coveredbranches, coveredbranchesDelta, totalbranches: current.summary.totalbranches, totalbranchesDelta, branchcoverage: current.summary.branchcoverage, branchcoverageDelta } as ICodeCoverageSummary } export async function CreateCoverageSummary(coverage: ICodeCoverageSummary): Promise<string> { /* prettier-ignore */ return ` | Type | Current coverage | Delta from HEAD | |---|---|---:| | Assemblies | ${coverage.assemblies} | ${getCorrectSign(coverage.assembliesDelta)}${coverage.assembliesDelta} | | Classes | ${coverage.classes} | ${getCorrectSign(coverage.classesDelta)}${coverage.classesDelta} | | Files | ${coverage.files} | ${getCorrectSign(coverage.filesDelta)}${coverage.filesDelta} | | Covered Lines | ${coverage.coveredlines} | ${getCorrectSign(coverage.coveredlinesDelta)}${coverage.coveredlinesDelta} | | Uncovered Lines | ${coverage.uncoveredlines} | ${getCorrectSign(coverage.uncoveredlinesDelta)}${coverage.uncoveredlinesDelta} | | Coverable Lines | ${coverage.coverablelines} | ${getCorrectSign(coverage.coverablelinesDelta)}${coverage.coverablelinesDelta} | | Total Lines | ${coverage.totallines} | ${getCorrectSign(coverage.totallinesDelta)}${coverage.totallinesDelta} | | Line Coverage | ${coverage.linecoverage}% | ${getCorrectSign(coverage.linecoverageDelta)} ${coverage.linecoverageDelta.toFixed(2)}% | | Covered Branches | ${coverage.coveredbranches} | ${getCorrectSign(coverage.coveredbranchesDelta)}${coverage.coveredbranchesDelta} | | Total Branches | ${coverage.totalbranches} | ${getCorrectSign(coverage.totalbranchesDelta)}${coverage.totalbranchesDelta} | | Branch Coverage | ${coverage.branchcoverage}% | ${getCorrectSign(coverage.branchcoverageDelta)}${coverage.branchcoverageDelta.toFixed(2)}% | ` }
LocusSolutions/coverage-action
src/main.ts
import * as github from '@actions/github' import * as core from '@actions/core' import * as fs from 'fs' import {CreateCoverageSummary, GetCoverageSummary} from './CoverageSummary' async function run(): Promise<void> { try { let targetBranchRunOutput = null let currentBranchRunOutput = null /* Setup inputs */ const token = core.getInput('REPO_TOKEN') const title = core.getInput('TITLE') const sha = core.getInput('SHA') const currentSummaryFile = core.getInput('CURRENT_SUMMARY_PATH') const targetSummaryFile = core.getInput('TARGET_SUMMARY_PATH') const octokit = github.getOctokit(token) /* Parse target branch summary */ const currentBranchSummaryContent = fs.readFileSync(currentSummaryFile, 'utf-8').trim() if (currentBranchSummaryContent.length > 0) { currentBranchRunOutput = JSON.parse(currentBranchSummaryContent) } else { throw new Error('No current branch summary found') } /* Parse current branch summary */ const targetBranchSummaryContent = fs.readFileSync(targetSummaryFile, 'utf-8').trim() if (targetBranchSummaryContent.length > 0) { targetBranchRunOutput = JSON.parse(targetBranchSummaryContent) } /* Create coverage output */ try { const coverage = await GetCoverageSummary(targetBranchRunOutput, currentBranchRunOutput) const coverageSummary = await CreateCoverageSummary(coverage) /* Create status-check result */ const payload = { owner: github.context.repo.owner, repo: github.context.repo.repo, name: title, head_sha: sha, status: 'completed', conclusion: coverage.linecoverageDelta >= 0 ? 'success' : 'neutral', output: { title: `Coverage is ${coverage.linecoverageDelta >= 0 ? 'up' : 'down'} by ${Math.abs(coverage.linecoverageDelta).toFixed(2)}% (${coverage.linecoverage.toFixed(2)}%)`, summary: `If this branch is merged, coverage will go ${coverage.linecoverageDelta >= 0 ? 'up' : 'down'} by ${Math.abs(coverage.linecoverageDelta).toFixed(2)}% `, text: coverageSummary // text: } } const response = await octokit.checks.create(payload) if (response.status !== 201) { throw new Error(`Failed to create status check. Error code: ${response.status}`) } else { core.info(`Created check successfully:'${payload.output.title}'`) } } catch (err) { core.info(`Error: ${err}`) } } catch (error) { core.setFailed(error.message) } } run()
LocusSolutions/coverage-action
__tests__/main.test.ts
<reponame>LocusSolutions/coverage-action import {GetCoverageSummary} from '../src/CoverageSummary' import * as fs from 'fs' test('get code coverage', async () => { /* const mainBranchRun = fs.readFileSync('MainRun.json', 'utf-8') const mainBranchRunOutput = JSON.parse(mainBranchRun.trim()) const currentRun = fs.readFileSync('Summary.json', 'utf-8') const currentRunOutput = JSON.parse(currentRun.trim()) console.log(await GetCoverageSummary(mainBranchRunOutput, currentRunOutput)) */ })
damingerdai/qhttp
src/http.ts
<gh_stars>0 import request from 'request'; import { Model, Method } from './model'; /** * http服务接口 */ interface IHttpService { /** * 发送get请求 * @param url 请求连接 * @param data 数据 * @param header 请求头 */ get<T>(url: string, data: Model<string>, header: Model<string>): Promise<T>; /** * 发送post请求 * @param url 请求连接 * @param data 数据 * @param header 请求头 */ post<T>(url: string, data: Model<string>, header: Model<string>): Promise<T>; /** * 发送put请求 * @param url 请求连接 * @param data 数据 * @param header 请求头 */ put<T>(url: string, data: Model<string>, header: Model<string>): Promise<T>; /** * 发送delte请求 * @param url 请求连接 * @param header 请求头 */ delete<T>(url: string, header: Model<string>): Promise<T>; /** * 发送http请求 * @param method 请求方法 * @param url 请求的连接 * @param data 请求体数据 * @param params 请求数据 * @param header 请求体 */ http<T>(method: Method, url: string, data: Model<string>, params: Model<string>, header: Model<string>): Promise<T>; } export class HttpService implements IHttpService { get<T>(url: string, data: Model<string>, header: Model<string>): Promise<T> { return this.http('get', url, {}, data, header); } post<T>(url: string, data: Model<string>, header: Model<string>): Promise<T> { return this.http('post', url, data, {}, header); } put<T>(url: string, data: Model<string>, header: Model<string>): Promise<T> { return this.http('put', url, data, {}, header); } delete<T>(url: string, header: Model<string>): Promise<T> { return this.http('delete', url, {}, {}, header); } http<T>(method: Method, url: string, data: Model<string>, params: Model<string>, headers: Model<string>): Promise<T> { const promise = (resolve: (value: T) => void, reject: (error: any) => void) => { request({ method: method, url: url, headers: headers || {}, qs: params || {}, body: data || {}, json: true }, (error: any, response: { statusCode: number; }, body: T) => { if (!error && response.statusCode == 200) { resolve(body as T); } else { reject(error || 'http error'); } }); } return new Promise(promise); } }
damingerdai/qhttp
src/model.ts
<reponame>damingerdai/qhttp<filename>src/model.ts export interface Model<T> { [key: string]: T; } export type Method = 'get' | 'post' | 'put' | 'delete';
Emeshka/graphytica
src/app/switch-true-false/switch-true-false.component.ts
import { Component, OnInit, Output, EventEmitter, Input, SimpleChanges } from '@angular/core'; @Component({ selector: 'switch-true-false', templateUrl: './switch-true-false.component.html', styleUrls: ['./switch-true-false.component.css'] }) export class SwitchTrueFalseComponent implements OnInit { constructor() { } @Input() firstValue: any = ''; currentValue: any = ''; @Output() value = new EventEmitter<any>(); @Input() title: any = ''; setValue(value) { this.currentValue = value; //console.log('switch-true-false: set current value', this.currentValue) this.value.emit(value); } ngOnChanges(changes: SimpleChanges) { if (changes.firstValue) { //console.log('switch-true-false ngOnChanges firstValue', changes.firstValue.currentValue) if (changes.firstValue.currentValue === false || changes.firstValue.currentValue === true) { this.currentValue = changes.firstValue.currentValue; } else this.currentValue = ''; } } ngOnInit(): void { //console.log('switch-true-false', this.firstValue) if (this.firstValue === false || this.firstValue === true) this.currentValue = this.firstValue; else this.currentValue = ''; } }
Emeshka/graphytica
src/app/icon-button/icon-button.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-icon-button', templateUrl: './icon-button.component.html', styleUrls: ['./icon-button.component.css'] }) export class IconButtonComponent { constructor() { } @Input() title: string; @Input() iconSrc: string; @Input() active: any = false; @Input() callback: () => {}; isActive() { if (typeof this.active == 'function') return this.active(); else return !!this.active; } }